Add easytranscriber-transcribe.py for word-level alignment
#1
by davanstrien HF Staff - opened
- README.md +35 -7
- easytranscriber-transcribe.py +429 -0
README.md
CHANGED
|
@@ -34,16 +34,19 @@ No download/upload step. Buckets are mounted directly as volumes via [hf-mount](
|
|
| 34 |
|
| 35 |
### Transcription
|
| 36 |
|
| 37 |
-
| Script | Model | Backend |
|
| 38 |
-
|--------|-------|---------|--------------|
|
| 39 |
-
| `cohere-transcribe.py` | Cohere Transcribe (2B) | transformers | 161x RT |
|
| 40 |
-
| `cohere-transcribe-vllm.py` | Cohere Transcribe (2B) | vLLM nightly | 214x RT |
|
|
|
|
| 41 |
|
| 42 |
-
**`cohere-transcribe.py`** (recommended) — uses `model.transcribe()` with automatic long-form chunking, overlap, and reassembly. Stable dependencies.
|
| 43 |
|
| 44 |
**`cohere-transcribe-vllm.py`** — experimental vLLM variant. Faster but requires nightly vLLM and has minor duplication at chunk boundaries.
|
| 45 |
|
| 46 |
-
|
|
|
|
|
|
|
| 47 |
|
| 48 |
| Flag | Default | Description |
|
| 49 |
|------|---------|-------------|
|
|
@@ -52,15 +55,39 @@ No download/upload step. Buckets are mounted directly as volumes via [hf-mount](
|
|
| 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 |
|
|
@@ -71,3 +98,4 @@ CBS Suspense (1940s radio drama), 66 episodes, 33 hours of audio:
|
|
| 71 |
|
| 72 |
- **Gated model**: Accept terms at the [model page](https://huggingface.co/CohereLabs/cohere-transcribe-03-2026) before use.
|
| 73 |
- **Tokenizer workaround**: `cohere-transcribe.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)).
|
|
|
|
|
|
| 34 |
|
| 35 |
### Transcription
|
| 36 |
|
| 37 |
+
| Script | Model | Backend | Output | Speed |
|
| 38 |
+
|--------|-------|---------|--------|-------|
|
| 39 |
+
| `cohere-transcribe.py` | Cohere Transcribe (2B) | transformers | `.txt` | 161x RT (A100) |
|
| 40 |
+
| `cohere-transcribe-vllm.py` | Cohere Transcribe (2B) | vLLM nightly | `.txt` | 214x RT (A100) |
|
| 41 |
+
| `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) |
|
| 42 |
|
| 43 |
+
**`cohere-transcribe.py`** (recommended for plain text) — uses `model.transcribe()` with automatic long-form chunking, overlap, and reassembly. Stable dependencies.
|
| 44 |
|
| 45 |
**`cohere-transcribe-vllm.py`** — experimental vLLM variant. Faster but requires nightly vLLM and has minor duplication at chunk boundaries.
|
| 46 |
|
| 47 |
+
**`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`).
|
| 48 |
+
|
| 49 |
+
#### Options — `cohere-transcribe.py` / `cohere-transcribe-vllm.py`
|
| 50 |
|
| 51 |
| Flag | Default | Description |
|
| 52 |
|------|---------|-------------|
|
|
|
|
| 55 |
| `--batch-size` | 16 | Batch size for inference |
|
| 56 |
| `--max-files` | all | Limit files to process (for testing) |
|
| 57 |
|
| 58 |
+
#### Options — `easytranscriber-transcribe.py`
|
| 59 |
+
|
| 60 |
+
| Flag | Default | Description |
|
| 61 |
+
|------|---------|-------------|
|
| 62 |
+
| `--language` | required | ISO 639-1 code. Cohere supports the same 14 languages as above; ct2/hf support any Whisper language |
|
| 63 |
+
| `--backend` | `cohere` | `cohere`, `ct2` (CTranslate2 Whisper, fastest for Whisper), or `hf` (transformers) |
|
| 64 |
+
| `--transcription-model` | Cohere 2B / distil-whisper-large-v3.5 | HF model ID; override to use KB-Whisper, Whisper-large-v3, etc. |
|
| 65 |
+
| `--emissions-model` | per-language default | wav2vec2 for forced alignment: en→`wav2vec2-base-960h`, sv→`voxrex-swedish`, else→`facebook/mms-1b-all` |
|
| 66 |
+
| `--vad` | `silero` | `silero` (no auth) or `pyannote` (requires accepting terms + HF_TOKEN) |
|
| 67 |
+
| `--tokenizer-lang` | derived from `--language` | NLTK Punkt language name for sentence tokenization |
|
| 68 |
+
| `--emit-txt` | off | Also write `.txt` transcripts alongside the JSON alignments |
|
| 69 |
+
| `--emit-srt` | off | Also write `.srt` subtitles derived from alignment segments |
|
| 70 |
+
| `--batch-size-features` | 8 | Feature-extraction batch size |
|
| 71 |
+
| `--batch-size-transcribe` | 16 | ASR batch size (where backend supports it) |
|
| 72 |
+
| `--max-files` | all | Limit files to process (for testing) |
|
| 73 |
+
|
| 74 |
#### Benchmarks
|
| 75 |
|
| 76 |
+
CBS Suspense (1940s radio drama), 66 episodes, 33 hours of audio.
|
| 77 |
+
|
| 78 |
+
**`cohere-transcribe.py`** (plain text):
|
| 79 |
|
| 80 |
| GPU | Time | RTFx |
|
| 81 |
|-----|------|------|
|
| 82 |
| A100-SXM4-80GB | 12.3 min | 161x realtime |
|
| 83 |
| L4 | ~64s / 30 min episode | 28x realtime |
|
| 84 |
|
| 85 |
+
**`easytranscriber-transcribe.py`** (JSON alignments + optional .txt/.srt; VAD → ASR → wav2vec2 → forced alignment):
|
| 86 |
+
|
| 87 |
+
| GPU | Time | RTFx | Output |
|
| 88 |
+
|-----|------|------|--------|
|
| 89 |
+
| L4 | 46.2 min | 42.9x realtime | 66 JSON + SRT + TXT (42,633 segments, 295k words) |
|
| 90 |
+
|
| 91 |
### Data
|
| 92 |
|
| 93 |
| Script | Description |
|
|
|
|
| 98 |
|
| 99 |
- **Gated model**: Accept terms at the [model page](https://huggingface.co/CohereLabs/cohere-transcribe-03-2026) before use.
|
| 100 |
- **Tokenizer workaround**: `cohere-transcribe.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)).
|
| 101 |
+
- **easytranscriber**: the Cohere backend requires `transformers>=5.4.0` (pinned in the script). Pyannote VAD is gated — accept terms at [pyannote/segmentation-3.0](https://huggingface.co/pyannote/segmentation-3.0) and [pyannote/speaker-diarization-3.1](https://huggingface.co/pyannote/speaker-diarization-3.1) if using `--vad pyannote`. Otherwise stick with the default Silero VAD.
|
easytranscriber-transcribe.py
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "easytranscriber>=0.2.2",
|
| 5 |
+
# "easyaligner",
|
| 6 |
+
# "transformers>=5.4.0",
|
| 7 |
+
# "torch>=2.7.0,!=2.9.*",
|
| 8 |
+
# "torchaudio>=2.7.0,!=2.9.*",
|
| 9 |
+
# "ctranslate2>=4.4.0",
|
| 10 |
+
# "pyannote.audio>=3.3.1",
|
| 11 |
+
# "silero-vad~=6.0",
|
| 12 |
+
# "nltk>=3.8.2",
|
| 13 |
+
# "msgspec",
|
| 14 |
+
# "soundfile",
|
| 15 |
+
# "librosa",
|
| 16 |
+
# "static-ffmpeg",
|
| 17 |
+
# "huggingface-hub[hf_transfer]",
|
| 18 |
+
# ]
|
| 19 |
+
# ///
|
| 20 |
+
|
| 21 |
+
"""
|
| 22 |
+
Transcribe audio with word-level timestamps using kb-labb/easytranscriber.
|
| 23 |
+
|
| 24 |
+
Runs VAD -> ASR -> emissions -> forced alignment and writes per-file JSON
|
| 25 |
+
with `speeches[].alignments[].words[].{text,start,end,score}`. Optionally
|
| 26 |
+
also writes plain `.txt` transcripts and `.srt` subtitles.
|
| 27 |
+
|
| 28 |
+
Designed to work with HF Buckets mounted as volumes via `hf jobs uv run -v ...`.
|
| 29 |
+
|
| 30 |
+
Layout:
|
| 31 |
+
INPUT OUTPUT (default JSON only)
|
| 32 |
+
/input/ep1.mp3 -> /output/alignments/ep1.json
|
| 33 |
+
/input/sub/clip.wav -> /output/alignments/sub/clip.json
|
| 34 |
+
|
| 35 |
+
With --emit-txt / --emit-srt, side-files land at:
|
| 36 |
+
/output/ep1.txt, /output/ep1.srt (preserving relative sub-dirs)
|
| 37 |
+
|
| 38 |
+
Default backend is Cohere Transcribe 2B (same model as cohere-transcribe.py)
|
| 39 |
+
but here with word-level alignments on top. Pass --backend ct2 to use a
|
| 40 |
+
Whisper variant (e.g. KBLab/kb-whisper-large for Swedish).
|
| 41 |
+
|
| 42 |
+
Examples:
|
| 43 |
+
|
| 44 |
+
# Smoke test
|
| 45 |
+
uv run easytranscriber-transcribe.py ./test-audio ./test-output \\
|
| 46 |
+
--language en --max-files 1 --emit-txt --emit-srt
|
| 47 |
+
|
| 48 |
+
# Swedish with KB-Whisper (ct2 backend)
|
| 49 |
+
uv run easytranscriber-transcribe.py ./audio-sv ./output-sv \\
|
| 50 |
+
--language sv --backend ct2 \\
|
| 51 |
+
--transcription-model KBLab/kb-whisper-large \\
|
| 52 |
+
--emit-srt
|
| 53 |
+
|
| 54 |
+
# HF Jobs with bucket volumes
|
| 55 |
+
hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
|
| 56 |
+
-e UV_TORCH_BACKEND=cu128 \\
|
| 57 |
+
-v bucket/user/audio-files:/input:ro \\
|
| 58 |
+
-v bucket/user/transcripts-aligned:/output \\
|
| 59 |
+
easytranscriber-transcribe.py /input /output \\
|
| 60 |
+
--language en --emit-txt --emit-srt
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
import argparse
|
| 64 |
+
import json
|
| 65 |
+
import logging
|
| 66 |
+
import os
|
| 67 |
+
import sys
|
| 68 |
+
import time
|
| 69 |
+
from pathlib import Path
|
| 70 |
+
|
| 71 |
+
import torch
|
| 72 |
+
|
| 73 |
+
logging.basicConfig(
|
| 74 |
+
level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s"
|
| 75 |
+
)
|
| 76 |
+
logger = logging.getLogger(__name__)
|
| 77 |
+
|
| 78 |
+
AUDIO_EXTENSIONS = {".mp3", ".wav", ".flac", ".ogg", ".m4a", ".wma", ".aac", ".opus"}
|
| 79 |
+
|
| 80 |
+
COHERE_MODEL = "CohereLabs/cohere-transcribe-03-2026"
|
| 81 |
+
WHISPER_DEFAULT_MODEL = "distil-whisper/distil-large-v3.5"
|
| 82 |
+
|
| 83 |
+
# Cohere Transcribe's 14 supported languages.
|
| 84 |
+
# Source: easytranscriber/src/easytranscriber/asr/cohere.py
|
| 85 |
+
COHERE_LANGUAGES = frozenset(
|
| 86 |
+
{"ar", "de", "el", "en", "es", "fr", "it", "ja", "ko", "nl", "pl", "pt", "vi", "zh"}
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
# Language -> default wav2vec2 emissions (forced alignment) model.
|
| 90 |
+
# Anything not listed falls back to the multilingual MMS model.
|
| 91 |
+
LANGUAGE_EMISSIONS_DEFAULTS = {
|
| 92 |
+
"en": "facebook/wav2vec2-base-960h",
|
| 93 |
+
"sv": "KBLab/wav2vec2-large-voxrex-swedish",
|
| 94 |
+
}
|
| 95 |
+
FALLBACK_EMISSIONS_MODEL = "facebook/mms-1b-all"
|
| 96 |
+
|
| 97 |
+
# Language -> NLTK Punkt tokenizer language name.
|
| 98 |
+
# easyaligner.text.load_tokenizer wraps nltk.tokenize.punkt.PunktTokenizer.
|
| 99 |
+
LANGUAGE_TOKENIZER_MAP = {
|
| 100 |
+
"en": "english", "sv": "swedish", "de": "german", "fr": "french",
|
| 101 |
+
"it": "italian", "es": "spanish", "pt": "portuguese", "el": "greek",
|
| 102 |
+
"nl": "dutch", "pl": "polish", "ru": "russian", "cs": "czech",
|
| 103 |
+
"da": "danish", "fi": "finnish", "no": "norwegian", "tr": "turkish",
|
| 104 |
+
"et": "estonian",
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def check_cuda_availability():
|
| 109 |
+
if not torch.cuda.is_available():
|
| 110 |
+
logger.error("CUDA is not available. This script requires a GPU.")
|
| 111 |
+
sys.exit(1)
|
| 112 |
+
logger.info(f"CUDA available. GPU: {torch.cuda.get_device_name(0)}")
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def discover_audio_files(input_dir: Path) -> list[Path]:
|
| 116 |
+
"""Walk input_dir recursively, returning sorted list of audio files."""
|
| 117 |
+
files = []
|
| 118 |
+
for path in sorted(input_dir.rglob("*")):
|
| 119 |
+
if path.is_file() and path.suffix.lower() in AUDIO_EXTENSIONS:
|
| 120 |
+
files.append(path)
|
| 121 |
+
return files
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def get_audio_duration(file_path: Path) -> float | None:
|
| 125 |
+
"""Get audio duration in seconds."""
|
| 126 |
+
try:
|
| 127 |
+
import librosa
|
| 128 |
+
return librosa.get_duration(path=str(file_path))
|
| 129 |
+
except Exception:
|
| 130 |
+
return None
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _format_srt_timestamp(seconds: float) -> str:
|
| 134 |
+
"""Format seconds as SRT timestamp: HH:MM:SS,mmm."""
|
| 135 |
+
if seconds < 0:
|
| 136 |
+
seconds = 0.0
|
| 137 |
+
total_ms = int(round(seconds * 1000))
|
| 138 |
+
ms = total_ms % 1000
|
| 139 |
+
total_s = total_ms // 1000
|
| 140 |
+
s = total_s % 60
|
| 141 |
+
m = (total_s // 60) % 60
|
| 142 |
+
h = total_s // 3600
|
| 143 |
+
return f"{h:02d}:{m:02d}:{s:02d},{ms:03d}"
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _write_srt(segments, out_path: Path) -> None:
|
| 147 |
+
"""Write AlignmentSegments to an SRT file."""
|
| 148 |
+
lines = []
|
| 149 |
+
for i, seg in enumerate(segments, start=1):
|
| 150 |
+
start = _format_srt_timestamp(float(seg.start))
|
| 151 |
+
end = _format_srt_timestamp(float(seg.end))
|
| 152 |
+
text = (seg.text or "").strip().replace("\n", " ")
|
| 153 |
+
lines.append(f"{i}\n{start} --> {end}\n{text}\n")
|
| 154 |
+
out_path.write_text("\n".join(lines), encoding="utf-8")
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _write_txt(segments, out_path: Path) -> None:
|
| 158 |
+
"""Write concatenated segment text to a .txt file."""
|
| 159 |
+
text = "\n".join((seg.text or "").strip() for seg in segments if seg.text)
|
| 160 |
+
out_path.write_text(text + ("\n" if text and not text.endswith("\n") else ""), encoding="utf-8")
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def resolve_transcription_model(backend: str, override: str | None) -> str:
|
| 164 |
+
if override:
|
| 165 |
+
return override
|
| 166 |
+
if backend == "cohere":
|
| 167 |
+
return COHERE_MODEL
|
| 168 |
+
return WHISPER_DEFAULT_MODEL
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def resolve_emissions_model(language: str, override: str | None) -> str:
|
| 172 |
+
if override:
|
| 173 |
+
return override
|
| 174 |
+
return LANGUAGE_EMISSIONS_DEFAULTS.get(language, FALLBACK_EMISSIONS_MODEL)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def resolve_tokenizer_lang(language: str, override: str | None) -> str:
|
| 178 |
+
if override:
|
| 179 |
+
return override
|
| 180 |
+
return LANGUAGE_TOKENIZER_MAP.get(language, "english")
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def main():
|
| 184 |
+
parser = argparse.ArgumentParser(
|
| 185 |
+
description="Transcribe audio with word-level timestamps via easytranscriber.",
|
| 186 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 187 |
+
epilog="""
|
| 188 |
+
Backends: cohere (default, 14 langs), ct2 (Whisper via CTranslate2), hf (transformers).
|
| 189 |
+
|
| 190 |
+
Examples:
|
| 191 |
+
uv run easytranscriber-transcribe.py ./audio ./out --language en
|
| 192 |
+
uv run easytranscriber-transcribe.py ./audio ./out --language en --emit-srt --emit-txt
|
| 193 |
+
uv run easytranscriber-transcribe.py ./sv ./out-sv --language sv --backend ct2 \\
|
| 194 |
+
--transcription-model KBLab/kb-whisper-large
|
| 195 |
+
|
| 196 |
+
HF Jobs with bucket volumes:
|
| 197 |
+
hf jobs uv run --flavor l4x1 -s HF_TOKEN -e UV_TORCH_BACKEND=cu128 \\
|
| 198 |
+
-v bucket/user/audio-files:/input:ro \\
|
| 199 |
+
-v bucket/user/transcripts-aligned:/output \\
|
| 200 |
+
easytranscriber-transcribe.py /input /output --language en --emit-txt --emit-srt
|
| 201 |
+
""",
|
| 202 |
+
)
|
| 203 |
+
parser.add_argument("input_dir", help="Directory containing audio files (recursively scanned)")
|
| 204 |
+
parser.add_argument("output_dir", help="Directory to write alignments/JSON (and optional .txt/.srt)")
|
| 205 |
+
parser.add_argument("--language", required=True, help="ISO 639-1 language code (e.g. en, sv, de)")
|
| 206 |
+
parser.add_argument(
|
| 207 |
+
"--backend", default="cohere", choices=["cohere", "ct2", "hf"],
|
| 208 |
+
help="ASR backend (default: cohere)",
|
| 209 |
+
)
|
| 210 |
+
parser.add_argument(
|
| 211 |
+
"--transcription-model", default=None,
|
| 212 |
+
help=f"Transcription model HF ID. Default: {COHERE_MODEL} (cohere) or {WHISPER_DEFAULT_MODEL} (ct2/hf)",
|
| 213 |
+
)
|
| 214 |
+
parser.add_argument(
|
| 215 |
+
"--emissions-model", default=None,
|
| 216 |
+
help="wav2vec2 HF ID for forced alignment. Default picked from --language.",
|
| 217 |
+
)
|
| 218 |
+
parser.add_argument(
|
| 219 |
+
"--vad", default="silero", choices=["silero", "pyannote"],
|
| 220 |
+
help="VAD backend (default: silero). pyannote requires accepting terms + HF_TOKEN.",
|
| 221 |
+
)
|
| 222 |
+
parser.add_argument(
|
| 223 |
+
"--tokenizer-lang", default=None,
|
| 224 |
+
help="NLTK Punkt language name (english, swedish, ...). Default derived from --language.",
|
| 225 |
+
)
|
| 226 |
+
parser.add_argument("--batch-size-features", type=int, default=8)
|
| 227 |
+
parser.add_argument("--batch-size-transcribe", type=int, default=16)
|
| 228 |
+
parser.add_argument("--emit-txt", action="store_true", help="Also write .txt transcript per file")
|
| 229 |
+
parser.add_argument("--emit-srt", action="store_true", help="Also write .srt subtitles per file")
|
| 230 |
+
parser.add_argument("--max-files", type=int, default=None, help="Limit number of files (for testing)")
|
| 231 |
+
parser.add_argument("--verbose", action="store_true", help="Print resolved package versions")
|
| 232 |
+
|
| 233 |
+
args = parser.parse_args()
|
| 234 |
+
|
| 235 |
+
check_cuda_availability()
|
| 236 |
+
|
| 237 |
+
language = args.language.lower()
|
| 238 |
+
if args.backend == "cohere" and language not in COHERE_LANGUAGES:
|
| 239 |
+
logger.error(
|
| 240 |
+
f"Language '{language}' is not supported by the Cohere backend. "
|
| 241 |
+
f"Supported: {', '.join(sorted(COHERE_LANGUAGES))}. "
|
| 242 |
+
f"Use --backend ct2 with a Whisper model that covers this language."
|
| 243 |
+
)
|
| 244 |
+
sys.exit(1)
|
| 245 |
+
|
| 246 |
+
input_dir = Path(args.input_dir).resolve()
|
| 247 |
+
output_dir = Path(args.output_dir).resolve()
|
| 248 |
+
|
| 249 |
+
if not input_dir.is_dir():
|
| 250 |
+
logger.error(f"Input directory does not exist: {input_dir}")
|
| 251 |
+
sys.exit(1)
|
| 252 |
+
|
| 253 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 254 |
+
alignments_dir = output_dir / "alignments"
|
| 255 |
+
vad_dir = output_dir / ".work" / "vad"
|
| 256 |
+
transcriptions_dir = output_dir / ".work" / "transcriptions"
|
| 257 |
+
emissions_dir = output_dir / ".work" / "emissions"
|
| 258 |
+
|
| 259 |
+
logger.info(f"Scanning {input_dir} for audio files...")
|
| 260 |
+
files = discover_audio_files(input_dir)
|
| 261 |
+
if not files:
|
| 262 |
+
logger.error(f"No audio files found in {input_dir}")
|
| 263 |
+
logger.error(f"Supported extensions: {', '.join(sorted(AUDIO_EXTENSIONS))}")
|
| 264 |
+
sys.exit(1)
|
| 265 |
+
|
| 266 |
+
if args.max_files:
|
| 267 |
+
files = files[: args.max_files]
|
| 268 |
+
logger.info(f"Found {len(files)} audio file(s)")
|
| 269 |
+
|
| 270 |
+
# Relative paths (strings) �� the library joins audio_dir + audio_path internally
|
| 271 |
+
# and reuses the same relative structure (with .json suffix) for all output dirs.
|
| 272 |
+
rel_paths = [str(f.relative_to(input_dir)) for f in files]
|
| 273 |
+
|
| 274 |
+
transcription_model = resolve_transcription_model(args.backend, args.transcription_model)
|
| 275 |
+
emissions_model = resolve_emissions_model(language, args.emissions_model)
|
| 276 |
+
tokenizer_lang = resolve_tokenizer_lang(language, args.tokenizer_lang)
|
| 277 |
+
|
| 278 |
+
logger.info(f"Backend: {args.backend}")
|
| 279 |
+
logger.info(f"Transcription model: {transcription_model}")
|
| 280 |
+
logger.info(f"Emissions model: {emissions_model}")
|
| 281 |
+
logger.info(f"VAD: {args.vad}")
|
| 282 |
+
logger.info(f"Language: {language} (tokenizer={tokenizer_lang})")
|
| 283 |
+
|
| 284 |
+
# easyaligner shells out to `ffmpeg` to convert audio to WAV — HF Jobs base
|
| 285 |
+
# images don't ship ffmpeg, so bootstrap a static binary onto PATH before
|
| 286 |
+
# importing the library.
|
| 287 |
+
import static_ffmpeg
|
| 288 |
+
static_ffmpeg.add_paths()
|
| 289 |
+
|
| 290 |
+
# Imports that pull in torch/transformers/etc. are deferred so argparse --help stays fast.
|
| 291 |
+
from easyaligner.text import load_tokenizer
|
| 292 |
+
from easytranscriber.pipelines import pipeline
|
| 293 |
+
from easytranscriber.text.normalization import text_normalizer
|
| 294 |
+
|
| 295 |
+
tokenizer = load_tokenizer(tokenizer_lang)
|
| 296 |
+
|
| 297 |
+
cache_dir = os.environ.get("HF_HOME") or os.environ.get("TRANSFORMERS_CACHE") or "models"
|
| 298 |
+
|
| 299 |
+
logger.info("Starting pipeline (VAD -> ASR -> emissions -> alignment)...")
|
| 300 |
+
start = time.time()
|
| 301 |
+
alignments = pipeline(
|
| 302 |
+
vad_model=args.vad,
|
| 303 |
+
emissions_model=emissions_model,
|
| 304 |
+
transcription_model=transcription_model,
|
| 305 |
+
audio_paths=rel_paths,
|
| 306 |
+
audio_dir=str(input_dir),
|
| 307 |
+
backend=args.backend,
|
| 308 |
+
language=language,
|
| 309 |
+
tokenizer=tokenizer,
|
| 310 |
+
text_normalizer_fn=text_normalizer,
|
| 311 |
+
batch_size_features=args.batch_size_features,
|
| 312 |
+
output_vad_dir=str(vad_dir),
|
| 313 |
+
output_transcriptions_dir=str(transcriptions_dir),
|
| 314 |
+
output_emissions_dir=str(emissions_dir),
|
| 315 |
+
output_alignments_dir=str(alignments_dir),
|
| 316 |
+
cache_dir=cache_dir,
|
| 317 |
+
hf_token=os.environ.get("HF_TOKEN"),
|
| 318 |
+
save_json=True,
|
| 319 |
+
delete_emissions=True,
|
| 320 |
+
return_alignments=True,
|
| 321 |
+
)
|
| 322 |
+
elapsed = time.time() - start
|
| 323 |
+
|
| 324 |
+
# Post-process: optional .txt / .srt side-files + summary.jsonl.
|
| 325 |
+
total_audio_duration = 0.0
|
| 326 |
+
results = []
|
| 327 |
+
|
| 328 |
+
for file_path, rel, items in zip(files, rel_paths, alignments):
|
| 329 |
+
rel_path = Path(rel)
|
| 330 |
+
# The pipeline may hand back either list[SpeechSegment] (which nests
|
| 331 |
+
# AlignmentSegments under `.alignments`) or a pre-flattened list of
|
| 332 |
+
# AlignmentSegments. Normalise to a flat list either way.
|
| 333 |
+
align_segments = []
|
| 334 |
+
for item in items or []:
|
| 335 |
+
nested = getattr(item, "alignments", None)
|
| 336 |
+
if nested:
|
| 337 |
+
align_segments.extend(nested)
|
| 338 |
+
elif hasattr(item, "words"):
|
| 339 |
+
align_segments.append(item)
|
| 340 |
+
num_words = sum(len(seg.words or []) for seg in align_segments)
|
| 341 |
+
|
| 342 |
+
if args.emit_txt:
|
| 343 |
+
txt_path = output_dir / rel_path.with_suffix(".txt")
|
| 344 |
+
txt_path.parent.mkdir(parents=True, exist_ok=True)
|
| 345 |
+
_write_txt(align_segments, txt_path)
|
| 346 |
+
|
| 347 |
+
if args.emit_srt:
|
| 348 |
+
srt_path = output_dir / rel_path.with_suffix(".srt")
|
| 349 |
+
srt_path.parent.mkdir(parents=True, exist_ok=True)
|
| 350 |
+
_write_srt(align_segments, srt_path)
|
| 351 |
+
|
| 352 |
+
duration = get_audio_duration(file_path)
|
| 353 |
+
if duration:
|
| 354 |
+
total_audio_duration += duration
|
| 355 |
+
|
| 356 |
+
results.append({
|
| 357 |
+
"file": rel,
|
| 358 |
+
"duration_s": round(duration, 1) if duration else None,
|
| 359 |
+
"num_segments": len(align_segments),
|
| 360 |
+
"num_words": num_words,
|
| 361 |
+
})
|
| 362 |
+
logger.info(
|
| 363 |
+
f" {rel}: {len(align_segments)} segment(s), {num_words} word(s)"
|
| 364 |
+
f"{f', {duration:.0f}s audio' if duration else ''}"
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
summary_path = output_dir / "summary.jsonl"
|
| 368 |
+
with open(summary_path, "w", encoding="utf-8") as f:
|
| 369 |
+
for r in results:
|
| 370 |
+
f.write(json.dumps(r) + "\n")
|
| 371 |
+
|
| 372 |
+
elapsed_str = f"{elapsed / 60:.1f} min" if elapsed > 60 else f"{elapsed:.1f}s"
|
| 373 |
+
logger.info("=" * 50)
|
| 374 |
+
logger.info(f"Done! Processed {len(files)} file(s) in {elapsed_str}")
|
| 375 |
+
logger.info(f" Alignments: {alignments_dir}")
|
| 376 |
+
if args.emit_txt:
|
| 377 |
+
logger.info(f" Text: {output_dir}/<rel>.txt")
|
| 378 |
+
if args.emit_srt:
|
| 379 |
+
logger.info(f" Subtitles: {output_dir}/<rel>.srt")
|
| 380 |
+
if total_audio_duration > 0:
|
| 381 |
+
rtfx = total_audio_duration / elapsed
|
| 382 |
+
logger.info(f" Audio: {total_audio_duration / 60:.1f} min total")
|
| 383 |
+
logger.info(f" RTFx: {rtfx:.1f}x realtime")
|
| 384 |
+
logger.info(f" Summary: {summary_path}")
|
| 385 |
+
|
| 386 |
+
if args.verbose:
|
| 387 |
+
import importlib.metadata
|
| 388 |
+
logger.info("--- Package versions ---")
|
| 389 |
+
for pkg in [
|
| 390 |
+
"easytranscriber", "easyaligner", "transformers", "torch", "torchaudio",
|
| 391 |
+
"ctranslate2", "pyannote.audio", "silero-vad", "nltk", "librosa",
|
| 392 |
+
"soundfile", "huggingface-hub",
|
| 393 |
+
]:
|
| 394 |
+
try:
|
| 395 |
+
logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
|
| 396 |
+
except importlib.metadata.PackageNotFoundError:
|
| 397 |
+
logger.info(f" {pkg}: not installed")
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
if __name__ == "__main__":
|
| 401 |
+
if len(sys.argv) == 1:
|
| 402 |
+
print("=" * 60)
|
| 403 |
+
print("easytranscriber: audio -> JSON alignments (+ optional .txt/.srt)")
|
| 404 |
+
print("=" * 60)
|
| 405 |
+
print("\nRuns VAD -> ASR -> forced alignment and writes word-level timestamps.")
|
| 406 |
+
print("Default backend: Cohere Transcribe 2B (14 langs). Use --backend ct2")
|
| 407 |
+
print("for Whisper variants (e.g. Swedish via KBLab/kb-whisper-large).")
|
| 408 |
+
print()
|
| 409 |
+
print("Usage:")
|
| 410 |
+
print(" uv run easytranscriber-transcribe.py INPUT_DIR OUTPUT_DIR --language en")
|
| 411 |
+
print()
|
| 412 |
+
print("Examples:")
|
| 413 |
+
print(" uv run easytranscriber-transcribe.py ./audio ./out --language en")
|
| 414 |
+
print(" uv run easytranscriber-transcribe.py ./audio ./out --language en \\")
|
| 415 |
+
print(" --emit-txt --emit-srt")
|
| 416 |
+
print(" uv run easytranscriber-transcribe.py ./sv ./out-sv --language sv \\")
|
| 417 |
+
print(" --backend ct2 --transcription-model KBLab/kb-whisper-large")
|
| 418 |
+
print()
|
| 419 |
+
print("HF Jobs with bucket volumes:")
|
| 420 |
+
print(" hf jobs uv run --flavor l4x1 -s HF_TOKEN -e UV_TORCH_BACKEND=cu128 \\")
|
| 421 |
+
print(" -v bucket/user/audio-files:/input:ro \\")
|
| 422 |
+
print(" -v bucket/user/transcripts-aligned:/output \\")
|
| 423 |
+
print(" easytranscriber-transcribe.py /input /output \\")
|
| 424 |
+
print(" --language en --emit-txt --emit-srt")
|
| 425 |
+
print()
|
| 426 |
+
print("For full help: uv run easytranscriber-transcribe.py --help")
|
| 427 |
+
sys.exit(0)
|
| 428 |
+
|
| 429 |
+
main()
|