Building Voice and Multimodal AI Applications / Start Here

Set Up Python and the Speech Models

Lesson 2 of 37. Open to read. No account needed.

Before anything can listen or speak, your computer needs the right Python, the course's libraries at versions known to work together, and the speech models on disk. In this lesson you create the practice folder that the whole course uses, install everything into its own environment, download and verify the models, and run a check that proves the pieces work together by having one model speak a sentence and another write it down.

When you finish you will have this layout:

~/voice-practice/
  .venv/                  the course's Python environment (about 300 MB)
  models/
    whisper-base.en/      speech-to-text model, 145 MB
    whisper-small.en/     larger speech-to-text model, 484 MB
    kokoro/               text-to-speech model and voices, 120 MB
    espeak-ng-data/       pronunciation data, copied to a short path
  data/                   generated clips and samples (later lessons)
  setup/                  this lesson's files

~ means your home folder: /Users/yourname on macOS, /home/yourname on Linux and C:\Users\yourname on Windows. Plan for about 1.1 GB of downloads and 20 to 30 minutes on a typical connection.

Before You Start

You need a terminal, a plain-text editor and the ability to run a Python script, as described in the course prerequisites. Nothing else is assumed.

Check which Python you have. On macOS or Linux:

python3 --version

On Windows (PowerShell), the Python launcher lists installed versions:

py --list

The course needs Python 3.12 or 3.13. Python 3.14 and 3.15 are not yet supported, because some speech libraries do not publish ready-built packages for them: kokoro-onnx declares support only below 3.14, and onnxruntime and CTranslate2 publish no packages for 3.15 yet (S12, S13, S17). If you need to install Python, use the installers at python.org on Windows and macOS; on Linux use your distribution's packages (S37). On Debian and Ubuntu the venv module is a separate package, usually python3.13-venv or python3-venv, which you may need to install first.

Hardware: macOS 14 or later on Apple silicon, Windows 10 22H2 or 11 on an x64 processor, or 64-bit Linux. Intel Macs and Windows on Arm cannot run this course's speech libraries, because onnxruntime publishes its macOS package only for Apple silicon and CTranslate2 has no Windows on Arm package (S12, S13).

Step 1: Create the Practice Folder and an Environment

