Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save glowinthedark/8e4cd2eee43aeda307ce7d7dffc2f414 to your computer and use it in GitHub Desktop.

Select an option

Save glowinthedark/8e4cd2eee43aeda307ce7d7dffc2f414 to your computer and use it in GitHub Desktop.
whisper_mlx_bulk_macos_apple_silicon.py
#!/usr/bin/env python3
"""
Bulk transcription via the mlx-whisper *Python API* (Apple Silicon), tuned for
maximum recognition accuracy rather than throughput.
Why this exists alongside the shell wrapper:
mlx-whisper's CLI (v0.4.2) exposes NO --beam-size, NO --patience, and no
way to supply a temperature *tuple*. `--temperature` is a bare float, so
the fallback ladder inside transcribe() is unreachable and beam search is
unreachable. The Python API forwards **decode_options straight into
DecodingOptions, which does accept beam_size / patience / best_of /
length_penalty. Everything below is only obtainable this way.
Two further wins over per-file CLI invocations:
* mlx_whisper.transcribe.ModelHolder caches the loaded model in-process
(transcribe.py:50), so an N-file batch loads weights once instead of N
times.
* cli.py:240 caches `output_name` across its own file loop, silently
overwriting every file's output with the first file's name. Not an issue
here -- naming is handled explicitly.
Usage:
./whisper-mlx-bulk.py '**/*.mp4'
./whisper-mlx-bulk.py '*.m4a' --language en --initial-prompt "Kubernetes, etcd, CRDs."
"""
from __future__ import annotations
import argparse
import os
import platform
import shutil
import sys
import traceback
from pathlib import Path
ALL_EXTS = ("srt", "vtt", "txt", "tsv", "json")
SKIP_INPUT_SUFFIXES = {f".{e}" for e in ALL_EXTS} | {".md", ".log", ".py", ".sh"}
DEFAULT_MODEL = "mlx-community/whisper-large-v3-mlx"
# --------------------------------------------------------------------------- #
# preflight
# --------------------------------------------------------------------------- #
MLX_INSTALL_HELP = """\
ERROR: `mlx_whisper` is not importable.
mlx-whisper requires macOS on Apple Silicon. It will not run on Intel Macs,
Linux, or Windows -- use the openai-whisper script there instead.
Install as uv tool (recommended -- isolated, no venv to manage):
uv tool install mlx-whisper
Install with uv (into existing project with project.toml):
uv add mlx-whisper
uv run ./whisper-mlx-bulk.py '*.mp4'
in a venv with no project:
uv venv && source .venv/bin/activate
uv pip install mlx-whisper
run with inline dependency resolution, no venv (one off):
uv run --with mlx-whisper ./whisper-mlx-bulk.py '*.mp4'
Install with pip:
python3 -m venv ~/.venvs/mlx-whisper
source ~/.venvs/mlx-whisper/bin/activate
python3 -m pip install --upgrade pip
python3 -m pip install mlx-whisper
A bare `pip install mlx-whisper` against a Homebrew or system Python will
likely fail with "externally-managed-environment" (PEP 668). Use the venv
above rather than reaching for --break-system-packages.
Upgrade:
uv pip install --upgrade mlx-whisper # or: pip install --upgrade ...
First run downloads weights from Hugging Face to ~/.cache/huggingface
(large-v3 is roughly 3 GB). Pre-fetch with:
uv pip install huggingface_hub
hf download mlx-community/whisper-large-v3-mlx
"""
FFMPEG_INSTALL_HELP = """\
ERROR: `ffmpeg` was not found on PATH.
mlx-whisper shells out to ffmpeg to decode audio; nothing works without it.
brew install ffmpeg
...or, without Homebrew:
port install ffmpeg # MacPorts
conda install -c conda-forge ffmpeg
The PyPI packages named `ffmpeg` / `ffmpeg-python` are Python bindings, NOT
the binary. Installing them will not fix this.
"""
def preflight() -> None:
if platform.system() != "Darwin" or platform.machine() != "arm64":
print(
f"ERROR: mlx-whisper requires macOS/arm64; this is "
f"{platform.system()}/{platform.machine()}.",
file=sys.stderr,
)
sys.exit(2)
if shutil.which("ffmpeg") is None:
print(FFMPEG_INSTALL_HELP, file=sys.stderr)
sys.exit(127)
# --------------------------------------------------------------------------- #
# discovery / naming
# --------------------------------------------------------------------------- #
def expand_pattern(pattern: str) -> list[Path]:
p = Path(pattern)
if p.is_absolute():
anchor = Path(p.anchor)
matches = anchor.glob(str(p.relative_to(anchor)))
else:
matches = Path(".").glob(pattern)
return sorted(
m
for m in matches
if m.is_file() and m.suffix.lower() not in SKIP_INPUT_SUFFIXES
)
def outputs_for(audio: Path, formats: list[str]) -> list[Path]:
stem = os.path.splitext(audio.name)[0]
return [audio.parent / f"{stem}.{ext}" for ext in formats]
def writer_output_name(audio: Path) -> str:
"""
mlx_whisper.writers.ResultWriter does:
(output_dir / output_name).with_suffix(f".{ext}")
with_suffix() replaces the last dot-segment, so a stem containing dots gets
TRUNCATED: "lecture.part1" -> "lecture.srt", and lecture.part1/part2 then
collide and overwrite each other. Appending a throwaway extension gives
with_suffix() something disposable to eat, preserving the real stem.
"""
return os.path.splitext(audio.name)[0] + ".x"
# --------------------------------------------------------------------------- #
# args
# --------------------------------------------------------------------------- #
def parse_args(argv: list[str]) -> argparse.Namespace:
ap = argparse.ArgumentParser(
description="Accuracy-tuned bulk transcription via mlx-whisper.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
epilog="Quote the pattern, or the shell expands it before argv[1].",
)
ap.add_argument("pattern", help="glob, e.g. '*.mp4' or '**/*.m4a'")
ap.add_argument("--model", default=DEFAULT_MODEL)
ap.add_argument(
"--language",
default=None,
help="ISO code, e.g. en. Pinning it removes first-window "
"language-detection error, a common source of whole-file garbage.",
)
ap.add_argument(
"--initial-prompt",
default=None,
help="Domain vocabulary / style primer for the first window, e.g. "
"proper nouns and jargon. One of the highest-leverage accuracy knobs.",
)
ap.add_argument(
"--formats",
default="srt,vtt,txt,tsv,json",
help=f"comma-separated subset of {','.join(ALL_EXTS)}, or 'all'",
)
q = ap.add_argument_group("decoding quality (unreachable via the mlx CLI)")
q.add_argument("--beam-size", type=int, default=5)
q.add_argument(
"--patience",
type=float,
default=1.0,
help="beam-search patience (arXiv:2204.05424); >1 explores longer",
)
q.add_argument("--best-of", type=int, default=5, help="samples per t>0 fallback")
q.add_argument(
"--length-penalty",
type=float,
default=None,
help="alpha in [0,1]. None = length normalisation. NEVER set 0.0: it "
"makes ranking use raw summed logprob, which truncates output.",
)
q.add_argument("--logprob-threshold", type=float, default=-1.0)
q.add_argument("--compression-ratio-threshold", type=float, default=2.4)
q.add_argument("--no-speech-threshold", type=float, default=0.6)
q.add_argument(
"--hallucination-silence-threshold",
type=float,
default=2.0,
help="seconds; inert unless word timestamps are on (they are)",
)
q.add_argument(
"--no-context",
action="store_true",
help="disable condition_on_previous_text. Costs cross-window "
"coherence, punctuation and proper-noun consistency; use only if the "
"audio provokes repetition loops the temperature ladder cannot break.",
)
q.add_argument(
"--dtype",
default="fp16",
choices=("fp16", "fp32"),
help="fp32 roughly doubles memory and time for marginal gain",
)
s = ap.add_argument_group("subtitle layout")
s.add_argument(
"--max-line-width",
type=int,
default=None,
help="Only takes effect together with --max-line-count. Setting BOTH "
"discards model segment boundaries and recuts cues by character "
"count, breaking sentences mid-clause. Leave unset for translation.",
)
s.add_argument("--max-line-count", type=int, default=None)
s.add_argument("--highlight-words", action="store_true", help="karaoke <u> cues")
ap.add_argument("--overwrite", action="store_true")
ap.add_argument(
"--verbose", default="progress", choices=("off", "progress", "segments")
)
return ap.parse_args(argv)
# --------------------------------------------------------------------------- #
# main
# --------------------------------------------------------------------------- #
def main(argv: list[str]) -> int:
args = parse_args(argv)
formats = (
list(ALL_EXTS)
if args.formats.strip() == "all"
else [f.strip().lower() for f in args.formats.split(",") if f.strip()]
)
if bad := [f for f in formats if f not in ALL_EXTS]:
print(f"unknown format(s): {', '.join(bad)}", file=sys.stderr)
return 2
if args.length_penalty == 0.0:
print(
"refusing --length-penalty 0.0: it passes the 0<=alpha<=1 validator "
"but ranks candidates by raw summed logprob, systematically "
"selecting truncated transcriptions. Use None or 1.0.",
file=sys.stderr,
)
return 2
if (args.max_line_width is None) != (args.max_line_count is None):
print(
"note: max_line_width and max_line_count only take effect together; "
"segment boundaries will be preserved.",
file=sys.stderr,
)
if args.highlight_words and (
args.max_line_width is None or args.max_line_count is None
):
print(
"note: --highlight-words has no effect without both --max-line-*.",
file=sys.stderr,
)
preflight()
files = expand_pattern(args.pattern)
if not files:
print(f"no files matched {args.pattern!r} (did you quote it?)", file=sys.stderr)
return 1
pending = [
f
for f in files
if args.overwrite or not all(o.exists() for o in outputs_for(f, formats))
]
for f in files:
if f not in pending:
print(f" skip (complete): {f}")
print(f"{len(files)} matched, {len(pending)} to process.")
if not pending:
return 0
try:
import mlx_whisper
from mlx_whisper.writers import get_writer
except ImportError:
print(MLX_INSTALL_HELP, file=sys.stderr)
return 127
verbose = {"off": None, "progress": False, "segments": True}[args.verbose]
writer_options = {
"max_line_width": args.max_line_width,
"max_line_count": args.max_line_count,
"highlight_words": args.highlight_words,
}
# Assembled once; ModelHolder keeps the weights resident across the batch.
decode_kwargs = dict(
path_or_hf_repo=args.model,
task="transcribe",
language=args.language,
initial_prompt=args.initial_prompt,
# Full fallback ladder. The CLI cannot express this -- its
# --temperature is a single float, which collapses the loop to one
# pass and (for any value > 0) also discards beam_size and patience.
temperature=(0.0, 0.2, 0.4, 0.6, 0.8, 1.0),
# Applied at t == 0 only; best_of is applied at t > 0 only.
beam_size=args.beam_size,
patience=args.patience,
best_of=args.best_of,
length_penalty=args.length_penalty,
compression_ratio_threshold=args.compression_ratio_threshold,
logprob_threshold=args.logprob_threshold,
no_speech_threshold=args.no_speech_threshold,
condition_on_previous_text=not args.no_context,
# Prerequisite for hallucination_silence_threshold and for accurate
# cue boundaries. Does not produce per-word cues by itself.
word_timestamps=True,
hallucination_silence_threshold=args.hallucination_silence_threshold,
fp16=(args.dtype == "fp16"),
verbose=verbose,
)
print(
f"model={args.model} dtype={args.dtype} beam={args.beam_size} "
f"best_of={args.best_of} lang={args.language or 'auto'}",
flush=True,
)
failures: list[tuple[Path, str]] = []
for i, audio in enumerate(pending, 1):
print(f"\n[{i}/{len(pending)}] {audio}", flush=True)
try:
result = mlx_whisper.transcribe(str(audio), **decode_kwargs)
except KeyboardInterrupt:
print("\ninterrupted", file=sys.stderr)
return 130
except Exception:
traceback.print_exc()
failures.append((audio, "transcribe"))
continue
try:
name = writer_output_name(audio)
for ext in formats:
get_writer(ext, str(audio.parent))(result, name, writer_options)
except Exception:
traceback.print_exc()
failures.append((audio, "write"))
continue
detected = result.get("language", "?")
print(
f" ok [{detected}] -> "
f"{', '.join(o.name for o in outputs_for(audio, formats))}"
)
if failures:
print(f"\n{len(failures)} failure(s):", file=sys.stderr)
for path, stage in failures:
print(f" [{stage}] {path}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment