|
| 1 | +# /// script |
| 2 | +# requires-python = ">=3.11" |
| 3 | +# dependencies = [ |
| 4 | +# "transformers @ git+https://github.com/huggingface/transformers.git@da7234ac435f", |
| 5 | +# "torch==2.8.0", |
| 6 | +# "torchaudio==2.8.0", |
| 7 | +# "huggingface-hub", |
| 8 | +# "soundfile", |
| 9 | +# "librosa", |
| 10 | +# "numpy", |
| 11 | +# ] |
| 12 | +# /// |
| 13 | + |
| 14 | +""" |
| 15 | +Transcribe English audio files with IBM Granite Speech 5.0 TurboCTC (470M). |
| 16 | +
|
| 17 | +Encoder-only CTC model: one forward pass + argmax per batch, no autoregressive |
| 18 | +decoding, so it is very fast and cannot hallucinate or loop. English only. |
| 19 | +
|
| 20 | +Files are fed whole by default: block attention makes cost linear in length, |
| 21 | +so a 30-minute file is fine (measured 10.3 GB peak for four 30-minute files |
| 22 | +per batch, i.e. ~2.5 GB per 30 min of audio at bf16). For hour-plus files or |
| 23 | +a 24 GB card, lower --batch-size or use --chunk-seconds N, which cuts every |
| 24 | +file into N-second windows, pooled, length-sorted and batched (30 s windows |
| 25 | +at batch 32 peak at 2.2 GB). |
| 26 | +Audio decoding runs in a thread pool (--decode-workers) since it dominates |
| 27 | +wall time for a model this fast. |
| 28 | +
|
| 29 | +Designed to work with HF Buckets mounted as volumes via `hf jobs uv run -v ...`. |
| 30 | +
|
| 31 | +Input: Output: |
| 32 | + /input/episode1.mp3 -> /output/episode1.txt |
| 33 | + /input/sub/clip.wav -> /output/sub/clip.txt |
| 34 | +
|
| 35 | +Examples: |
| 36 | +
|
| 37 | + # Local test (requires CUDA GPU) |
| 38 | + uv run granite-turboctc-transcribe.py ./test-audio ./test-output |
| 39 | +
|
| 40 | + # HF Jobs with bucket volumes |
| 41 | + hf jobs uv run --flavor l4x1 -s HF_TOKEN \\ |
| 42 | + -e UV_TORCH_BACKEND=cu128 \\ |
| 43 | + -v hf://buckets/user/audio-input:/input:ro \\ |
| 44 | + -v hf://buckets/user/transcripts:/output \\ |
| 45 | + granite-turboctc-transcribe.py /input /output |
| 46 | +
|
| 47 | +Model: ibm-granite/granite-speech-5.0-470m-turboctc (Apache 2.0) |
| 48 | + - English only, 16 kHz mono (resampled on load) |
| 49 | + - transformers support landed on main 2026-08-25 (PR #48288); pinned to that |
| 50 | + commit until it ships in a release |
| 51 | +""" |
| 52 | + |
| 53 | +import argparse |
| 54 | +import json |
| 55 | +import logging |
| 56 | +import os |
| 57 | +import sys |
| 58 | +import time |
| 59 | +from concurrent.futures import ThreadPoolExecutor, as_completed |
| 60 | +from pathlib import Path |
| 61 | + |
| 62 | +import numpy as np |
| 63 | +import torch |
| 64 | + |
| 65 | +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") |
| 66 | +logger = logging.getLogger(__name__) |
| 67 | + |
| 68 | +MODEL = "ibm-granite/granite-speech-5.0-470m-turboctc" |
| 69 | +SAMPLE_RATE = 16000 |
| 70 | + |
| 71 | +AUDIO_EXTENSIONS = {".mp3", ".wav", ".flac", ".ogg", ".m4a", ".wma", ".aac", ".opus"} |
| 72 | + |
| 73 | + |
| 74 | +def check_cuda_availability(): |
| 75 | + if not torch.cuda.is_available(): |
| 76 | + logger.error("CUDA is not available. This script requires a GPU.") |
| 77 | + sys.exit(1) |
| 78 | + logger.info(f"CUDA available. GPU: {torch.cuda.get_device_name(0)}") |
| 79 | + |
| 80 | + |
| 81 | +def discover_audio_files(input_dir: Path) -> list[Path]: |
| 82 | + """Walk input_dir recursively, returning sorted list of audio files.""" |
| 83 | + return [ |
| 84 | + p |
| 85 | + for p in sorted(input_dir.rglob("*")) |
| 86 | + if p.is_file() and p.suffix.lower() in AUDIO_EXTENSIONS |
| 87 | + ] |
| 88 | + |
| 89 | + |
| 90 | +def load_audio(path: Path) -> np.ndarray: |
| 91 | + """Decode to float32 mono at 16 kHz.""" |
| 92 | + import librosa |
| 93 | + |
| 94 | + audio, _ = librosa.load(str(path), sr=SAMPLE_RATE, mono=True) |
| 95 | + return audio.astype(np.float32) |
| 96 | + |
| 97 | + |
| 98 | +def chunk_audio(audio: np.ndarray, chunk_seconds: float) -> list[np.ndarray]: |
| 99 | + """Fixed non-overlapping windows; the last one keeps the remainder.""" |
| 100 | + if chunk_seconds <= 0 or len(audio) <= chunk_seconds * SAMPLE_RATE: |
| 101 | + return [audio] |
| 102 | + step = int(chunk_seconds * SAMPLE_RATE) |
| 103 | + return [audio[i : i + step] for i in range(0, len(audio), step)] |
| 104 | + |
| 105 | + |
| 106 | +def main(): |
| 107 | + parser = argparse.ArgumentParser( |
| 108 | + description="Transcribe English audio with Granite Speech 5.0 TurboCTC.", |
| 109 | + formatter_class=argparse.RawDescriptionHelpFormatter, |
| 110 | + epilog=""" |
| 111 | +Examples: |
| 112 | + uv run granite-turboctc-transcribe.py ./audio ./output |
| 113 | + uv run granite-turboctc-transcribe.py ./audio ./output --chunk-seconds 30 --batch-size 32 |
| 114 | +
|
| 115 | +HF Jobs with bucket volumes: |
| 116 | + hf jobs uv run --flavor l4x1 -s HF_TOKEN -e UV_TORCH_BACKEND=cu128 \\ |
| 117 | + -v hf://buckets/user/audio-bucket:/input:ro \\ |
| 118 | + -v hf://buckets/user/transcripts:/output \\ |
| 119 | + granite-turboctc-transcribe.py /input /output |
| 120 | + """, |
| 121 | + ) |
| 122 | + parser.add_argument("input_dir", help="Directory containing audio files") |
| 123 | + parser.add_argument("output_dir", help="Directory to write transcript text files") |
| 124 | + parser.add_argument( |
| 125 | + "--chunk-seconds", |
| 126 | + type=float, |
| 127 | + default=0.0, |
| 128 | + help="Cut files into N-second windows; 0 = feed each file whole (default: 0)", |
| 129 | + ) |
| 130 | + parser.add_argument( |
| 131 | + "--batch-size", |
| 132 | + type=int, |
| 133 | + default=4, |
| 134 | + help="Files (or windows) per forward pass (default: 4; 32+ with --chunk-seconds 30)", |
| 135 | + ) |
| 136 | + parser.add_argument( |
| 137 | + "--decode-workers", |
| 138 | + type=int, |
| 139 | + default=os.cpu_count() or 4, |
| 140 | + help="Threads for audio decoding (default: CPU count)", |
| 141 | + ) |
| 142 | + parser.add_argument( |
| 143 | + "--max-files", |
| 144 | + type=int, |
| 145 | + default=None, |
| 146 | + help="Limit number of files to process (for testing)", |
| 147 | + ) |
| 148 | + parser.add_argument( |
| 149 | + "--verbose", |
| 150 | + action="store_true", |
| 151 | + help="Print resolved package versions", |
| 152 | + ) |
| 153 | + |
| 154 | + args = parser.parse_args() |
| 155 | + |
| 156 | + check_cuda_availability() |
| 157 | + |
| 158 | + input_dir = Path(args.input_dir) |
| 159 | + output_dir = Path(args.output_dir) |
| 160 | + |
| 161 | + if not input_dir.is_dir(): |
| 162 | + logger.error(f"Input directory does not exist: {input_dir}") |
| 163 | + sys.exit(1) |
| 164 | + |
| 165 | + output_dir.mkdir(parents=True, exist_ok=True) |
| 166 | + |
| 167 | + logger.info(f"Scanning {input_dir} for audio files...") |
| 168 | + files = discover_audio_files(input_dir) |
| 169 | + if not files: |
| 170 | + logger.error(f"No audio files found in {input_dir}") |
| 171 | + logger.error(f"Supported extensions: {', '.join(sorted(AUDIO_EXTENSIONS))}") |
| 172 | + sys.exit(1) |
| 173 | + |
| 174 | + if args.max_files: |
| 175 | + files = files[: args.max_files] |
| 176 | + |
| 177 | + logger.info(f"Found {len(files)} audio file(s)") |
| 178 | + |
| 179 | + wall_start = time.time() |
| 180 | + |
| 181 | + # Decode in a thread pool while the model loads, then feed the GPU as files |
| 182 | + # land: decoding is CPU-bound and, for a model this fast, the bottleneck. |
| 183 | + # segments: (file_idx, chunk_idx, audio) |
| 184 | + logger.info(f"Decoding audio with {args.decode_workers} worker(s)...") |
| 185 | + decode_start = time.time() |
| 186 | + pool = ThreadPoolExecutor(max_workers=args.decode_workers) |
| 187 | + futures = {pool.submit(load_audio, path): fi for fi, path in enumerate(files)} |
| 188 | + |
| 189 | + logger.info(f"Loading {MODEL}...") |
| 190 | + from transformers import AutoModelForCTC, AutoProcessor |
| 191 | + |
| 192 | + processor = AutoProcessor.from_pretrained(MODEL) |
| 193 | + model = AutoModelForCTC.from_pretrained(MODEL, dtype=torch.bfloat16).to("cuda:0") |
| 194 | + model.eval() |
| 195 | + logger.info("Model loaded") |
| 196 | + |
| 197 | + durations = [0.0] * len(files) |
| 198 | + texts: dict[tuple[int, int], str] = {} |
| 199 | + n_segments = 0 |
| 200 | + longest_s = 0.0 |
| 201 | + gpu_time = 0.0 |
| 202 | + buffer: list[tuple[int, int, np.ndarray]] = [] |
| 203 | + |
| 204 | + def run_batch(batch): |
| 205 | + nonlocal gpu_time, longest_s |
| 206 | + t = time.time() |
| 207 | + inputs = processor( |
| 208 | + [seg[2] for seg in batch], sampling_rate=SAMPLE_RATE, device=model.device |
| 209 | + ) |
| 210 | + inputs = inputs.to(model.device, dtype=model.dtype) |
| 211 | + ids = model.generate(**inputs) |
| 212 | + decoded = processor.batch_decode(ids, skip_special_tokens=True) |
| 213 | + for seg, text in zip(batch, decoded): |
| 214 | + texts[seg[:2]] = text.strip() |
| 215 | + torch.cuda.synchronize() |
| 216 | + gpu_time += time.time() - t |
| 217 | + longest_s = max(longest_s, max(len(seg[2]) for seg in batch) / SAMPLE_RATE) |
| 218 | + |
| 219 | + logger.info( |
| 220 | + f"Transcribing (chunk_seconds={args.chunk_seconds}, batch_size={args.batch_size})..." |
| 221 | + ) |
| 222 | + torch.cuda.reset_peak_memory_stats() |
| 223 | + decode_time = None |
| 224 | + with torch.inference_mode(): |
| 225 | + for fut in as_completed(futures): |
| 226 | + fi = futures[fut] |
| 227 | + audio = fut.result() |
| 228 | + durations[fi] = len(audio) / SAMPLE_RATE |
| 229 | + for ci, chunk in enumerate(chunk_audio(audio, args.chunk_seconds)): |
| 230 | + buffer.append((fi, ci, chunk)) |
| 231 | + n_segments += 1 |
| 232 | + if len(futures) and all(f.done() for f in futures) and decode_time is None: |
| 233 | + decode_time = time.time() - decode_start |
| 234 | + while len(buffer) >= args.batch_size: |
| 235 | + run_batch(buffer[: args.batch_size]) |
| 236 | + del buffer[: args.batch_size] |
| 237 | + logger.info( |
| 238 | + f" {files[fi].name}: decoded, {len(texts)}/{n_segments} segments done" |
| 239 | + ) |
| 240 | + if buffer: |
| 241 | + run_batch(buffer) |
| 242 | + buffer.clear() |
| 243 | + pool.shutdown() |
| 244 | + decode_time = decode_time or (time.time() - decode_start) |
| 245 | + total_audio = sum(durations) |
| 246 | + peak_gb = torch.cuda.max_memory_allocated() / 1e9 |
| 247 | + model_time = gpu_time |
| 248 | + |
| 249 | + # Reassemble per file and write outputs |
| 250 | + results = [] |
| 251 | + for fi, path in enumerate(files): |
| 252 | + parts = [texts[k] for k in sorted(k for k in texts if k[0] == fi)] |
| 253 | + text = " ".join(p for p in parts if p) |
| 254 | + rel = path.relative_to(input_dir) |
| 255 | + txt_path = output_dir / rel.with_suffix(".txt") |
| 256 | + txt_path.parent.mkdir(parents=True, exist_ok=True) |
| 257 | + txt_path.write_text(text, encoding="utf-8") |
| 258 | + results.append( |
| 259 | + { |
| 260 | + "file": str(rel), |
| 261 | + "duration_s": round(durations[fi], 1), |
| 262 | + "segments": len(parts), |
| 263 | + "transcript_length": len(text), |
| 264 | + "word_count": len(text.split()), |
| 265 | + } |
| 266 | + ) |
| 267 | + logger.info( |
| 268 | + f" {rel} -> {txt_path.name} ({len(text.split())} words, {durations[fi]:.0f}s audio)" |
| 269 | + ) |
| 270 | + |
| 271 | + summary_path = output_dir / "summary.jsonl" |
| 272 | + with open(summary_path, "w", encoding="utf-8") as f: |
| 273 | + f.writelines(json.dumps(r) + "\n" for r in results) |
| 274 | + |
| 275 | + wall = time.time() - wall_start |
| 276 | + logger.info("=" * 50) |
| 277 | + logger.info( |
| 278 | + f"Done! Transcribed {len(files)} file(s), {total_audio / 60:.1f} min of audio" |
| 279 | + ) |
| 280 | + logger.info(f" Output: {output_dir}") |
| 281 | + logger.info( |
| 282 | + f" Audio decode (overlapped with model load + GPU): {decode_time:.1f}s" |
| 283 | + ) |
| 284 | + logger.info( |
| 285 | + f" GPU busy (features+forward+decode): {model_time:.1f}s -> RTFx {total_audio / model_time:.0f}x" |
| 286 | + ) |
| 287 | + logger.info( |
| 288 | + f" Wall (incl. decode + model load): {wall:.1f}s -> RTFx {total_audio / wall:.0f}x" |
| 289 | + ) |
| 290 | + logger.info( |
| 291 | + f" Peak GPU memory: {peak_gb:.2f} GB " |
| 292 | + f"(batch_size={args.batch_size}, longest segment {longest_s:.0f}s)" |
| 293 | + ) |
| 294 | + logger.info(f" Summary: {summary_path}") |
| 295 | + |
| 296 | + if args.verbose: |
| 297 | + import importlib.metadata |
| 298 | + |
| 299 | + logger.info("--- Package versions ---") |
| 300 | + for pkg in [ |
| 301 | + "transformers", |
| 302 | + "torch", |
| 303 | + "torchaudio", |
| 304 | + "librosa", |
| 305 | + "soundfile", |
| 306 | + "huggingface-hub", |
| 307 | + ]: |
| 308 | + try: |
| 309 | + logger.info(f" {pkg}=={importlib.metadata.version(pkg)}") |
| 310 | + except importlib.metadata.PackageNotFoundError: |
| 311 | + logger.info(f" {pkg}: not installed") |
| 312 | + |
| 313 | + |
| 314 | +if __name__ == "__main__": |
| 315 | + if len(sys.argv) == 1: |
| 316 | + print("=" * 60) |
| 317 | + print("Audio Transcription with Granite Speech 5.0 TurboCTC (470M, English)") |
| 318 | + print("=" * 60) |
| 319 | + print("\nTranscribe audio files from a directory -> text files.") |
| 320 | + print("Encoder-only CTC: fast, batched, no hallucination loops.") |
| 321 | + print("Designed for HF Buckets mounted as volumes.") |
| 322 | + print() |
| 323 | + print("Usage:") |
| 324 | + print(" uv run granite-turboctc-transcribe.py INPUT_DIR OUTPUT_DIR") |
| 325 | + print() |
| 326 | + print("HF Jobs with bucket volumes:") |
| 327 | + print(" hf jobs uv run --flavor l4x1 -s HF_TOKEN -e UV_TORCH_BACKEND=cu128 \\") |
| 328 | + print(" -v hf://buckets/user/audio-input:/input:ro \\") |
| 329 | + print(" -v hf://buckets/user/transcripts:/output \\") |
| 330 | + print(" granite-turboctc-transcribe.py /input /output") |
| 331 | + print() |
| 332 | + print("For full help: uv run granite-turboctc-transcribe.py --help") |
| 333 | + sys.exit(0) |
| 334 | + |
| 335 | + main() |
0 commit comments