An environment (a "virtual environment", created by Python's venv module) is a folder with its own copy of the Python interpreter and its own installed libraries. Installing the course libraries there keeps them apart from anything else on your computer, so the course cannot break another project and another project cannot change the course's versions (S66).

On macOS or Linux (use python3.12 instead if that is what you have):

mkdir -p ~/voice-practice/setup
cd ~/voice-practice
python3.13 -m venv .venv
.venv/bin/python -m pip --version

On Windows (PowerShell; use -3.12 if that is what you have):

New-Item -ItemType Directory -Force "$HOME\voice-practice\setup"
Set-Location "$HOME\voice-practice"
py -3.13 -m venv .venv
.venv\Scripts\python.exe -m pip --version

The last command should print a path inside voice-practice/.venv. That is how you know you are using the environment's Python and not another one. The course never asks you to "activate" the environment: every command names its Python directly, ~/voice-practice/.venv/bin/python on macOS and Linux and ~\voice-practice\.venv\Scripts\python.exe on Windows. That is longer to type but impossible to get wrong in a new terminal.

Step 2: Install the Course Libraries

Save this file as requirements.txt in ~/voice-practice/setup:

# Building Voice and Multimodal AI Applications: course libraries.
# Exact versions, tested together on Python 3.12 and 3.13.
numpy==2.5.4
soundfile==0.14.0
sounddevice==0.5.6
faster-whisper==1.2.1
ctranslate2==4.8.3
onnxruntime==1.31.0
# PyAV 19 removed an option that faster-whisper 1.2.1 still uses.
av==18.1.0
kokoro-onnx==0.6.1
jiwer==4.0.0
pillow==13.0.0
pypdfium2==5.14.0
httpx==0.28.1
pydantic==2.14.1
fastapi==0.142.2
uvicorn==0.54.0
websockets==17.2
python-multipart==0.0.32
pytest==9.1.1

Every library is pinned to an exact version (==), the set that was installed and tested together for this course. Three pins prevent problems the course has already met:

  • av==18.1.0. PyAV decodes audio files for faster-whisper. PyAV 19 removed an option that faster-whisper 1.2.1 still passes, so with PyAV 19 every attempt to transcribe a file fails with a TypeError. faster-whisper only asks for "PyAV 11 or later", so without this pin pip would install the broken combination (S11, S14).
  • onnxruntime and ctranslate2. These two engines run the speech models and determine which Python versions and processors the course supports (S12, S13).
  • numpy==2.5.4. It needs Python 3.12 or later, which is one reason older Pythons are not supported (S26).

The other libraries come into use later: jiwer scores transcripts, pillow and pypdfium2 handle images and documents, httpx and pydantic talk to the local language model, fastapi, uvicorn, websockets and python-multipart serve the web page, and pytest runs tests.

Install them from the setup folder. On macOS or Linux:

cd ~/voice-practice/setup
../.venv/bin/python -m pip install --only-binary=:all: -r requirements.txt
../.venv/bin/python -m pip check

On Windows:

Set-Location "$HOME\voice-practice\setup"
..\.venv\Scripts\python.exe -m pip install --only-binary=:all: -r requirements.txt
..\.venv\Scripts\python.exe -m pip check

--only-binary=:all: tells pip to use only ready-built packages ("wheels") and never to compile anything from source. Every package in the list has wheels for the supported systems, so if pip cannot find one, it stops with a clear "no matching distribution" error instead of trying, and failing, to compile. pip check then confirms that no installed package conflicts with another.

What success looks like (illustrative, from the author's run on macOS with Python 3.13.0; the list is shortened here):

Successfully installed annotated-doc-0.0.5 annotated-types-0.8.0 anyio-4.15.1 ... websockets-17.2
No broken requirements found.

The author's install took about 13 minutes on a slow connection; most of it was downloading about 300 MB.

Step 3: Download and Verify the Speech Models

Save this as download_models.py in ~/voice-practice/setup:

"""Download the course's speech models into ~/voice-practice/models and check them.

Downloads two Whisper models (from SYSTRAN's Hugging Face repositories, at
fixed revisions) and the Kokoro model and voices (from the kokoro-onnx
releases on GitHub), checks every file against the SHA-256 fingerprint
recorded when the course was tested, and copies espeak-ng's data folder to a
short path. Files that are already present and correct are skipped, so it is
safe to run again after an interruption.
"""

import hashlib
import shutil
import sys
import urllib.request
from pathlib import Path

import espeakng_loader

MODELS = Path.home() / "voice-practice" / "models"

WHISPER_URL = "https://huggingface.co/Systran/faster-whisper-{name}/resolve/{revision}/{file}"
WHISPER_REVISIONS = {
    "base.en": "3d3d5dee26484f91867d81cb899cfcf72b96be6c",
    "small.en": "d1d751a5f8271d482d14ca55d9e2deeebbae577f",
}
KOKORO_URL = "https://github.com/thewh1teagle/kokoro-onnx/releases/download/model-files-v1.0/{file}"

# Destination (inside MODELS) -> SHA-256 recorded when the course was tested.
EXPECTED = {
    "whisper-base.en/config.json": "f3bc3821e9fc76a27bae538e11ae5b677dcdd352b4600429ce7951d398569aeb",
    "whisper-base.en/model.bin": "2a166925539a16005f14ff328359f9b9adb9dc4fb631bb3b227526862e93e2ef",
    "whisper-base.en/tokenizer.json": "929c5252409436dce1b38a75d1abbcb5e132d170d8e324e4e04ed915fa2d22df",
    "whisper-base.en/vocabulary.txt": "ff77588746d3a2595d32ab5b69ffd7b95ce2441ac57533cb66fc3eb575a115cf",
    "whisper-small.en/config.json": "666a9605530ac1f61fa8177f3702b4dacec9966749e42610839fcc32661d5fae",
    "whisper-small.en/model.bin": "62b2a45b05ee59acb4a5341b33ee35e041395d378d418a18acfe4c9e768ee37a",
    "whisper-small.en/tokenizer.json": "929c5252409436dce1b38a75d1abbcb5e132d170d8e324e4e04ed915fa2d22df",
    "whisper-small.en/vocabulary.txt": "ff77588746d3a2595d32ab5b69ffd7b95ce2441ac57533cb66fc3eb575a115cf",
    "kokoro/kokoro-v1.0.int8.onnx": "6e742170d309016e5891a994e1ce1559c702a2ccd0075e67ef7157974f6406cb",
    "kokoro/voices-v1.0.bin": "bca610b8308e8d99f32e6fe4197e7ec01679264efed0cac9140fe9c29f1fbf7d",
}


def url_for(destination: str) -> str:
    folder, file = destination.split("/")
    if folder.startswith("whisper-"):
        name = folder.removeprefix("whisper-")
        return WHISPER_URL.format(name=name, revision=WHISPER_REVISIONS[name], file=file)
    return KOKORO_URL.format(file=file)


def sha256(path: Path) -> str:
    digest = hashlib.sha256()
    with path.open("rb") as f:
        for block in iter(lambda: f.read(1 << 20), b""):
            digest.update(block)
    return digest.hexdigest()


def download(url: str, target: Path) -> None:
    partial = target.with_name(target.name + ".part")
    with urllib.request.urlopen(url, timeout=60) as response, partial.open("wb") as out:
        total = int(response.headers.get("Content-Length", 0))
        done, next_report = 0, 0.1
        for block in iter(lambda: response.read(1 << 20), b""):
            out.write(block)
            done += len(block)
            if total and done / total >= next_report:
                print(f"    {done / total:4.0%} of {total / 1e6:.0f} MB", flush=True)
                next_report += 0.1
    partial.replace(target)


def main() -> None:
    failures = 0
    for destination, expected in EXPECTED.items():
        target = MODELS / destination
        target.parent.mkdir(parents=True, exist_ok=True)
        if target.exists() and sha256(target) == expected:
            print(f"ok (already present)  {destination}")
            continue
        print(f"downloading           {destination}", flush=True)
        try:
            download(url_for(destination), target)
        except OSError as exc:
            print(f"FAILED to download    {destination}: {exc}")
            failures += 1
            continue
        if sha256(target) == expected:
            print(f"ok (checked)          {destination}")
        else:
            print(f"FAILED check          {destination}: the file differs from the tested one; it was deleted")
            target.unlink()
            failures += 1

    # espeak-ng cannot use a data folder whose full path is 160 characters or
    # longer, so the course keeps its own copy at a short path.
    espeak = MODELS / "espeak-ng-data"
    if not espeak.is_dir():
        shutil.copytree(espeakng_loader.get_data_path(), espeak)
    length = len(str(espeak.resolve()))
    print(f"espeak-ng data        {espeak} ({length} characters)")
    if length >= 160:
        print("FAILED: that path is too long for espeak-ng; see the lesson's troubleshooting table")
        failures += 1

    if failures:
        sys.exit(f"{failures} problem(s); fix them and run this script again")
    print("all speech models are in place")


if __name__ == "__main__":
    main()

How it works:

  • Where the files come from. The Whisper models are SYSTRAN's conversions of OpenAI's Whisper models for faster-whisper, released under the MIT licence (S15). Each URL names a fixed revision, a particular version of the repository, so you get exactly the files the course was tested with even if the repository changes later. The Kokoro model and voices come from the kokoro-onnx project's release page; the model and voices are licensed Apache 2.0 (S18).
  • EXPECTED. For every file, the SHA-256 fingerprint recorded when the course was tested. A fingerprint is a short value computed from every byte of a file; if even one byte differs, the fingerprint is completely different. Checking it proves the file arrived complete and unchanged.
  • download(). Writes to a .part file and renames it only when the download finishes, so an interrupted download never leaves a file that looks complete. It prints progress every 10 %.
  • The main loop. Skips files that are already present with the right fingerprint, downloads the rest, checks each one and deletes any that does not match, so you can always simply run the script again.
  • The espeak-ng copy. Kokoro uses espeak-ng, a pronunciation program that is bundled with kokoro-onnx and licensed GPL-3.0 (S40). The bundled copy stops with a confusing "Error processing file" message if the full path of its data folder is 160 characters or longer. Inside an environment that path is long, so the script copies the folder to ~/voice-practice/models/espeak-ng-data, prints the new path's length, and fails clearly if even that is too long.

Run it (it uses the network and writes about 760 MB into models):

../.venv/bin/python download_models.py

On Windows: ..\.venv\Scripts\python.exe download_models.py.

Illustrative output (progress lines removed; your output shows your full home folder where this shows ~):

downloading           whisper-base.en/config.json
ok (checked)          whisper-base.en/config.json
downloading           whisper-base.en/model.bin
ok (checked)          whisper-base.en/model.bin
...
downloading           kokoro/voices-v1.0.bin
ok (checked)          kokoro/voices-v1.0.bin
espeak-ng data        ~/voice-practice/models/espeak-ng-data (141 characters)
all speech models are in place

Every file must say ok. Run the script a second time and every line says ok (already present). If a download is interrupted, run it again; it continues with whatever is missing.

Step 4: Check That Everything Works Together

Save this as check_setup.py in ~/voice-practice/setup:

"""Check that the course environment and speech models work together.

Prints one line per check and ends with a summary. It writes one short WAV
file, ~/voice-practice/data/setup-check.wav, and reads nothing from the
network.
"""

import platform
import sys
from importlib import metadata
from pathlib import Path

PRACTICE = Path.home() / "voice-practice"
MODELS = PRACTICE / "models"
PINS = {"numpy": "2.5.4", "faster-whisper": "1.2.1", "ctranslate2": "4.8.3", "onnxruntime": "1.31.0",
        "av": "18.1.0", "kokoro-onnx": "0.6.1", "soundfile": "0.14.0", "sounddevice": "0.5.6"}

results = []


def check(name: str, ok: bool, detail: str) -> bool:
    results.append(ok)
    print(f"{'PASS' if ok else 'FAIL'}  {name:22} {detail}")
    return ok


def main() -> None:
    version = platform.python_version()
    check("Python", sys.version_info[:2] in ((3, 12), (3, 13)), f"{version} at {sys.executable}")
    check("course environment", sys.prefix != sys.base_prefix and Path(sys.prefix) == PRACTICE / ".venv",
          f"running inside {sys.prefix}")

    for package, pinned in PINS.items():
        try:
            installed = metadata.version(package)
        except metadata.PackageNotFoundError:
            installed = "not installed"
        check(package, installed == pinned, f"{installed} (course pin {pinned})")

    for folder in ("whisper-base.en", "whisper-small.en", "kokoro", "espeak-ng-data"):
        check(f"models/{folder}", (MODELS / folder).is_dir(), str(MODELS / folder))
    espeak_length = len(str((MODELS / "espeak-ng-data").resolve()))
    check("espeak-ng path length", espeak_length < 160, f"{espeak_length} characters (must be under 160)")

    try:
        import sounddevice
        check("PortAudio", True, sounddevice.get_portaudio_version()[1])
    except ImportError:
        check("PortAudio", False, "sounddevice is not installed in this Python")
    except OSError as exc:  # Linux without the libportaudio2 package
        check("PortAudio", False, f"{exc} (only needed for microphone and playback)")

    if all(results):
        round_trip()
    print(f"\n{sum(results)} of {len(results)} checks passed")
    if not all(results):
        sys.exit(1)


def round_trip() -> None:
    """Synthesise a sentence with Kokoro and transcribe it with Whisper."""
    import soundfile as sf
    from faster_whisper import WhisperModel
    from kokoro_onnx import EspeakConfig, Kokoro

    kokoro = Kokoro(str(MODELS / "kokoro" / "kokoro-v1.0.int8.onnx"), str(MODELS / "kokoro" / "voices-v1.0.bin"),
                    espeak_config=EspeakConfig(data_path=str(MODELS / "espeak-ng-data")))
    samples, rate = kokoro.create("The voice practice folder is ready.", voice="af_heart", lang="en-us")
    wav = PRACTICE / "data" / "setup-check.wav"
    wav.parent.mkdir(parents=True, exist_ok=True)
    sf.write(wav, samples, rate, subtype="PCM_16")
    check("speech synthesis", len(samples) > rate, f"{len(samples) / rate:.2f} s at {rate} Hz written to {wav.name}")

    model = WhisperModel(str(MODELS / "whisper-base.en"), device="cpu", compute_type="int8")
    segments, _ = model.transcribe(str(wav), language="en")
    text = " ".join(s.text.strip() for s in segments)
    check("speech recognition", "ready" in text.lower(), repr(text))


if __name__ == "__main__":
    main()

What it checks, in order:

  • Python and the environment. The version must be 3.12 or 3.13, and sys.prefix (the folder of the Python that is running) must be ~/voice-practice/.venv. If you run the script with another Python, this is the first thing that fails.
  • Pinned versions. importlib.metadata reads the installed version of each key library and compares it with the course pin.
  • Model folders and the espeak-ng path length.
  • PortAudio, the sound library behind sounddevice. It is included on macOS and Windows; on Linux it is a system package such as libportaudio2 (S24). It is needed only for the optional microphone and playback steps, but the check reports it now.
  • A round trip, only if everything else passed: Kokoro speaks a sentence into ~/voice-practice/data/setup-check.wav, and the base.en Whisper model writes it down again. If the transcript contains "ready", both models, the audio libraries and the file decoding all work.

Run it:

../.venv/bin/python check_setup.py

Illustrative output from the author's run:

PASS  Python                 3.13.0 at ~/voice-practice/.venv/bin/python
PASS  course environment     running inside ~/voice-practice/.venv
PASS  numpy                  2.5.4 (course pin 2.5.4)
PASS  faster-whisper         1.2.1 (course pin 1.2.1)
PASS  ctranslate2            4.8.3 (course pin 4.8.3)
PASS  onnxruntime            1.31.0 (course pin 1.31.0)
PASS  av                     18.1.0 (course pin 18.1.0)
PASS  kokoro-onnx            0.6.1 (course pin 0.6.1)
PASS  soundfile              0.14.0 (course pin 0.14.0)
PASS  sounddevice            0.5.6 (course pin 0.5.6)
PASS  models/whisper-base.en ~/voice-practice/models/whisper-base.en
PASS  models/whisper-small.en ~/voice-practice/models/whisper-small.en
PASS  models/kokoro          ~/voice-practice/models/kokoro
PASS  models/espeak-ng-data  ~/voice-practice/models/espeak-ng-data
PASS  espeak-ng path length  141 characters (must be under 160)
PASS  PortAudio              PortAudio V19.7.0-devel, revision unknown
PASS  speech synthesis       1.88 s at 24000 Hz written to setup-check.wav
PASS  speech recognition     'The voice practice folder is ready.'

18 of 18 checks passed

The round trip took about a minute on the author's busy computer, most of it loading the two models for the first time.

When Something Goes Wrong

What you seeLikely causeSafe next check
No matching distribution found during installPython 3.14 or 3.15, an Intel Mac or Windows on Arm, or a typing mistake in requirements.txt.venv/bin/python --version; compare your file with the lesson's
No module named venv or ensurepip is not available (Linux)The venv package is not installedInstall python3.13-venv (or python3-venv) with your package manager
FAILED to downloadNetwork problem or a blocked siteRun the script again; check that huggingface.co and github.com open in a browser
FAILED check ... differs from the tested oneA damaged or changed downloadRun again; it was deleted and will be fetched afresh
FAIL course environment and several not installed linesYou ran the check with a different PythonUse the environment's Python exactly as shown
FAIL espeak-ng path lengthYour home folder path is very longAsk your administrator or create the practice folder on a shorter path, and adjust the paths in the scripts consistently
FAIL PortAudio (Linux)libportaudio2 is missingInstall it with your package manager; only the optional recording and playback steps need it
FAIL speech recognition with an unexpected transcriptA model file or library version is wrongRerun download_models.py and check every pin line above it

Your Turn: Predict the Failure

Checks are only useful if you know what their failures look like.

Task. Rename ~/voice-practice/models/whisper-small.en to whisper-small.en.off. Before running anything, write down which lines of check_setup.py will fail and whether the round trip will run. Then run check_setup.py, compare, and rename the folder back. Finally, run download_models.py and explain what it does when the folder is back.

Success: your prediction matches, the folder is restored, and a final check_setup.py run shows 18 of 18 checks passed.

Answer and Reasoning

Only one line fails: FAIL models/whisper-small.en. Everything before it still passes, and because the round trip runs only when every earlier check passes, the synthesis and recognition lines do not appear at all. The summary reads 15 of 16 checks passed and the script exits with an error (exit status 1), which matters when another script runs it.

After you rename the folder back, download_models.py reports every file as ok (already present): it compares fingerprints rather than trusting the files' presence, so it fetches nothing. Had you renamed it and then run the downloader first, it would have downloaded small.en again into a new folder, leaving the renamed copy behind. That is why the course checks before it repairs.

Reset and Cleanup

Keep ~/voice-practice: every later lesson uses it. To start this lesson again from nothing, delete ~/voice-practice/.venv and ~/voice-practice/models and repeat the steps. Nothing outside ~/voice-practice was changed, and the only network use was installing packages and downloading the models.

References

  • Library versions, licences and supported platforms (S11 to S14, S17, S24, S26)
  • Model sources and licences (S15, S18); espeak-ng licence (S40)
  • Python releases and the venv module (S37, S66)

32 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy