davanstrien HF Staff commited on
Commit
a53c76f
·
verified ·
1 Parent(s): 19f4824

Sync from GitHub via hub-sync

Browse files
Files changed (2) hide show
  1. README.md +29 -1
  2. buzzasr-transcribe.py +575 -0
README.md CHANGED
@@ -6,11 +6,12 @@ tags:
6
  - transcription
7
  - automatic-speech-recognition
8
  - speaker-diarization
 
9
  ---
10
 
11
  # Transcription
12
 
13
- Scripts for transcribing — and diarizing — audio files using HF Buckets and Jobs.
14
 
15
  ## Quick Start
16
 
@@ -55,6 +56,7 @@ Audio already on your machine? Mount the folder directly — `-v ./audio:/input`
55
  | `cohere-transcribe.py` | Cohere Transcribe (2B) | transformers | `.txt` | 161x RT (A100) |
56
  | `cohere-transcribe-vllm.py` | Cohere Transcribe (2B) | vLLM nightly | `.txt` | 214x RT (A100) |
57
  | `granite-turboctc-transcribe.py` | [Granite Speech 5.0 TurboCTC](https://huggingface.co/ibm-granite/granite-speech-5.0-470m-turboctc) (470M, English) | transformers (pinned `main`) | `.txt` (lowercase, no punctuation) | 594x RT wall / ~5000x GPU-only (A100); 504x RT wall (A10G) |
 
58
  | `easytranscriber-transcribe.py` | Cohere Transcribe 2B (default) or Whisper variants | [easytranscriber](https://github.com/kb-labb/easytranscriber) | JSON word timestamps (+ optional `.txt` / `.srt`) | 42.9x RT (L4) |
59
  | `moss-transcribe-diarize.py` | [MOSS-Transcribe-Diarize](https://huggingface.co/OpenMOSS-Team/MOSS-Transcribe-Diarize) (0.9B) | transformers (remote code) | JSON speaker segments `{start, end, speaker, text}` (+ optional `.txt` / `.srt`) | 3.2x RT (A10G, 74-min file) |
60
  | `moss-transcribe-diarize-server.py` | [MOSS-Transcribe-Diarize](https://huggingface.co/OpenMOSS-Team/MOSS-Transcribe-Diarize) (0.9B) | in-job sgl-omni server | JSON speaker segments (+ optional `.txt`) | 47.4x RT aggregate (A100, 6 streams) |
@@ -65,6 +67,8 @@ Audio already on your machine? Mount the folder directly — `-v ./audio:/input`
65
 
66
  **`granite-turboctc-transcribe.py`** — when you have **a lot of English audio** and want raw text fast. Encoder-only CTC (one forward pass + argmax, no autoregressive decoding), so it cannot loop or hallucinate and the GPU is essentially idle: 5 hours of 1940s radio ran in 3.2 s of GPU time on an A100 (~30x Cohere), with the job's wall time dominated by mp3 decoding and model load. Output is lowercase without punctuation or casing, and quality is a step below Cohere on hard audio (~8.5% word disagreement with Cohere's transcripts on the same episodes, no ground truth). Files are fed whole by default — block attention makes cost linear in length and a 30-min file needs ~2.5 GB — with `--chunk-seconds 30` for hour-plus files or a 24 GB card. Needs `transformers` from `main` (support landed 2026-08-25, pinned to a commit) until the next release; English only.
67
 
 
 
68
  **`easytranscriber-transcribe.py`** — when you need **word-level timestamps** (subtitles, search indexing, forced alignment). Runs VAD → ASR → wav2vec2 emissions → forced alignment. Defaults to the Cohere backend so you get the same model as the other scripts with alignment on top; swap to `--backend ct2` + a Whisper model for languages Cohere doesn't cover (e.g. Swedish via `KBLab/kb-whisper-large`).
69
 
70
  **`moss-transcribe-diarize.py`** — when you need **who said what**. Joint transcription + speaker diarization + timestamps in one generation pass (no separate ASR/diarization/alignment stages). 128k context handles up to ~90 min of audio per file internally, so files are never pre-chunked and the anonymous speaker labels (`[S01]`, `[S02]`, ...) stay consistent across the whole recording. English + Chinese; also accepts video containers (mp4, mkv, ...); supports hotword biasing for names/jargon.
@@ -89,6 +93,17 @@ Audio already on your machine? Mount the folder directly — `-v ./audio:/input`
89
  | `--decode-workers` | CPU count | Threads for mp3/wav decoding, overlapped with model load and inference |
90
  | `--max-files` | all | Limit files to process (for testing) |
91
 
 
 
 
 
 
 
 
 
 
 
 
92
  #### Options — `easytranscriber-transcribe.py`
93
 
94
  | Flag | Default | Description |
@@ -138,6 +153,19 @@ CBS Suspense (1940s radio drama), 66 episodes, 33 hours of audio.
138
  | A100-SXM4-80GB | 12.3 min | 161x realtime |
139
  | L4 | ~64s / 30 min episode | 28x realtime |
140
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  **`easytranscriber-transcribe.py`** (JSON alignments + optional .txt/.srt; VAD → ASR → wav2vec2 → forced alignment):
142
 
143
  | GPU | Time | RTFx | Output |
 
6
  - transcription
7
  - automatic-speech-recognition
8
  - speaker-diarization
9
+ - multilingual
10
  ---
11
 
12
  # Transcription
13
 
14
+ Scripts for transcribing — and diarizing — audio files using HF Buckets and Jobs. English and the major European/Asian languages via Cohere Transcribe; 102 languages via the BuzzASR monolingual Whisper fine-tunes.
15
 
16
  ## Quick Start
17
 
 
56
  | `cohere-transcribe.py` | Cohere Transcribe (2B) | transformers | `.txt` | 161x RT (A100) |
57
  | `cohere-transcribe-vllm.py` | Cohere Transcribe (2B) | vLLM nightly | `.txt` | 214x RT (A100) |
58
  | `granite-turboctc-transcribe.py` | [Granite Speech 5.0 TurboCTC](https://huggingface.co/ibm-granite/granite-speech-5.0-470m-turboctc) (470M, English) | transformers (pinned `main`) | `.txt` (lowercase, no punctuation) | 594x RT wall / ~5000x GPU-only (A100); 504x RT wall (A10G) |
59
+ | `buzzasr-transcribe.py` | [BuzzASR](https://huggingface.co/BuzzASR) (102 monolingual Whisper-large-v3 fine-tunes, 1.55B) | transformers | `.txt` (mostly lowercase, no punctuation) | 20x RT (L4, sequential) / 51x RT (L4, chunked) |
60
  | `easytranscriber-transcribe.py` | Cohere Transcribe 2B (default) or Whisper variants | [easytranscriber](https://github.com/kb-labb/easytranscriber) | JSON word timestamps (+ optional `.txt` / `.srt`) | 42.9x RT (L4) |
61
  | `moss-transcribe-diarize.py` | [MOSS-Transcribe-Diarize](https://huggingface.co/OpenMOSS-Team/MOSS-Transcribe-Diarize) (0.9B) | transformers (remote code) | JSON speaker segments `{start, end, speaker, text}` (+ optional `.txt` / `.srt`) | 3.2x RT (A10G, 74-min file) |
62
  | `moss-transcribe-diarize-server.py` | [MOSS-Transcribe-Diarize](https://huggingface.co/OpenMOSS-Team/MOSS-Transcribe-Diarize) (0.9B) | in-job sgl-omni server | JSON speaker segments (+ optional `.txt`) | 47.4x RT aggregate (A100, 6 streams) |
 
67
 
68
  **`granite-turboctc-transcribe.py`** — when you have **a lot of English audio** and want raw text fast. Encoder-only CTC (one forward pass + argmax, no autoregressive decoding), so it cannot loop or hallucinate and the GPU is essentially idle: 5 hours of 1940s radio ran in 3.2 s of GPU time on an A100 (~30x Cohere), with the job's wall time dominated by mp3 decoding and model load. Output is lowercase without punctuation or casing, and quality is a step below Cohere on hard audio (~8.5% word disagreement with Cohere's transcripts on the same episodes, no ground truth). Files are fed whole by default — block attention makes cost linear in length and a 30-min file needs ~2.5 GB — with `--chunk-seconds 30` for hour-plus files or a 24 GB card. Needs `transformers` from `main` (support landed 2026-08-25, pinned to a commit) until the next release; English only.
69
 
70
+ **`buzzasr-transcribe.py`** — when the audio is in **a language Cohere doesn't cover** (Armenian, Amharic, Georgian, Khmer, Lao, Sorani Kurdish, Wolof, Yoruba, …): one model per language for 102 FLEURS languages. [BuzzASR](https://lemn-lab.github.io/buzz-asr/) (Findings of EMNLP 2026, MIT) fine-tunes Whisper-large-v3 once per FLEURS language, with a native tokenizer for the languages Whisper's tokenizer fragments; the authors report lower CER than Whisper-large-v3 zero-shot on 89/102 languages and the lowest of any open system on 31. Pass `--language armenian` (or the ISO code `hy`) and the matching `BuzzASR/<language>` checkpoint is loaded: every card tags both the name and the code, so the recipe resolves either with a tag filter on the org at run time (no table to maintain; new languages just work). Finding a model by hand is the same one-liner: `hf models list --author BuzzASR --filter ckb --format quiet` → `BuzzASR/sorani-kurdish`, or `--search kurdish` by name. The language prompt is baked into each model, so the model is never asked to detect the language. Default long-form decoding is Whisper's sequential algorithm (timestamps place each window, degenerate windows are re-decoded at higher temperature), which skipped no windows in our tests but is ~2.5x slower than `--long-form chunked` (the transformers pipeline), whose overlap merge drops text: on 3 h of Dutch audiobook the chunked run produced 14% fewer words than sequential, with whole sentences missing. Generation uses the authors' settings (greedy, no repeated 3-gram, repetition penalty 1.2), which also stop a genuinely repeated phrase from being written twice inside one 30 s window. Output is normalised like the training data (mostly lowercase, no punctuation); for a language Whisper already covers well, `openai/whisper-large-v3` through the same recipe gives punctuated, cased text of the same completeness (see Benchmarks), so reach for BuzzASR where Whisper is weak. The recipe rebuilds each model's `generation_config.json` on load: the native-tokenizer checkpoints ship it flagged `_from_model_config`, which makes transformers drop the language prompt and timestamp ids and breaks long-form generation. `--model openai/whisper-large-v3` runs the zero-shot base through the same loop as a control.
71
+
72
  **`easytranscriber-transcribe.py`** — when you need **word-level timestamps** (subtitles, search indexing, forced alignment). Runs VAD → ASR → wav2vec2 emissions → forced alignment. Defaults to the Cohere backend so you get the same model as the other scripts with alignment on top; swap to `--backend ct2` + a Whisper model for languages Cohere doesn't cover (e.g. Swedish via `KBLab/kb-whisper-large`).
73
 
74
  **`moss-transcribe-diarize.py`** — when you need **who said what**. Joint transcription + speaker diarization + timestamps in one generation pass (no separate ASR/diarization/alignment stages). 128k context handles up to ~90 min of audio per file internally, so files are never pre-chunked and the anonymous speaker labels (`[S01]`, `[S02]`, ...) stay consistent across the whole recording. English + Chinese; also accepts video containers (mp4, mkv, ...); supports hotword biasing for names/jargon.
 
93
  | `--decode-workers` | CPU count | Threads for mp3/wav decoding, overlapped with model load and inference |
94
  | `--max-files` | all | Limit files to process (for testing) |
95
 
96
+ #### Options — `buzzasr-transcribe.py`
97
+
98
+ | Flag | Default | Description |
99
+ |------|---------|-------------|
100
+ | `--language` | required | Language name (`dutch`, `sorani-kurdish`) or ISO code (`nl`, `ckb`), resolved via the org's model tags; `--list-languages` prints all of them live from the Hub |
101
+ | `--model` | `BuzzASR/<language>` | Any Whisper checkpoint on the Hub (e.g. `openai/whisper-large-v3` as a zero-shot control) |
102
+ | `--long-form` | `sequential` | `sequential` (Whisper's own long-form decoding with timestamps + temperature fallback; skipped no windows in our tests) or `chunked` (transformers pipeline, 30 s windows with 5 s overlap; ~2.5x faster, drops text at bad merges) |
103
+ | `--batch-size` | 16 | Files per generate call (sequential) or 30 s windows per forward pass (chunked) |
104
+ | `--decode-workers` | CPU count | Threads for mp3/wav decoding, overlapped with model load |
105
+ | `--max-files` | all | Limit files to process (for testing) |
106
+
107
  #### Options — `easytranscriber-transcribe.py`
108
 
109
  | Flag | Default | Description |
 
153
  | A100-SXM4-80GB | 12.3 min | 161x realtime |
154
  | L4 | ~64s / 30 min episode | 28x realtime |
155
 
156
+ **`buzzasr-transcribe.py`** (Dutch LibriVox audiobook, 4 chapters, 178 min; Armenian CC0 news/talk from the Internet Archive, 3 files, 25 min):
157
+
158
+ | Run | GPU | Time | RTFx | Peak GPU | Words out |
159
+ |-----|-----|------|------|----------|-----------|
160
+ | `BuzzASR/dutch`, sequential (default) | L4 | 8.9 min | 20x | 4.5 GB | 27,438 |
161
+ | `BuzzASR/dutch`, `--long-form chunked` | L4 | 3.5 min | 51x | 7.5 GB | 23,669 (−14%; sentences dropped at merges) |
162
+ | `openai/whisper-large-v3` control, sequential | L4 | 13.4 min | 13x | 4.3 GB | 27,688 (punctuated + cased; 14% word disagreement with BuzzASR; single-file batches, before the batching refactor) |
163
+ | `openai/whisper-large-v3` control, chunked | L4 | 4.5 min | 40x | 7.6 GB | 19,925 (−28% vs its own sequential run) |
164
+ | `BuzzASR/armenian`, sequential (25 min, 3 files) | L4 | 1.9 min | 13x | 4.1 GB | 2,198 words on the 19.5-min programme, coherent Armenian |
165
+ | `openai/whisper-large-v3` control, sequential, same files | L4 | 14.8 min | 2x | 4.5 GB | 582 words on the same programme, garbled + mojibake |
166
+
167
+ Peak host memory for the 178-min sequential batch was 9.0 GB; with the transformers docs' `logprob_threshold` fallback it was 17.6 GB, because that setting keeps every token's full-vocabulary scores on the host, and the output was identical without it, so the recipe leaves it out. No ground truth for either set: word counts and per-file diffs measure completeness, not accuracy. Two things follow. The chunked pipeline's losses are the pipeline's, not the model's (Whisper-large-v3 loses 28% of its words the same way), so `sequential` is the default for both. And on Dutch, a language Whisper already handles well (the authors report a 1.3x CER gain), zero-shot Whisper-large-v3 with the same sequential decoding was as complete and kept punctuation and casing, so the fine-tunes earn their place on the languages Whisper handles badly: on Armenian (6.8x claimed CER gain) the control produced a quarter of the words, garbled, at 2x realtime because its temperature fallback fired on almost every window.
168
+
169
  **`easytranscriber-transcribe.py`** (JSON alignments + optional .txt/.srt; VAD → ASR → wav2vec2 → forced alignment):
170
 
171
  | GPU | Time | RTFx | Output |
buzzasr-transcribe.py ADDED
@@ -0,0 +1,575 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "transformers>=4.57,<6",
5
+ # "torch==2.8.0",
6
+ # "huggingface-hub",
7
+ # "soundfile",
8
+ # "librosa",
9
+ # "numpy",
10
+ # ]
11
+ # ///
12
+
13
+ """
14
+ Transcribe audio files in one of 102 languages with a BuzzASR monolingual model.
15
+
16
+ BuzzASR (lemn-lab, Findings of EMNLP 2026) is one Whisper-large-v3 fine-tune
17
+ per FLEURS language, published as BuzzASR/<language> on the Hub. Pick the
18
+ language and the script loads that checkpoint; the language/task prompt is
19
+ baked into each model, so the model is never asked to detect the language.
20
+
21
+ Long audio: --long-form picks how files longer than Whisper's 30 s window are
22
+ decoded. `sequential` (default) is Whisper's own long-form algorithm: timestamp
23
+ tokens place each next window and degenerate windows are re-decoded at higher
24
+ temperature (no window was skipped in our tests). `chunked` is the transformers pipeline
25
+ (overlapping 30 s windows merged on the overlap): ~2.5x faster, but the merge
26
+ drops sentences when a window decodes badly (measured 14% fewer words on
27
+ Dutch audiobooks). Files are batched together; audio decoding runs in a thread
28
+ pool while the model loads.
29
+
30
+ Designed to work with HF Buckets mounted as volumes via `hf jobs uv run -v ...`.
31
+
32
+ Input: Output:
33
+ /input/episode1.mp3 -> /output/episode1.txt
34
+ /input/sub/clip.wav -> /output/sub/clip.txt
35
+
36
+ Examples:
37
+
38
+ # Local test (requires CUDA GPU)
39
+ uv run buzzasr-transcribe.py ./test-audio ./test-output --language dutch
40
+
41
+ # HF Jobs with bucket volumes
42
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
43
+ -e UV_TORCH_BACKEND=cu128 \\
44
+ -v hf://buckets/user/audio-input:/input:ro \\
45
+ -v hf://buckets/user/transcripts:/output \\
46
+ buzzasr-transcribe.py /input /output --language dutch
47
+
48
+ # Which model is Sorani Kurdish? Each card tags both the name and the ISO code
49
+ hf models list --author BuzzASR --filter ckb --format quiet # -> BuzzASR/sorani-kurdish
50
+ uv run buzzasr-transcribe.py --list-languages # all of them, live from the Hub
51
+
52
+ Models: https://huggingface.co/BuzzASR (MIT), 1.55B params each, fp16 safetensors
53
+ - `--language` takes the Hub name (dutch, sorani-kurdish, ...) or ISO code (nl, ckb, ...);
54
+ it is resolved against the org's model tags at run time, so new languages need no code change
55
+ - `--model` runs any other Whisper checkpoint through the same loop (e.g. openai/whisper-large-v3
56
+ as a zero-shot control)
57
+ """
58
+
59
+ import argparse
60
+ import json
61
+ import logging
62
+ import os
63
+ import sys
64
+ import time
65
+ from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait
66
+ from pathlib import Path
67
+
68
+ import numpy as np
69
+ import torch
70
+
71
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
72
+ logger = logging.getLogger(__name__)
73
+
74
+ SAMPLE_RATE = 16000
75
+ # Whisper's receptive field; the pipeline overlaps windows by CHUNK_SECONDS / 6.
76
+ CHUNK_SECONDS = 30
77
+ # Audio buffered per generate call (float32 at 16 kHz is ~3.8 MB per minute).
78
+ GROUP_SECONDS = 7200
79
+
80
+ AUDIO_EXTENSIONS = {".mp3", ".wav", ".flac", ".ogg", ".m4a", ".wma", ".aac", ".opus"}
81
+
82
+ ORG = "BuzzASR"
83
+
84
+ # From the model cards' usage snippet (greedy + anti-loop settings).
85
+ GENERATE_KWARGS = {"num_beams": 1, "no_repeat_ngram_size": 3, "repetition_penalty": 1.2}
86
+ # Whisper's long-form fallback (from the transformers Whisper docs): retry a
87
+ # window at higher temperature when its output looks degenerate. The docs also
88
+ # set logprob_threshold=-1.0, but that makes transformers keep every token's
89
+ # full-vocabulary scores on the host for the whole batch (measured 17.6 GB
90
+ # peak RSS for 178 min of audio vs 4.7 GB on the GPU), so only the
91
+ # compression-ratio check is used here.
92
+ SEQUENTIAL_KWARGS = {
93
+ "return_timestamps": True,
94
+ "condition_on_prev_tokens": False,
95
+ "compression_ratio_threshold": 1.35,
96
+ "temperature": (0.0, 0.2, 0.4, 0.6, 0.8, 1.0),
97
+ }
98
+
99
+
100
+ def check_cuda_availability():
101
+ if not torch.cuda.is_available():
102
+ logger.error("CUDA is not available. This script requires a GPU.")
103
+ sys.exit(1)
104
+ logger.info(f"CUDA available. GPU: {torch.cuda.get_device_name(0)}")
105
+
106
+
107
+ def list_org_models() -> list[tuple[str, str, str]]:
108
+ """(name, language code, repo id) for every model in the org, from the card metadata."""
109
+ from huggingface_hub import HfApi
110
+
111
+ rows = []
112
+ for m in HfApi().list_models(author=ORG, expand=["cardData"], limit=1000):
113
+ code = (m.card_data or {}).get("language") or "?"
114
+ if isinstance(code, list):
115
+ code = code[0]
116
+ rows.append((m.id.split("/", 1)[1], code, m.id))
117
+ return sorted(rows)
118
+
119
+
120
+ def resolve_model(language: str | None, model: str | None) -> str:
121
+ """Map --language to the org's repo for it, unless --model overrides.
122
+
123
+ Every BuzzASR card tags both the language name and its ISO code, so a Hub
124
+ tag filter on the org resolves either spelling (`hf models list --author
125
+ BuzzASR --filter nl`). No table to keep in sync with the org.
126
+ """
127
+ if model:
128
+ return model
129
+ if not language:
130
+ logger.error("--language is required (or pass --model). See --list-languages.")
131
+ sys.exit(1)
132
+ from huggingface_hub import HfApi
133
+
134
+ api = HfApi()
135
+ key = language.strip().lower()
136
+ # Tag filter first (name and ISO code are both tags on every card), then a
137
+ # name search for repo names the tag filter misses (hyphenated ones).
138
+ try:
139
+ matches = [m.id for m in api.list_models(author=ORG, filter=key, limit=10)]
140
+ if not matches:
141
+ found = [m.id for m in api.list_models(author=ORG, search=key, limit=10)]
142
+ exact = [i for i in found if i.split("/", 1)[1] == key]
143
+ matches = exact or found
144
+ except Exception as err: # network / Hub API failure, not "no such language"
145
+ logger.error(
146
+ f"Could not query the Hub to resolve --language {key!r} ({err}). "
147
+ f"Pass --model {ORG}/<name> to skip the lookup."
148
+ )
149
+ sys.exit(1)
150
+ if len(matches) == 1:
151
+ return matches[0]
152
+ if not matches:
153
+ logger.error(
154
+ f"No {ORG} model is tagged {key!r}. Try the language name or ISO code, "
155
+ f"`hf models list --author {ORG} --search {key}`, or --list-languages."
156
+ )
157
+ else:
158
+ logger.error(
159
+ f"{key!r} matches several {ORG} models: {', '.join(matches)}. Pass --model."
160
+ )
161
+ sys.exit(1)
162
+
163
+
164
+ def discover_audio_files(input_dir: Path) -> list[Path]:
165
+ """Walk input_dir recursively, returning sorted list of audio files."""
166
+ return [
167
+ p
168
+ for p in sorted(input_dir.rglob("*"))
169
+ if p.is_file() and p.suffix.lower() in AUDIO_EXTENSIONS
170
+ ]
171
+
172
+
173
+ def load_audio(path: Path) -> np.ndarray:
174
+ """Decode to float32 mono at 16 kHz."""
175
+ import librosa
176
+
177
+ audio, _ = librosa.load(str(path), sr=SAMPLE_RATE, mono=True)
178
+ return audio.astype(np.float32)
179
+
180
+
181
+ def batched(items: list, size: int):
182
+ for i in range(0, len(items), size):
183
+ yield items[i : i + size]
184
+
185
+
186
+ def load_generation_config(model_id: str):
187
+ """Reload generation_config.json without the `_from_model_config` flag.
188
+
189
+ The full-fine-tune BuzzASR checkpoints (native tokenizer) ship a minimal
190
+ generation config saved with `"_from_model_config": true`. transformers
191
+ treats such a file as auto-derived and drops every extra field on load, so
192
+ `lang_to_id`, `language`, `task` and `no_timestamps_token_id` vanish: the
193
+ language prompt is no longer forced and long-form generation errors out.
194
+ Rebuilding from the raw JSON keeps the authors' settings. Harmless for the
195
+ simple-fine-tune checkpoints, which ship the full Whisper config.
196
+ """
197
+ from huggingface_hub import hf_hub_download
198
+ from transformers import GenerationConfig
199
+
200
+ local = Path(model_id) / "generation_config.json"
201
+ path = (
202
+ local
203
+ if local.is_file()
204
+ else hf_hub_download(model_id, "generation_config.json")
205
+ )
206
+ raw = json.loads(Path(path).read_text())
207
+ was_flagged = raw.pop("_from_model_config", False)
208
+ config = GenerationConfig(**raw)
209
+ if not hasattr(config, "max_initial_timestamp_index"):
210
+ config.max_initial_timestamp_index = 50 # Whisper default
211
+ config.is_multilingual = True
212
+ if was_flagged:
213
+ logger.info(
214
+ "generation_config.json was flagged _from_model_config; rebuilt it so the "
215
+ f"language prompt ({config.language}) and timestamp ids are kept"
216
+ )
217
+ return config
218
+
219
+
220
+ def main():
221
+ parser = argparse.ArgumentParser(
222
+ description="Transcribe audio with a BuzzASR monolingual Whisper-large-v3 fine-tune.",
223
+ formatter_class=argparse.RawDescriptionHelpFormatter,
224
+ epilog="""
225
+ Examples:
226
+ uv run buzzasr-transcribe.py ./audio ./output --language dutch
227
+ uv run buzzasr-transcribe.py ./audio ./output --language nl --batch-size 32
228
+ uv run buzzasr-transcribe.py ./audio ./output --model openai/whisper-large-v3 # zero-shot control
229
+
230
+ HF Jobs with bucket volumes:
231
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN -e UV_TORCH_BACKEND=cu128 \\
232
+ -v hf://buckets/user/audio-bucket:/input:ro \\
233
+ -v hf://buckets/user/transcripts:/output \\
234
+ buzzasr-transcribe.py /input /output --language dutch
235
+ """,
236
+ )
237
+ parser.add_argument("input_dir", nargs="?", help="Directory containing audio files")
238
+ parser.add_argument(
239
+ "output_dir", nargs="?", help="Directory to write transcript text files"
240
+ )
241
+ parser.add_argument(
242
+ "--language",
243
+ help="Language name (dutch, sorani-kurdish) or ISO code (nl, ckb); resolved via the org's model tags",
244
+ )
245
+ parser.add_argument(
246
+ "--model",
247
+ help="Override the checkpoint (any Whisper model on the Hub); --language is then ignored",
248
+ )
249
+ parser.add_argument(
250
+ "--list-languages",
251
+ action="store_true",
252
+ help="List the org's models with their language codes (live from the Hub) and exit",
253
+ )
254
+ parser.add_argument(
255
+ "--long-form",
256
+ choices=["sequential", "chunked"],
257
+ default="sequential",
258
+ help="How files longer than 30 s are decoded: Whisper's sequential algorithm "
259
+ "(skipped no windows in our tests) or the transformers chunked pipeline "
260
+ "(faster, drops text at bad merges) (default: sequential)",
261
+ )
262
+ parser.add_argument(
263
+ "--batch-size",
264
+ type=int,
265
+ default=16,
266
+ help="Files per generate call (sequential) or 30 s windows per forward pass (chunked) (default: 16)",
267
+ )
268
+ parser.add_argument(
269
+ "--decode-workers",
270
+ type=int,
271
+ default=os.cpu_count() or 4,
272
+ help="Threads for audio decoding (default: CPU count)",
273
+ )
274
+ parser.add_argument(
275
+ "--max-files",
276
+ type=int,
277
+ default=None,
278
+ help="Limit number of files to process (for testing)",
279
+ )
280
+ parser.add_argument(
281
+ "--verbose",
282
+ action="store_true",
283
+ help="Print resolved package versions",
284
+ )
285
+
286
+ args = parser.parse_args()
287
+
288
+ if args.list_languages:
289
+ for name, code, repo_id in list_org_models():
290
+ print(f"{name:16s} {code:4s} {repo_id}")
291
+ sys.exit(0)
292
+
293
+ if not args.input_dir or not args.output_dir:
294
+ parser.error("input_dir and output_dir are required")
295
+
296
+ model_id = resolve_model(args.language, args.model)
297
+
298
+ check_cuda_availability()
299
+
300
+ input_dir = Path(args.input_dir)
301
+ output_dir = Path(args.output_dir)
302
+
303
+ if not input_dir.is_dir():
304
+ logger.error(f"Input directory does not exist: {input_dir}")
305
+ sys.exit(1)
306
+
307
+ output_dir.mkdir(parents=True, exist_ok=True)
308
+
309
+ logger.info(f"Scanning {input_dir} for audio files...")
310
+ files = discover_audio_files(input_dir)
311
+ if not files:
312
+ logger.error(f"No audio files found in {input_dir}")
313
+ logger.error(f"Supported extensions: {', '.join(sorted(AUDIO_EXTENSIONS))}")
314
+ sys.exit(1)
315
+
316
+ if args.max_files:
317
+ files = files[: args.max_files]
318
+
319
+ logger.info(f"Found {len(files)} audio file(s)")
320
+
321
+ # Output is <name>.txt, so episode.mp3 and episode.wav in one directory
322
+ # would overwrite each other. Refuse up front rather than lose a transcript.
323
+ out_paths = [
324
+ output_dir / f.relative_to(input_dir).with_suffix(".txt") for f in files
325
+ ]
326
+ seen: dict[Path, Path] = {}
327
+ for src, dst in zip(files, out_paths):
328
+ if dst in seen:
329
+ logger.error(f"{src} and {seen[dst]} would both write {dst}; rename one.")
330
+ sys.exit(1)
331
+ seen[dst] = src
332
+
333
+ wall_start = time.time()
334
+
335
+ # Decode in a thread pool while the model loads. Only a few files are in
336
+ # flight at once (decoded audio is 3.8 MB/min), and each group is
337
+ # transcribed and written out as soon as it is full, so memory is bounded
338
+ # by GROUP_SECONDS plus the decode-ahead window and a crash keeps the
339
+ # transcripts already written.
340
+ logger.info(f"Decoding audio with {args.decode_workers} worker(s)...")
341
+ decode_start = time.time()
342
+ pool = ThreadPoolExecutor(max_workers=args.decode_workers)
343
+ to_decode = list(enumerate(files))
344
+ pending: dict = {} # future -> file index
345
+ decode_ahead = 2 * args.decode_workers
346
+
347
+ def timed_load(path: Path) -> tuple[np.ndarray, float]:
348
+ return load_audio(path), time.time()
349
+
350
+ def top_up_decoding():
351
+ while to_decode and len(pending) < decode_ahead:
352
+ fi, path = to_decode.pop(0)
353
+ pending[pool.submit(timed_load, path)] = fi
354
+
355
+ top_up_decoding()
356
+
357
+ logger.info(f"Loading {model_id}...")
358
+ from transformers import WhisperForConditionalGeneration, WhisperProcessor
359
+
360
+ processor = WhisperProcessor.from_pretrained(model_id)
361
+ model = WhisperForConditionalGeneration.from_pretrained(
362
+ model_id, dtype=torch.float16
363
+ )
364
+ model.generation_config = load_generation_config(model_id)
365
+ model.to("cuda:0").eval()
366
+ asr = None
367
+ if args.long_form == "chunked":
368
+ from transformers import pipeline
369
+
370
+ asr = pipeline(
371
+ "automatic-speech-recognition",
372
+ model=model,
373
+ tokenizer=processor.tokenizer,
374
+ feature_extractor=processor.feature_extractor,
375
+ chunk_length_s=CHUNK_SECONDS,
376
+ batch_size=args.batch_size,
377
+ device=0,
378
+ )
379
+ logger.info("Model loaded")
380
+
381
+ durations = [0.0] * len(files)
382
+ texts: dict[int, str] = {}
383
+ gpu_time = 0.0
384
+ group: list[tuple[int, np.ndarray]] = []
385
+ group_seconds = 0.0
386
+
387
+ def generate_batch(audios: list[np.ndarray]) -> list[str]:
388
+ """Feature-extract + generate + decode one batch of whole files."""
389
+ inputs = processor(
390
+ audios,
391
+ sampling_rate=SAMPLE_RATE,
392
+ return_tensors="pt",
393
+ truncation=False,
394
+ padding="longest",
395
+ return_attention_mask=True,
396
+ )
397
+ if inputs.input_features.shape[-1] <= 3000:
398
+ # Every file fits one window: short-form. Re-extract padded to the
399
+ # full 30 s window (3000 frames); the encoder and Whisper's language
400
+ # detection (used by non-BuzzASR checkpoints) expect exactly that.
401
+ feats = processor(audios, sampling_rate=SAMPLE_RATE, return_tensors="pt")
402
+ ids = model.generate(
403
+ input_features=feats.input_features.to("cuda:0", torch.float16),
404
+ **GENERATE_KWARGS,
405
+ )
406
+ return [
407
+ t.strip() for t in processor.batch_decode(ids, skip_special_tokens=True)
408
+ ]
409
+ input_features = inputs.input_features.to("cuda:0", torch.float16)
410
+ attention_mask = inputs.attention_mask.to("cuda:0")
411
+ # Decode segment by segment: the fine-tunes start a segment without a
412
+ # leading-space token, so decoding the whole sequence at once glues the
413
+ # last word of one segment to the first word of the next.
414
+ out = model.generate(
415
+ input_features=input_features,
416
+ attention_mask=attention_mask,
417
+ return_segments=True,
418
+ **GENERATE_KWARGS,
419
+ **SEQUENTIAL_KWARGS,
420
+ )
421
+ texts = []
422
+ for segments in out["segments"]:
423
+ parts = processor.batch_decode(
424
+ [seg["tokens"].tolist() for seg in segments], skip_special_tokens=True
425
+ )
426
+ texts.append(" ".join(t.strip() for t in parts if t.strip()))
427
+ return texts
428
+
429
+ def run_group():
430
+ nonlocal gpu_time
431
+ t = time.time()
432
+ if args.long_form == "chunked":
433
+ inputs = [
434
+ {"raw": audio, "sampling_rate": SAMPLE_RATE} for _, audio in group
435
+ ]
436
+ outputs = asr(inputs, generate_kwargs=GENERATE_KWARGS)
437
+ for (fi, _), out in zip(group, outputs):
438
+ texts[fi] = out["text"].strip()
439
+ else:
440
+ for batch in batched(group, args.batch_size):
441
+ decoded = generate_batch([audio for _, audio in batch])
442
+ for (fi, _), text in zip(batch, decoded):
443
+ texts[fi] = text
444
+ torch.cuda.synchronize()
445
+ gpu_time += time.time() - t
446
+ logger.info(
447
+ f" group of {len(group)} file(s), {group_seconds / 60:.1f} min audio done"
448
+ )
449
+
450
+ summary_path = output_dir / "summary.jsonl"
451
+ summary_path.write_text("", encoding="utf-8")
452
+
453
+ def write_group():
454
+ """Write this group's transcripts and append their summary rows, in file order."""
455
+ with open(summary_path, "a", encoding="utf-8") as f:
456
+ for fi, _ in sorted(group):
457
+ text = texts.pop(fi)
458
+ rel = files[fi].relative_to(input_dir)
459
+ txt_path = out_paths[fi]
460
+ txt_path.parent.mkdir(parents=True, exist_ok=True)
461
+ txt_path.write_text(text, encoding="utf-8")
462
+ row = {
463
+ "file": str(rel),
464
+ "model": model_id,
465
+ "long_form": args.long_form,
466
+ "duration_s": round(durations[fi], 1),
467
+ "transcript_length": len(text),
468
+ "word_count": len(text.split()),
469
+ }
470
+ f.write(json.dumps(row, ensure_ascii=False) + "\n")
471
+ logger.info(
472
+ f" {rel} -> {txt_path.name} ({len(text.split())} words, "
473
+ f"{durations[fi]:.0f}s audio)"
474
+ )
475
+
476
+ logger.info(
477
+ f"Transcribing (long_form={args.long_form}, batch_size={args.batch_size}, {model_id})..."
478
+ )
479
+ torch.cuda.reset_peak_memory_stats()
480
+ last_decoded_at = decode_start
481
+
482
+ def flush_group():
483
+ nonlocal group_seconds
484
+ run_group()
485
+ write_group()
486
+ group.clear()
487
+ group_seconds = 0.0
488
+
489
+ with torch.inference_mode():
490
+ while pending:
491
+ done, _ = wait(pending, return_when=FIRST_COMPLETED)
492
+ for fut in done:
493
+ fi = pending.pop(fut)
494
+ audio, decoded_at = fut.result()
495
+ last_decoded_at = max(last_decoded_at, decoded_at)
496
+ durations[fi] = len(audio) / SAMPLE_RATE
497
+ # Flush before an addition would push the group past its budget;
498
+ # a single file longer than the budget is a group on its own.
499
+ if group and group_seconds + durations[fi] > GROUP_SECONDS:
500
+ flush_group()
501
+ group.append((fi, audio))
502
+ group_seconds += durations[fi]
503
+ top_up_decoding()
504
+ if not pending and group:
505
+ flush_group()
506
+ pool.shutdown()
507
+ decode_time = last_decoded_at - decode_start
508
+ total_audio = sum(durations)
509
+ peak_gb = torch.cuda.max_memory_allocated() / 1e9
510
+ import resource
511
+
512
+ peak_rss_gb = (
513
+ resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1e6
514
+ ) # kB on Linux
515
+
516
+ wall = time.time() - wall_start
517
+ logger.info("=" * 50)
518
+ logger.info(
519
+ f"Done! Transcribed {len(files)} file(s), {total_audio / 60:.1f} min of audio with {model_id}"
520
+ )
521
+ logger.info(f" Output: {output_dir}")
522
+ logger.info(
523
+ f" Audio decode (overlapped with model load + GPU): {decode_time:.1f}s"
524
+ )
525
+ logger.info(
526
+ f" GPU busy (features+generate+decode): {gpu_time:.1f}s -> RTFx {total_audio / gpu_time:.0f}x"
527
+ )
528
+ logger.info(
529
+ f" Wall (incl. decode + model load): {wall:.1f}s -> RTFx {total_audio / wall:.0f}x"
530
+ )
531
+ logger.info(
532
+ f" Peak GPU memory: {peak_gb:.2f} GB, peak host RSS: {peak_rss_gb:.1f} GB "
533
+ f"(long_form={args.long_form}, batch_size={args.batch_size})"
534
+ )
535
+ logger.info(f" Summary: {summary_path}")
536
+
537
+ if args.verbose:
538
+ import importlib.metadata
539
+
540
+ logger.info("--- Package versions ---")
541
+ for pkg in ["transformers", "torch", "librosa", "soundfile", "huggingface-hub"]:
542
+ try:
543
+ logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
544
+ except importlib.metadata.PackageNotFoundError:
545
+ logger.info(f" {pkg}: not installed")
546
+
547
+
548
+ if __name__ == "__main__":
549
+ if len(sys.argv) == 1:
550
+ print("=" * 60)
551
+ print(
552
+ "Audio Transcription with BuzzASR (102 monolingual Whisper-large-v3 fine-tunes)"
553
+ )
554
+ print("=" * 60)
555
+ print("\nTranscribe audio files from a directory -> text files.")
556
+ print("One model per language; long audio chunked and batched.")
557
+ print("Designed for HF Buckets mounted as volumes.")
558
+ print()
559
+ print("Usage:")
560
+ print(" uv run buzzasr-transcribe.py INPUT_DIR OUTPUT_DIR --language dutch")
561
+ print(" uv run buzzasr-transcribe.py --list-languages")
562
+ print(
563
+ " hf models list --author BuzzASR --filter ckb --format quiet # name from ISO code"
564
+ )
565
+ print()
566
+ print("HF Jobs with bucket volumes:")
567
+ print(" hf jobs uv run --flavor l4x1 -s HF_TOKEN -e UV_TORCH_BACKEND=cu128 \\")
568
+ print(" -v hf://buckets/user/audio-input:/input:ro \\")
569
+ print(" -v hf://buckets/user/transcripts:/output \\")
570
+ print(" buzzasr-transcribe.py /input /output --language dutch")
571
+ print()
572
+ print("For full help: uv run buzzasr-transcribe.py --help")
573
+ sys.exit(0)
574
+
575
+ main()