Transcribe your first recording with Python

You have a recording in Mandarin and want searchable, copyable text. You do not need to build a server or train a model first. This tutorial does one job: run Python on your computer and save a short recording's transcript to a file.

Start with the official example WAV and produce transcript.json. Then substitute a recording you are authorized to process. The route is: prepare Python → install the tools → prepare the audio and model → transcribe → inspect the result while listening to the audio.

This path is deliberately limited to Mandarin, CPU execution, and one WAV lasting at most 30 seconds. That is a tutorial guardrail, not a universal FunASR limit. This example produces text, not automatically timed subtitles, verified names, speaker identities, or guaranteed realtime performance.

1. Understand the toolkit, model, and application

Automatic speech recognition (ASR) converts spoken words into text. You need both software that loads files and coordinates computation, and a model that has learned to recognize speech.

You do not need to learn fine-tuning or GPU optimization to complete a first transcript. Add capabilities later, when you know whether your next task needs subtitles, meeting notes, or live interaction.

2. What you need before starting

The commands below choose Linux x86_64, Python 3.11, and CPU. You need a terminal, permission to create a working directory, and network access for the initial software and model downloads. This CPU path does not require CUDA. Speed and memory use depend on the model and your machine; realtime processing is not promised.

For Windows, macOS, or an existing GPU environment, first use the installation guide to select the appropriate PyTorch build. Do not mix these Linux CPU commands into an unrelated environment. Model downloads also require a writable cache and adequate disk space. An installed Python package does not mean the weights are ready.

3. Create an isolated environment and install

A virtual environment is a separate toolbox for this exercise. It reduces conflicts with other projects. Run these commands in order in your terminal:

mkdir first-transcript
cd first-transcript
python3.11 -m venv .venv
. .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install "torch==2.8.0" "torchaudio==2.8.0" --index-url https://download.pytorch.org/whl/cpu
python -m pip install "funasr==1.4.26"
python -m pip check
python -c "import sys, funasr, torch, torchaudio; from funasr import AutoModel; print(sys.executable); print(funasr.__version__, funasr.__file__); print(torch.__version__, torchaudio.__version__)"
python -m pip freeze > environment.txt

This pins FunASR 1.4.26 and pairs torch/torchaudio 2.8.0 using the official PyTorch version instructions. It does not lock the whole dependency graph, so retain environment.txt for troubleshooting. The checks should report FunASR 1.4.26 and the Python executable inside your new .venv. Importing successfully is an environment check, not a successful transcription.

4. Begin with the example audio

Download the Mandarin WAV linked by the official tutorial. This command downloads audio; it does not upload your recording:

curl --fail --location --output sample.wav https://isv-data.oss-cn-hangzhou.aliyuncs.com/ics/MaaS/ASR/test_audio/asr_example_zh.wav

WAV is an audio container. A 16 kHz sample rate means 16000 samples per second, and mono means one audio channel. The script accepts only mono, 16000 Hz, 16-bit PCM WAV. Renaming an MP3 file to .wav does not convert it.

For your own audio, choose a short, clearly spoken Mandarin recording that you may process. If conversion is needed, an already-installed FFmpeg can produce a separate file while retaining the original:

ffmpeg -n -i my-recording.mp3 -ac 1 -ar 16000 -c:a pcm_s16le my-recording-16k.wav

Replace my-recording.mp3 with your real path. -n refuses to overwrite existing output. Format conversion does not shorten a whole recording: choose an input of at most 30 seconds. Play it before running recognition so that a file problem is not mistaken for a model problem.

5. Run the complete transcription script

Put this complete code in transcribe_first.py inside your working directory. You do not need to understand every line yet: the first part checks files, AutoModel(...) loads the model, generate(...) performs recognition, and the final part saves JSON. Invalid input stops before a large model is downloaded.

import argparse
import json
from pathlib import Path
import wave

MODEL_ID = "iic/speech_seaco_paraformer_large_asr_nat-zh-cn-16k-common-vocab8404-pytorch"


