Commit ·
06d0dab
1
Parent(s): acdac4e
Initial transcription scripts
Browse files- transcribe-transformers.py: Cohere Transcribe via transformers (161x RT on A100)
- transcribe.py: vLLM variant (214x RT, experimental)
- download-ia.py: Internet Archive to HF Bucket downloader
- README.md +75 -0
- download-ia.py +152 -0
- transcribe-transformers.py +285 -0
- transcribe.py +338 -0
README.md
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
viewer: false
|
| 3 |
+
tags:
|
| 4 |
+
- uv-script
|
| 5 |
+
- audio
|
| 6 |
+
- transcription
|
| 7 |
+
- automatic-speech-recognition
|
| 8 |
+
private: true
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
# Transcription
|
| 12 |
+
|
| 13 |
+
Scripts for transcribing audio files using HF Buckets and Jobs.
|
| 14 |
+
|
| 15 |
+
## Quick Start
|
| 16 |
+
|
| 17 |
+
```bash
|
| 18 |
+
# 1. Download audio from Internet Archive straight into a bucket
|
| 19 |
+
hf jobs uv run \
|
| 20 |
+
-v bucket/user/audio-files:/output \
|
| 21 |
+
download-ia.py SUSPENSE /output
|
| 22 |
+
|
| 23 |
+
# 2. Transcribe — audio bucket in, transcript bucket out
|
| 24 |
+
hf jobs uv run --flavor l4x1 -s HF_TOKEN \
|
| 25 |
+
-e UV_TORCH_BACKEND=cu124 \
|
| 26 |
+
-v bucket/user/audio-files:/input:ro \
|
| 27 |
+
-v bucket/user/transcripts:/output \
|
| 28 |
+
transcribe-transformers.py /input /output --language en --compile
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
No download/upload step. Buckets are mounted directly as volumes via [hf-mount](https://github.com/huggingface/hf-mount).
|
| 32 |
+
|
| 33 |
+
## Scripts
|
| 34 |
+
|
| 35 |
+
### Transcription
|
| 36 |
+
|
| 37 |
+
| Script | Model | Backend | Speed (A100) |
|
| 38 |
+
|--------|-------|---------|--------------|
|
| 39 |
+
| `transcribe-transformers.py` | Cohere Transcribe (2B) | transformers | 161x RT |
|
| 40 |
+
| `transcribe.py` | Cohere Transcribe (2B) | vLLM nightly | 214x RT |
|
| 41 |
+
|
| 42 |
+
**`transcribe-transformers.py`** (recommended) — uses `model.transcribe()` with automatic long-form chunking, overlap, and reassembly. Stable dependencies.
|
| 43 |
+
|
| 44 |
+
**`transcribe.py`** — experimental vLLM variant. Faster but requires nightly vLLM and has minor duplication at chunk boundaries.
|
| 45 |
+
|
| 46 |
+
#### Options
|
| 47 |
+
|
| 48 |
+
| Flag | Default | Description |
|
| 49 |
+
|------|---------|-------------|
|
| 50 |
+
| `--language` | required | en, de, fr, it, es, pt, el, nl, pl, ar, vi, zh, ja, ko |
|
| 51 |
+
| `--compile` | off | torch.compile encoder (one-time warmup, faster after) |
|
| 52 |
+
| `--batch-size` | 16 | Batch size for inference |
|
| 53 |
+
| `--max-files` | all | Limit files to process (for testing) |
|
| 54 |
+
|
| 55 |
+
#### Benchmarks
|
| 56 |
+
|
| 57 |
+
CBS Suspense (1940s radio drama), 66 episodes, 33 hours of audio:
|
| 58 |
+
|
| 59 |
+
| GPU | Time | RTFx |
|
| 60 |
+
|-----|------|------|
|
| 61 |
+
| A100-SXM4-80GB | 12.3 min | 161x realtime |
|
| 62 |
+
| L4 | ~64s / 30 min episode | 28x realtime |
|
| 63 |
+
|
| 64 |
+
### Data
|
| 65 |
+
|
| 66 |
+
| Script | Description |
|
| 67 |
+
|--------|-------------|
|
| 68 |
+
| `download-ia.py` | Download audio from Internet Archive into a mounted bucket |
|
| 69 |
+
|
| 70 |
+
## Notes
|
| 71 |
+
|
| 72 |
+
- **`UV_TORCH_BACKEND=cu124`**: Needed on A100 for correct CUDA torch build. Not needed on L4.
|
| 73 |
+
- **`torch==2.6.0`**: Pinned for A100 CUDA driver compatibility.
|
| 74 |
+
- **Gated model**: Accept terms at the [model page](https://huggingface.co/CohereLabs/cohere-transcribe-03-2026) before use.
|
| 75 |
+
- **Tokenizer workaround**: `transcribe-transformers.py` applies a one-line patch for a tokenizer compat issue. Will be removed once upstream fixes land ([model discussion](https://huggingface.co/CohereLabs/cohere-transcribe-03-2026/discussions/11)).
|
download-ia.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "internetarchive",
|
| 5 |
+
# "huggingface-hub",
|
| 6 |
+
# ]
|
| 7 |
+
# ///
|
| 8 |
+
|
| 9 |
+
"""
|
| 10 |
+
Download audio files from an Internet Archive item to an HF Bucket.
|
| 11 |
+
|
| 12 |
+
Designed to run as a CPU HF Job with a mounted output bucket.
|
| 13 |
+
|
| 14 |
+
Examples:
|
| 15 |
+
|
| 16 |
+
# Local — download to a local directory
|
| 17 |
+
uv run download-ia.py SUSPENSE ./suspense-audio
|
| 18 |
+
|
| 19 |
+
# HF Jobs — download straight into a bucket
|
| 20 |
+
hf jobs uv run \
|
| 21 |
+
-v bucket/user/audio-bucket:/output \
|
| 22 |
+
download-ia.py SUSPENSE /output
|
| 23 |
+
|
| 24 |
+
# With filters
|
| 25 |
+
uv run download-ia.py SUSPENSE ./output --glob '43-*' --max-files 10
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
import argparse
|
| 29 |
+
import logging
|
| 30 |
+
import sys
|
| 31 |
+
import time
|
| 32 |
+
from pathlib import Path
|
| 33 |
+
|
| 34 |
+
logging.basicConfig(
|
| 35 |
+
level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s"
|
| 36 |
+
)
|
| 37 |
+
logger = logging.getLogger(__name__)
|
| 38 |
+
|
| 39 |
+
AUDIO_EXTENSIONS = {".mp3", ".wav", ".flac", ".ogg", ".m4a", ".aac", ".opus"}
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def main():
|
| 43 |
+
parser = argparse.ArgumentParser(
|
| 44 |
+
description="Download audio files from Internet Archive to a directory.",
|
| 45 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 46 |
+
epilog="""
|
| 47 |
+
Examples:
|
| 48 |
+
uv run download-ia.py SUSPENSE ./output
|
| 49 |
+
uv run download-ia.py SUSPENSE ./output --glob '43-*' --max-files 10
|
| 50 |
+
uv run download-ia.py Dragnet_OTR ./output --max-files 20
|
| 51 |
+
|
| 52 |
+
HF Jobs with bucket volume:
|
| 53 |
+
hf jobs uv run \\
|
| 54 |
+
-v bucket/user/audio-bucket:/output \\
|
| 55 |
+
download-ia.py SUSPENSE /output
|
| 56 |
+
""",
|
| 57 |
+
)
|
| 58 |
+
parser.add_argument("item_id", help="Internet Archive item identifier")
|
| 59 |
+
parser.add_argument("output_dir", help="Directory to download files to")
|
| 60 |
+
parser.add_argument(
|
| 61 |
+
"--glob",
|
| 62 |
+
default="*.mp3",
|
| 63 |
+
help="Glob pattern for files to download (default: *.mp3)",
|
| 64 |
+
)
|
| 65 |
+
parser.add_argument(
|
| 66 |
+
"--max-files",
|
| 67 |
+
type=int,
|
| 68 |
+
default=None,
|
| 69 |
+
help="Limit number of files to download",
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
args = parser.parse_args()
|
| 73 |
+
|
| 74 |
+
output_dir = Path(args.output_dir)
|
| 75 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 76 |
+
|
| 77 |
+
import internetarchive as ia
|
| 78 |
+
|
| 79 |
+
logger.info(f"Fetching file list for '{args.item_id}'...")
|
| 80 |
+
item = ia.get_item(args.item_id)
|
| 81 |
+
|
| 82 |
+
# Filter to audio files matching glob
|
| 83 |
+
import fnmatch
|
| 84 |
+
|
| 85 |
+
files = []
|
| 86 |
+
for f in item.files:
|
| 87 |
+
name = f["name"]
|
| 88 |
+
ext = Path(name).suffix.lower()
|
| 89 |
+
if ext in AUDIO_EXTENSIONS and fnmatch.fnmatch(name, args.glob):
|
| 90 |
+
files.append(f)
|
| 91 |
+
|
| 92 |
+
files.sort(key=lambda f: f["name"])
|
| 93 |
+
|
| 94 |
+
if not files:
|
| 95 |
+
logger.error(f"No audio files matching '{args.glob}' in item '{args.item_id}'")
|
| 96 |
+
sys.exit(1)
|
| 97 |
+
|
| 98 |
+
if args.max_files:
|
| 99 |
+
files = files[: args.max_files]
|
| 100 |
+
|
| 101 |
+
total_size = sum(int(f.get("size", 0)) for f in files)
|
| 102 |
+
logger.info(
|
| 103 |
+
f"Downloading {len(files)} file(s) "
|
| 104 |
+
f"({total_size / 1024 / 1024:.1f} MB) from '{args.item_id}'"
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
start_time = time.time()
|
| 108 |
+
downloaded = 0
|
| 109 |
+
|
| 110 |
+
for i, f in enumerate(files, 1):
|
| 111 |
+
name = f["name"]
|
| 112 |
+
dest = output_dir / name
|
| 113 |
+
if dest.exists():
|
| 114 |
+
logger.info(f" [{i}/{len(files)}] {name} (already exists, skipping)")
|
| 115 |
+
downloaded += 1
|
| 116 |
+
continue
|
| 117 |
+
|
| 118 |
+
logger.info(f" [{i}/{len(files)}] {name} ({int(f.get('size', 0)) / 1024 / 1024:.1f} MB)")
|
| 119 |
+
item.download(files=[name], destdir=str(output_dir), no_directory=True)
|
| 120 |
+
downloaded += 1
|
| 121 |
+
|
| 122 |
+
elapsed = time.time() - start_time
|
| 123 |
+
elapsed_str = f"{elapsed / 60:.1f} min" if elapsed > 60 else f"{elapsed:.1f}s"
|
| 124 |
+
|
| 125 |
+
logger.info("=" * 50)
|
| 126 |
+
logger.info(f"Done! Downloaded {downloaded} file(s) in {elapsed_str}")
|
| 127 |
+
logger.info(f" Output: {output_dir}")
|
| 128 |
+
logger.info(f" Total size: {total_size / 1024 / 1024:.1f} MB")
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
if __name__ == "__main__":
|
| 132 |
+
if len(sys.argv) == 1:
|
| 133 |
+
print("=" * 60)
|
| 134 |
+
print("Download Internet Archive Audio to Directory/Bucket")
|
| 135 |
+
print("=" * 60)
|
| 136 |
+
print()
|
| 137 |
+
print("Usage:")
|
| 138 |
+
print(" uv run download-ia.py ITEM_ID OUTPUT_DIR")
|
| 139 |
+
print()
|
| 140 |
+
print("Examples:")
|
| 141 |
+
print(" uv run download-ia.py SUSPENSE ./suspense-audio")
|
| 142 |
+
print(" uv run download-ia.py Dragnet_OTR ./dragnet --max-files 20")
|
| 143 |
+
print()
|
| 144 |
+
print("HF Jobs with bucket:")
|
| 145 |
+
print(" hf jobs uv run \\")
|
| 146 |
+
print(" -v bucket/user/audio-bucket:/output \\")
|
| 147 |
+
print(" download-ia.py SUSPENSE /output")
|
| 148 |
+
print()
|
| 149 |
+
print("For full help: uv run download-ia.py --help")
|
| 150 |
+
sys.exit(0)
|
| 151 |
+
|
| 152 |
+
main()
|
transcribe-transformers.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "transformers>=4.56,<5.3,!=5.0.*,!=5.1.*",
|
| 5 |
+
# "torch==2.6.0",
|
| 6 |
+
# "huggingface-hub",
|
| 7 |
+
# "soundfile",
|
| 8 |
+
# "librosa",
|
| 9 |
+
# "sentencepiece",
|
| 10 |
+
# "protobuf",
|
| 11 |
+
# ]
|
| 12 |
+
# ///
|
| 13 |
+
|
| 14 |
+
"""
|
| 15 |
+
Transcribe audio files from a directory using Cohere Transcribe via transformers.
|
| 16 |
+
|
| 17 |
+
Uses model.transcribe() which handles long-form audio automatically (chunking,
|
| 18 |
+
overlap, reassembly). No nightly dependencies required.
|
| 19 |
+
|
| 20 |
+
Designed to work with HF Buckets mounted as volumes via `hf jobs uv run -v ...`.
|
| 21 |
+
|
| 22 |
+
Input: Output:
|
| 23 |
+
/input/episode1.mp3 -> /output/episode1.txt
|
| 24 |
+
/input/sub/clip.wav -> /output/sub/clip.txt
|
| 25 |
+
|
| 26 |
+
Examples:
|
| 27 |
+
|
| 28 |
+
# Local test (requires CUDA GPU)
|
| 29 |
+
uv run transcribe-transformers.py ./test-audio ./test-output --language en
|
| 30 |
+
|
| 31 |
+
# HF Jobs with bucket volumes
|
| 32 |
+
hf jobs uv run --flavor l4x1 \\
|
| 33 |
+
-s HF_TOKEN \\
|
| 34 |
+
-v bucket/user/audio-input:/input:ro \\
|
| 35 |
+
-v bucket/user/transcripts:/output \\
|
| 36 |
+
transcribe-transformers.py /input /output --language en --compile
|
| 37 |
+
|
| 38 |
+
Model: CohereLabs/cohere-transcribe-03-2026 (2B, Apache 2.0)
|
| 39 |
+
- 14 languages: en, de, fr, it, es, pt, el, nl, pl, ar, vi, zh, ja, ko
|
| 40 |
+
- Automatic long-form chunking (>35s handled transparently)
|
| 41 |
+
- compile=True for torch.compile speedup (one-time warmup cost)
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
import argparse
|
| 45 |
+
import json
|
| 46 |
+
import logging
|
| 47 |
+
import sys
|
| 48 |
+
import time
|
| 49 |
+
from pathlib import Path
|
| 50 |
+
|
| 51 |
+
import torch
|
| 52 |
+
|
| 53 |
+
logging.basicConfig(
|
| 54 |
+
level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s"
|
| 55 |
+
)
|
| 56 |
+
logger = logging.getLogger(__name__)
|
| 57 |
+
|
| 58 |
+
MODEL = "CohereLabs/cohere-transcribe-03-2026"
|
| 59 |
+
|
| 60 |
+
AUDIO_EXTENSIONS = {".mp3", ".wav", ".flac", ".ogg", ".m4a", ".wma", ".aac", ".opus"}
|
| 61 |
+
|
| 62 |
+
SUPPORTED_LANGUAGES = {
|
| 63 |
+
"en", "de", "fr", "it", "es", "pt", "el", "nl", "pl", "ar", "vi", "zh", "ja", "ko",
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def check_cuda_availability():
|
| 68 |
+
if not torch.cuda.is_available():
|
| 69 |
+
logger.error("CUDA is not available. This script requires a GPU.")
|
| 70 |
+
sys.exit(1)
|
| 71 |
+
logger.info(f"CUDA available. GPU: {torch.cuda.get_device_name(0)}")
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def discover_audio_files(input_dir: Path) -> list[Path]:
|
| 75 |
+
"""Walk input_dir recursively, returning sorted list of audio files."""
|
| 76 |
+
files = []
|
| 77 |
+
for path in sorted(input_dir.rglob("*")):
|
| 78 |
+
if path.is_file() and path.suffix.lower() in AUDIO_EXTENSIONS:
|
| 79 |
+
files.append(path)
|
| 80 |
+
return files
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def get_audio_duration(file_path: Path) -> float | None:
|
| 84 |
+
"""Get audio duration in seconds."""
|
| 85 |
+
try:
|
| 86 |
+
import librosa
|
| 87 |
+
return librosa.get_duration(path=str(file_path))
|
| 88 |
+
except Exception:
|
| 89 |
+
return None
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def main():
|
| 93 |
+
parser = argparse.ArgumentParser(
|
| 94 |
+
description="Transcribe audio files using Cohere Transcribe (transformers).",
|
| 95 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 96 |
+
epilog="""
|
| 97 |
+
Languages: en, de, fr, it, es, pt, el, nl, pl, ar, vi, zh, ja, ko
|
| 98 |
+
|
| 99 |
+
Examples:
|
| 100 |
+
uv run transcribe-transformers.py ./audio ./output --language en
|
| 101 |
+
uv run transcribe-transformers.py /input /output --language en --compile
|
| 102 |
+
|
| 103 |
+
HF Jobs with bucket volumes:
|
| 104 |
+
hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
|
| 105 |
+
-v bucket/user/audio-bucket:/input:ro \\
|
| 106 |
+
-v bucket/user/transcripts:/output \\
|
| 107 |
+
transcribe-transformers.py /input /output --language en --compile
|
| 108 |
+
""",
|
| 109 |
+
)
|
| 110 |
+
parser.add_argument("input_dir", help="Directory containing audio files")
|
| 111 |
+
parser.add_argument("output_dir", help="Directory to write transcript text files")
|
| 112 |
+
parser.add_argument(
|
| 113 |
+
"--language",
|
| 114 |
+
required=True,
|
| 115 |
+
choices=sorted(SUPPORTED_LANGUAGES),
|
| 116 |
+
help="Language code (required, model does not auto-detect)",
|
| 117 |
+
)
|
| 118 |
+
parser.add_argument(
|
| 119 |
+
"--batch-size",
|
| 120 |
+
type=int,
|
| 121 |
+
default=16,
|
| 122 |
+
help="Batch size for inference (default: 16)",
|
| 123 |
+
)
|
| 124 |
+
parser.add_argument(
|
| 125 |
+
"--compile",
|
| 126 |
+
action="store_true",
|
| 127 |
+
help="Use torch.compile for faster throughput (one-time warmup cost)",
|
| 128 |
+
)
|
| 129 |
+
parser.add_argument(
|
| 130 |
+
"--max-files",
|
| 131 |
+
type=int,
|
| 132 |
+
default=None,
|
| 133 |
+
help="Limit number of files to process (for testing)",
|
| 134 |
+
)
|
| 135 |
+
parser.add_argument(
|
| 136 |
+
"--verbose",
|
| 137 |
+
action="store_true",
|
| 138 |
+
help="Print resolved package versions",
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
args = parser.parse_args()
|
| 142 |
+
|
| 143 |
+
check_cuda_availability()
|
| 144 |
+
|
| 145 |
+
input_dir = Path(args.input_dir)
|
| 146 |
+
output_dir = Path(args.output_dir)
|
| 147 |
+
|
| 148 |
+
if not input_dir.is_dir():
|
| 149 |
+
logger.error(f"Input directory does not exist: {input_dir}")
|
| 150 |
+
sys.exit(1)
|
| 151 |
+
|
| 152 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 153 |
+
|
| 154 |
+
# Discover audio files
|
| 155 |
+
logger.info(f"Scanning {input_dir} for audio files...")
|
| 156 |
+
files = discover_audio_files(input_dir)
|
| 157 |
+
if not files:
|
| 158 |
+
logger.error(f"No audio files found in {input_dir}")
|
| 159 |
+
logger.error(f"Supported extensions: {', '.join(sorted(AUDIO_EXTENSIONS))}")
|
| 160 |
+
sys.exit(1)
|
| 161 |
+
|
| 162 |
+
if args.max_files:
|
| 163 |
+
files = files[: args.max_files]
|
| 164 |
+
|
| 165 |
+
logger.info(f"Found {len(files)} audio file(s)")
|
| 166 |
+
|
| 167 |
+
# Load model
|
| 168 |
+
logger.info(f"Loading {MODEL}...")
|
| 169 |
+
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor
|
| 170 |
+
|
| 171 |
+
processor = AutoProcessor.from_pretrained(MODEL, trust_remote_code=True)
|
| 172 |
+
|
| 173 |
+
# Workaround: model.transcribe() -> _ensure_decode_pool accesses tokenizer
|
| 174 |
+
# attributes that CohereAsrTokenizer doesn't expose via the standard
|
| 175 |
+
# transformers interface. Patch them so transcribe() can build its pool.
|
| 176 |
+
tokenizer = processor.tokenizer
|
| 177 |
+
if not hasattr(tokenizer, "additional_special_tokens"):
|
| 178 |
+
tokenizer.additional_special_tokens = []
|
| 179 |
+
|
| 180 |
+
model = AutoModelForSpeechSeq2Seq.from_pretrained(
|
| 181 |
+
MODEL, trust_remote_code=True
|
| 182 |
+
).to("cuda:0")
|
| 183 |
+
model.eval()
|
| 184 |
+
logger.info("Model loaded")
|
| 185 |
+
|
| 186 |
+
# Transcribe all files — model.transcribe() handles chunking and batching
|
| 187 |
+
file_paths = [str(f) for f in files]
|
| 188 |
+
|
| 189 |
+
logger.info(
|
| 190 |
+
f"Transcribing {len(files)} file(s) "
|
| 191 |
+
f"(compile={args.compile}, batch_size={args.batch_size})..."
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
start_time = time.time()
|
| 195 |
+
|
| 196 |
+
texts = model.transcribe(
|
| 197 |
+
processor=processor,
|
| 198 |
+
audio_files=file_paths,
|
| 199 |
+
language=args.language,
|
| 200 |
+
compile=args.compile,
|
| 201 |
+
pipeline_detokenization=True,
|
| 202 |
+
batch_size=args.batch_size,
|
| 203 |
+
)
|
| 204 |
+
|
| 205 |
+
elapsed = time.time() - start_time
|
| 206 |
+
|
| 207 |
+
# Write outputs
|
| 208 |
+
total_audio_duration = 0.0
|
| 209 |
+
results = []
|
| 210 |
+
|
| 211 |
+
for file_path, text in zip(files, texts):
|
| 212 |
+
rel = file_path.relative_to(input_dir)
|
| 213 |
+
txt_path = output_dir / rel.with_suffix(".txt")
|
| 214 |
+
txt_path.parent.mkdir(parents=True, exist_ok=True)
|
| 215 |
+
txt_path.write_text(text, encoding="utf-8")
|
| 216 |
+
|
| 217 |
+
duration = get_audio_duration(file_path)
|
| 218 |
+
if duration:
|
| 219 |
+
total_audio_duration += duration
|
| 220 |
+
|
| 221 |
+
results.append({
|
| 222 |
+
"file": str(rel),
|
| 223 |
+
"duration_s": round(duration, 1) if duration else None,
|
| 224 |
+
"transcript_length": len(text),
|
| 225 |
+
"word_count": len(text.split()),
|
| 226 |
+
})
|
| 227 |
+
logger.info(
|
| 228 |
+
f" {rel} -> {txt_path.name} "
|
| 229 |
+
f"({len(text.split())} words"
|
| 230 |
+
f"{f', {duration:.0f}s audio' if duration else ''})"
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
# Write summary
|
| 234 |
+
summary_path = output_dir / "summary.jsonl"
|
| 235 |
+
with open(summary_path, "w", encoding="utf-8") as f:
|
| 236 |
+
for r in results:
|
| 237 |
+
f.write(json.dumps(r) + "\n")
|
| 238 |
+
|
| 239 |
+
# Report
|
| 240 |
+
elapsed_str = f"{elapsed / 60:.1f} min" if elapsed > 60 else f"{elapsed:.1f}s"
|
| 241 |
+
logger.info("=" * 50)
|
| 242 |
+
logger.info(f"Done! Transcribed {len(files)} file(s) in {elapsed_str}")
|
| 243 |
+
logger.info(f" Output: {output_dir}")
|
| 244 |
+
if total_audio_duration > 0:
|
| 245 |
+
rtfx = total_audio_duration / elapsed
|
| 246 |
+
logger.info(f" Audio: {total_audio_duration / 60:.1f} min total")
|
| 247 |
+
logger.info(f" RTFx: {rtfx:.1f}x realtime")
|
| 248 |
+
logger.info(f" Summary: {summary_path}")
|
| 249 |
+
|
| 250 |
+
if args.verbose:
|
| 251 |
+
import importlib.metadata
|
| 252 |
+
logger.info("--- Package versions ---")
|
| 253 |
+
for pkg in ["transformers", "torch", "librosa", "soundfile", "huggingface-hub"]:
|
| 254 |
+
try:
|
| 255 |
+
logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
|
| 256 |
+
except importlib.metadata.PackageNotFoundError:
|
| 257 |
+
logger.info(f" {pkg}: not installed")
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
if __name__ == "__main__":
|
| 261 |
+
if len(sys.argv) == 1:
|
| 262 |
+
print("=" * 60)
|
| 263 |
+
print("Audio Transcription with Cohere Transcribe (transformers)")
|
| 264 |
+
print("=" * 60)
|
| 265 |
+
print("\nTranscribe audio files from a directory -> text files.")
|
| 266 |
+
print("Long audio handled automatically (chunking + overlap).")
|
| 267 |
+
print("Designed for HF Buckets mounted as volumes.")
|
| 268 |
+
print()
|
| 269 |
+
print("Usage:")
|
| 270 |
+
print(" uv run transcribe-transformers.py INPUT_DIR OUTPUT_DIR --language en")
|
| 271 |
+
print()
|
| 272 |
+
print("Examples:")
|
| 273 |
+
print(" uv run transcribe-transformers.py ./audio ./output --language en")
|
| 274 |
+
print(" uv run transcribe-transformers.py ./audio ./output --language en --compile")
|
| 275 |
+
print()
|
| 276 |
+
print("HF Jobs with bucket volumes:")
|
| 277 |
+
print(" hf jobs uv run --flavor l4x1 -s HF_TOKEN \\")
|
| 278 |
+
print(" -v bucket/user/audio-input:/input:ro \\")
|
| 279 |
+
print(" -v bucket/user/transcripts:/output \\")
|
| 280 |
+
print(" transcribe-transformers.py /input /output --language en --compile")
|
| 281 |
+
print()
|
| 282 |
+
print("For full help: uv run transcribe-transformers.py --help")
|
| 283 |
+
sys.exit(0)
|
| 284 |
+
|
| 285 |
+
main()
|
transcribe.py
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "vllm",
|
| 5 |
+
# "torch",
|
| 6 |
+
# "huggingface-hub",
|
| 7 |
+
# "soundfile",
|
| 8 |
+
# "librosa",
|
| 9 |
+
# "numpy",
|
| 10 |
+
# ]
|
| 11 |
+
#
|
| 12 |
+
# [[tool.uv.index]]
|
| 13 |
+
# url = "https://wheels.vllm.ai/nightly/cu129"
|
| 14 |
+
#
|
| 15 |
+
# [tool.uv]
|
| 16 |
+
# prerelease = "allow"
|
| 17 |
+
# ///
|
| 18 |
+
|
| 19 |
+
"""
|
| 20 |
+
Transcribe audio files from a directory using Cohere Transcribe via vLLM.
|
| 21 |
+
|
| 22 |
+
Designed to work with HF Buckets mounted as volumes via `hf jobs uv run -v ...`.
|
| 23 |
+
|
| 24 |
+
Long audio files (>30s) are automatically chunked with overlap and reassembled.
|
| 25 |
+
All chunks from all files are batched through vLLM in a single call for maximum
|
| 26 |
+
throughput.
|
| 27 |
+
|
| 28 |
+
Input: Output:
|
| 29 |
+
/input/episode1.mp3 -> /output/episode1.txt
|
| 30 |
+
/input/sub/clip.wav -> /output/sub/clip.txt
|
| 31 |
+
|
| 32 |
+
Examples:
|
| 33 |
+
|
| 34 |
+
# Local test (requires CUDA GPU)
|
| 35 |
+
uv run transcribe.py ./test-audio ./test-output --language en
|
| 36 |
+
|
| 37 |
+
# HF Jobs with bucket volumes
|
| 38 |
+
hf jobs uv run --flavor l4x1 \\
|
| 39 |
+
-s HF_TOKEN \\
|
| 40 |
+
-v bucket/user/audio-input:/input:ro \\
|
| 41 |
+
-v bucket/user/transcripts:/output \\
|
| 42 |
+
transcribe.py /input /output --language en
|
| 43 |
+
|
| 44 |
+
Model: CohereLabs/cohere-transcribe-03-2026 (2B, Apache 2.0)
|
| 45 |
+
- 14 languages: en, de, fr, it, es, pt, el, nl, pl, ar, vi, zh, ja, ko
|
| 46 |
+
- Up to 3x faster than other dedicated ASR models in same size range
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
import argparse
|
| 50 |
+
import json
|
| 51 |
+
import logging
|
| 52 |
+
import sys
|
| 53 |
+
import time
|
| 54 |
+
from pathlib import Path
|
| 55 |
+
|
| 56 |
+
import numpy as np
|
| 57 |
+
import torch
|
| 58 |
+
|
| 59 |
+
logging.basicConfig(
|
| 60 |
+
level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s"
|
| 61 |
+
)
|
| 62 |
+
logger = logging.getLogger(__name__)
|
| 63 |
+
|
| 64 |
+
MODEL = "CohereLabs/cohere-transcribe-03-2026"
|
| 65 |
+
|
| 66 |
+
AUDIO_EXTENSIONS = {".mp3", ".wav", ".flac", ".ogg", ".m4a", ".wma", ".aac", ".opus"}
|
| 67 |
+
|
| 68 |
+
SUPPORTED_LANGUAGES = {
|
| 69 |
+
"en", "de", "fr", "it", "es", "pt", "el", "nl", "pl", "ar", "vi", "zh", "ja", "ko",
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
# Chunking config — matches model's internal chunking behavior
|
| 73 |
+
CHUNK_DURATION_S = 30 # seconds per chunk
|
| 74 |
+
OVERLAP_S = 2 # overlap between chunks to avoid cutting mid-word
|
| 75 |
+
SAMPLE_RATE = 16000
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def check_cuda_availability():
|
| 79 |
+
if not torch.cuda.is_available():
|
| 80 |
+
logger.error("CUDA is not available. This script requires a GPU.")
|
| 81 |
+
sys.exit(1)
|
| 82 |
+
logger.info(f"CUDA available. GPU: {torch.cuda.get_device_name(0)}")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def discover_audio_files(input_dir: Path) -> list[Path]:
|
| 86 |
+
"""Walk input_dir recursively, returning sorted list of audio files."""
|
| 87 |
+
files = []
|
| 88 |
+
for path in sorted(input_dir.rglob("*")):
|
| 89 |
+
if path.is_file() and path.suffix.lower() in AUDIO_EXTENSIONS:
|
| 90 |
+
files.append(path)
|
| 91 |
+
return files
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def load_audio(file_path: Path) -> tuple[np.ndarray, int]:
|
| 95 |
+
"""Load audio file resampled to 16kHz mono."""
|
| 96 |
+
import librosa
|
| 97 |
+
audio, sr = librosa.load(str(file_path), sr=SAMPLE_RATE, mono=True)
|
| 98 |
+
return audio, sr
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def chunk_audio(audio: np.ndarray, sr: int) -> list[np.ndarray]:
|
| 102 |
+
"""Split audio into overlapping chunks. Short audio returned as single chunk."""
|
| 103 |
+
chunk_samples = CHUNK_DURATION_S * sr
|
| 104 |
+
overlap_samples = OVERLAP_S * sr
|
| 105 |
+
step = chunk_samples - overlap_samples
|
| 106 |
+
|
| 107 |
+
if len(audio) <= chunk_samples:
|
| 108 |
+
return [audio]
|
| 109 |
+
|
| 110 |
+
chunks = []
|
| 111 |
+
start = 0
|
| 112 |
+
while start < len(audio):
|
| 113 |
+
end = min(start + chunk_samples, len(audio))
|
| 114 |
+
chunks.append(audio[start:end])
|
| 115 |
+
if end >= len(audio):
|
| 116 |
+
break
|
| 117 |
+
start += step
|
| 118 |
+
|
| 119 |
+
return chunks
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def build_prompt(language: str) -> str:
|
| 123 |
+
"""Build the CohereASR prompt with language tokens."""
|
| 124 |
+
return (
|
| 125 |
+
f"<|startofcontext|><|startoftranscript|>"
|
| 126 |
+
f"<|emo:undefined|><|{language}|><|{language}|><|pnc|><|noitn|>"
|
| 127 |
+
f"<|notimestamp|><|nodiarize|>"
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def main():
|
| 132 |
+
parser = argparse.ArgumentParser(
|
| 133 |
+
description="Transcribe audio files using Cohere Transcribe via vLLM.",
|
| 134 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 135 |
+
epilog="""
|
| 136 |
+
Languages: en, de, fr, it, es, pt, el, nl, pl, ar, vi, zh, ja, ko
|
| 137 |
+
|
| 138 |
+
Examples:
|
| 139 |
+
uv run transcribe.py ./audio ./output --language en
|
| 140 |
+
uv run transcribe.py /input /output --language en --max-files 3
|
| 141 |
+
|
| 142 |
+
HF Jobs with bucket volumes:
|
| 143 |
+
hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
|
| 144 |
+
-v bucket/user/audio-bucket:/input:ro \\
|
| 145 |
+
-v bucket/user/transcripts:/output \\
|
| 146 |
+
transcribe.py /input /output --language en
|
| 147 |
+
""",
|
| 148 |
+
)
|
| 149 |
+
parser.add_argument("input_dir", help="Directory containing audio files")
|
| 150 |
+
parser.add_argument("output_dir", help="Directory to write transcript text files")
|
| 151 |
+
parser.add_argument(
|
| 152 |
+
"--language",
|
| 153 |
+
required=True,
|
| 154 |
+
choices=sorted(SUPPORTED_LANGUAGES),
|
| 155 |
+
help="Language code (required, model does not auto-detect)",
|
| 156 |
+
)
|
| 157 |
+
parser.add_argument(
|
| 158 |
+
"--max-files",
|
| 159 |
+
type=int,
|
| 160 |
+
default=None,
|
| 161 |
+
help="Limit number of files to process (for testing)",
|
| 162 |
+
)
|
| 163 |
+
parser.add_argument(
|
| 164 |
+
"--gpu-memory-utilization",
|
| 165 |
+
type=float,
|
| 166 |
+
default=0.8,
|
| 167 |
+
help="GPU memory utilization (default: 0.8)",
|
| 168 |
+
)
|
| 169 |
+
parser.add_argument(
|
| 170 |
+
"--verbose",
|
| 171 |
+
action="store_true",
|
| 172 |
+
help="Print resolved package versions",
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
args = parser.parse_args()
|
| 176 |
+
|
| 177 |
+
check_cuda_availability()
|
| 178 |
+
|
| 179 |
+
input_dir = Path(args.input_dir)
|
| 180 |
+
output_dir = Path(args.output_dir)
|
| 181 |
+
|
| 182 |
+
if not input_dir.is_dir():
|
| 183 |
+
logger.error(f"Input directory does not exist: {input_dir}")
|
| 184 |
+
sys.exit(1)
|
| 185 |
+
|
| 186 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 187 |
+
|
| 188 |
+
# Discover audio files
|
| 189 |
+
logger.info(f"Scanning {input_dir} for audio files...")
|
| 190 |
+
files = discover_audio_files(input_dir)
|
| 191 |
+
if not files:
|
| 192 |
+
logger.error(f"No audio files found in {input_dir}")
|
| 193 |
+
logger.error(f"Supported extensions: {', '.join(sorted(AUDIO_EXTENSIONS))}")
|
| 194 |
+
sys.exit(1)
|
| 195 |
+
|
| 196 |
+
if args.max_files:
|
| 197 |
+
files = files[: args.max_files]
|
| 198 |
+
|
| 199 |
+
logger.info(f"Found {len(files)} audio file(s)")
|
| 200 |
+
|
| 201 |
+
# Load and chunk audio files
|
| 202 |
+
logger.info("Loading and chunking audio files...")
|
| 203 |
+
file_audio = [] # (file_path, full_audio, sr)
|
| 204 |
+
all_chunks = [] # (file_index, chunk_array) — flat list for batching
|
| 205 |
+
for i, f in enumerate(files):
|
| 206 |
+
audio, sr = load_audio(f)
|
| 207 |
+
file_audio.append((f, audio, sr))
|
| 208 |
+
chunks = chunk_audio(audio, sr)
|
| 209 |
+
duration = len(audio) / sr
|
| 210 |
+
logger.info(f" {f.name}: {duration:.0f}s -> {len(chunks)} chunk(s)")
|
| 211 |
+
for chunk in chunks:
|
| 212 |
+
all_chunks.append((i, chunk))
|
| 213 |
+
|
| 214 |
+
total_chunks = len(all_chunks)
|
| 215 |
+
logger.info(f"Total chunks to transcribe: {total_chunks}")
|
| 216 |
+
|
| 217 |
+
# Init vLLM
|
| 218 |
+
logger.info(f"Initializing vLLM with {MODEL}...")
|
| 219 |
+
from vllm import LLM, SamplingParams
|
| 220 |
+
|
| 221 |
+
llm = LLM(
|
| 222 |
+
model=MODEL,
|
| 223 |
+
trust_remote_code=True,
|
| 224 |
+
limit_mm_per_prompt={"audio": 1},
|
| 225 |
+
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
sampling_params = SamplingParams(
|
| 229 |
+
temperature=0.0,
|
| 230 |
+
max_tokens=1024,
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
# Build inputs — one prompt per chunk
|
| 234 |
+
prompt = build_prompt(args.language)
|
| 235 |
+
inputs = [
|
| 236 |
+
{
|
| 237 |
+
"prompt": prompt,
|
| 238 |
+
"multi_modal_data": {"audio": [(chunk, SAMPLE_RATE)]},
|
| 239 |
+
}
|
| 240 |
+
for _, chunk in all_chunks
|
| 241 |
+
]
|
| 242 |
+
|
| 243 |
+
# Transcribe all chunks in one batch
|
| 244 |
+
logger.info(f"Transcribing {total_chunks} chunk(s) across {len(files)} file(s)...")
|
| 245 |
+
start_time = time.time()
|
| 246 |
+
|
| 247 |
+
outputs = llm.generate(inputs, sampling_params)
|
| 248 |
+
|
| 249 |
+
elapsed = time.time() - start_time
|
| 250 |
+
|
| 251 |
+
# Reassemble chunks per file
|
| 252 |
+
file_texts: dict[int, list[str]] = {}
|
| 253 |
+
for (file_idx, _), output in zip(all_chunks, outputs):
|
| 254 |
+
text = output.outputs[0].text.strip()
|
| 255 |
+
file_texts.setdefault(file_idx, []).append(text)
|
| 256 |
+
|
| 257 |
+
# Write outputs
|
| 258 |
+
total_audio_duration = 0.0
|
| 259 |
+
results = []
|
| 260 |
+
|
| 261 |
+
for i, (file_path, audio, sr) in enumerate(file_audio):
|
| 262 |
+
chunks_text = file_texts.get(i, [])
|
| 263 |
+
full_text = " ".join(chunks_text)
|
| 264 |
+
|
| 265 |
+
rel = file_path.relative_to(input_dir)
|
| 266 |
+
txt_path = output_dir / rel.with_suffix(".txt")
|
| 267 |
+
txt_path.parent.mkdir(parents=True, exist_ok=True)
|
| 268 |
+
txt_path.write_text(full_text, encoding="utf-8")
|
| 269 |
+
|
| 270 |
+
duration = len(audio) / sr
|
| 271 |
+
total_audio_duration += duration
|
| 272 |
+
|
| 273 |
+
results.append({
|
| 274 |
+
"file": str(rel),
|
| 275 |
+
"duration_s": round(duration, 1),
|
| 276 |
+
"chunks": len(chunks_text),
|
| 277 |
+
"transcript_length": len(full_text),
|
| 278 |
+
"word_count": len(full_text.split()),
|
| 279 |
+
})
|
| 280 |
+
logger.info(
|
| 281 |
+
f" {rel} -> {txt_path.name} "
|
| 282 |
+
f"({len(full_text.split())} words, {len(chunks_text)} chunks, "
|
| 283 |
+
f"{duration:.0f}s audio)"
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
# Write summary
|
| 287 |
+
summary_path = output_dir / "summary.jsonl"
|
| 288 |
+
with open(summary_path, "w", encoding="utf-8") as f:
|
| 289 |
+
for r in results:
|
| 290 |
+
f.write(json.dumps(r) + "\n")
|
| 291 |
+
|
| 292 |
+
# Report
|
| 293 |
+
elapsed_str = f"{elapsed / 60:.1f} min" if elapsed > 60 else f"{elapsed:.1f}s"
|
| 294 |
+
rtfx = total_audio_duration / elapsed if elapsed > 0 else 0
|
| 295 |
+
logger.info("=" * 50)
|
| 296 |
+
logger.info(f"Done! Transcribed {len(files)} file(s) in {elapsed_str}")
|
| 297 |
+
logger.info(f" Output: {output_dir}")
|
| 298 |
+
logger.info(f" Audio: {total_audio_duration / 60:.1f} min total")
|
| 299 |
+
logger.info(f" RTFx: {rtfx:.1f}x realtime")
|
| 300 |
+
logger.info(f" Total chunks: {total_chunks}")
|
| 301 |
+
logger.info(f" Summary: {summary_path}")
|
| 302 |
+
|
| 303 |
+
if args.verbose:
|
| 304 |
+
import importlib.metadata
|
| 305 |
+
logger.info("--- Package versions ---")
|
| 306 |
+
for pkg in ["vllm", "transformers", "torch", "librosa", "soundfile"]:
|
| 307 |
+
try:
|
| 308 |
+
logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
|
| 309 |
+
except importlib.metadata.PackageNotFoundError:
|
| 310 |
+
logger.info(f" {pkg}: not installed")
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
if __name__ == "__main__":
|
| 314 |
+
if len(sys.argv) == 1:
|
| 315 |
+
print("=" * 60)
|
| 316 |
+
print("Audio Transcription with Cohere Transcribe (vLLM)")
|
| 317 |
+
print("=" * 60)
|
| 318 |
+
print("\nTranscribe audio files from a directory -> text files.")
|
| 319 |
+
print("Long audio automatically chunked with overlap.")
|
| 320 |
+
print("Designed for HF Buckets mounted as volumes.")
|
| 321 |
+
print()
|
| 322 |
+
print("Usage:")
|
| 323 |
+
print(" uv run transcribe.py INPUT_DIR OUTPUT_DIR --language en")
|
| 324 |
+
print()
|
| 325 |
+
print("Examples:")
|
| 326 |
+
print(" uv run transcribe.py ./audio ./output --language en")
|
| 327 |
+
print(" uv run transcribe.py ./audio ./output --language en --max-files 3")
|
| 328 |
+
print()
|
| 329 |
+
print("HF Jobs with bucket volumes:")
|
| 330 |
+
print(" hf jobs uv run --flavor l4x1 -s HF_TOKEN \\")
|
| 331 |
+
print(" -v bucket/user/audio-input:/input:ro \\")
|
| 332 |
+
print(" -v bucket/user/transcripts:/output \\")
|
| 333 |
+
print(" transcribe.py /input /output --language en")
|
| 334 |
+
print()
|
| 335 |
+
print("For full help: uv run transcribe.py --help")
|
| 336 |
+
sys.exit(0)
|
| 337 |
+
|
| 338 |
+
main()
|