def main(argv=None):
    parser = argparse.ArgumentParser(description="One short Mandarin WAV to one JSON transcript")
    parser.add_argument("--audio", required=True)
    parser.add_argument("--output", default="transcript.json")
    source = parser.add_mutually_exclusive_group(required=True)
    source.add_argument("--model-dir")
    source.add_argument("--allow-download", action="store_true")
    args = parser.parse_args(argv)

    audio = Path(args.audio).expanduser().resolve(strict=True)
    output = Path(args.output).expanduser().resolve()
    if not audio.is_file():
        parser.error("--audio must be a local WAV file")
    if output.exists() or not output.parent.is_dir():
        parser.error("Choose a new output file in an existing directory")
    with wave.open(str(audio), "rb") as wav:
        if (wav.getnchannels(), wav.getsampwidth(), wav.getframerate(), wav.getcomptype()) != (1, 2, 16000, "NONE"):
            parser.error("Expected mono, 16-bit PCM WAV at 16000 Hz")
        frames = wav.getnframes()
        duration = frames / 16000
        if not 0 < duration <= 30:
            parser.error("This first example accepts more than 0 and at most 30 seconds")
        if len(wav.readframes(frames)) != frames * 2:
            parser.error("WAV data is truncated")

    model_source = MODEL_ID
    if args.model_dir:
        directory = Path(args.model_dir).expanduser().resolve(strict=True)
        if not directory.is_dir():
            parser.error("--model-dir must be a complete local model directory")
        model_source = str(directory)

    from funasr import AutoModel, __version__

    model = AutoModel(
        model=model_source, hub="ms", device="cpu", ncpu=4,
        disable_update=True, trust_remote_code=False,
    )
    results = model.generate(input=str(audio), batch_size=1)
    if not isinstance(results, list) or len(results) != 1 or not isinstance(results[0], dict):
        raise RuntimeError("Expected one result dictionary; inspect the model and input")
    text = results[0].get("text")
    if not isinstance(text, str) or not text.strip():
        raise RuntimeError("No non-empty transcript; listen to the input before retrying")
    record = {
        "text": text,
        "audio": str(audio),
        "duration_seconds": duration,
        "model_dir": str(model.model_path),
        "funasr_version": __version__,
    }
    with output.open("x", encoding="utf-8") as target:
        json.dump(record, target, ensure_ascii=False, indent=2)
        target.write("\n")
    print("Wrote:", output)


if __name__ == "__main__":
    main()

Before the first run, read the selected model's card and usage terms. Once its download and use are approved, run:

python transcribe_first.py --audio sample.wav --allow-download --output transcript.json

--allow-download belongs to this tutorial script, not to the general FunASR API. It permits fetching the explicitly named model from ModelScope. The first run includes download and loading time, so it is not a measurement of recognition time alone. The script does not automatically retry or silently switch models after a failure.

6. Check that the task really worked

python -m json.tool transcript.json

First confirm that the transcription command exited successfully and its newly created JSON file parses. text contains the prediction; audio records the input path; duration_seconds is in seconds; model_dir identifies the directory actually loaded; funasr_version records the running package version.

Next listen to the recording, checking names, numbers, negation, and the ending. A file proves that the program completed; agreement with the audio determines whether the text is usable. Non-empty text is not automatically a correct answer. This simple path has no punctuation model configured and does not turn text into a subtitle timeline.

To process your own recording next, reuse the JSON's model_dir value in place of /absolute/path/to/model. It must be the complete, trusted directory for the same model, not a lone weight file:

python transcribe_first.py --audio my-recording-16k.wav --model-dir /absolute/path/to/model --output my-transcript.json

A local directory avoids resolving the model ID for another download, but it is not an automatic offline guarantee. Disconnected deployment requires complete dependencies, model configuration and supporting assets, followed by a real test with outbound access disabled. disable_update=True only disables the FunASR version check. Record the full model ID, revision and file checksums for reproducibility: a model ID alone is not an immutable version.

7. Troubleshoot the layer that failed

What you seeWhat to check first
python3.11 or venv is missingInstall the corresponding interpreter and venv support first. Do not skip environment setup and continue installing packages elsewhere.
funasr is missing, or torch/torchaudio cannot importActivate .venv again, inspect the Python path and python -m pip --version, then check the paired PyTorch builds. Do not upgrade the entire environment blindly.
Missing file, invalid WAV, wrong rate, or over 30 secondsCheck the path, play the audio, and convert it or choose a short excerpt. Changing a sample-rate label is not resampling.
Model download fails or no result appearsRead the final download/error message and inspect network access, cache permissions and free disk. Fix the cause before an explicit retry; do not launch duplicate processes.
Out of memory or the operating system ends the processStop duplicate instances and check available memory and model requirements. Shorter audio reduces only part of the memory cost; model weights still need memory.
The output file already existsInspect the earlier result and choose a new output filename. Refusing to overwrite it is intentional.
Empty or incorrect textConfirm audible speech, Mandarin, channels and sample rate. Retain the error and original prediction; do not fill gaps with an expected answer or silently change the model.

Execution contract for AI agents

Treat this as a local file-processing task, not a remote transcription service API. Check authorization and files before following the same script path.

Sources and verification scope

The API and model choice follow the 1.4.26 official tutorial, model mappings, and AutoModel implementation. Parameters, input checks, call contracts, result validation and file protection are tested using a model double. This revision did not run pretrained recognition or validate end-to-end inference with the installation combination above; it makes no accuracy, speed or GPU measurement claim. Complete the first-run and listening checks in section 6 in your environment. Software licensing does not replace each model's own weight terms.

Once the short recording works, continue with segmenting long recordings and checking for missing passages before moving on to meetings or courses.