davanstrien HF Staff commited on
Commit
737a232
·
verified ·
1 Parent(s): 2f660d2

Sync from GitHub via hub-sync

Browse files
README.md CHANGED
@@ -5,12 +5,12 @@ tags:
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
 
@@ -30,6 +30,14 @@ hf jobs uv run --flavor l4x1 -s HF_TOKEN \
30
  -v hf://buckets/user/transcripts:/output \
31
  https://huggingface.co/datasets/uv-scripts/transcription/raw/main/cohere-transcribe.py \
32
  /input /output --language en --compile
 
 
 
 
 
 
 
 
33
  ```
34
 
35
  No download/upload step. Buckets are mounted directly as volumes via [hf-mount](https://github.com/huggingface/hf-mount).
@@ -45,6 +53,8 @@ No download/upload step. Buckets are mounted directly as volumes via [hf-mount](
45
  | `cohere-transcribe.py` | Cohere Transcribe (2B) | transformers | `.txt` | 161x RT (A100) |
46
  | `cohere-transcribe-vllm.py` | Cohere Transcribe (2B) | vLLM nightly | `.txt` | 214x RT (A100) |
47
  | `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) |
 
 
48
 
49
  **`cohere-transcribe.py`** (recommended for plain text) — uses `model.transcribe()` with automatic long-form chunking, overlap, and reassembly. Stable dependencies.
50
 
@@ -52,6 +62,10 @@ No download/upload step. Buckets are mounted directly as volumes via [hf-mount](
52
 
53
  **`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`).
54
 
 
 
 
 
55
  #### Options — `cohere-transcribe.py` / `cohere-transcribe-vllm.py`
56
 
57
  | Flag | Default | Description |
@@ -77,6 +91,28 @@ No download/upload step. Buckets are mounted directly as volumes via [hf-mount](
77
  | `--batch-size-transcribe` | 16 | ASR batch size (where backend supports it) |
78
  | `--max-files` | all | Limit files to process (for testing) |
79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
  #### Benchmarks
81
 
82
  CBS Suspense (1940s radio drama), 66 episodes, 33 hours of audio.
@@ -94,14 +130,67 @@ CBS Suspense (1940s radio drama), 66 episodes, 33 hours of audio.
94
  |-----|------|------|--------|
95
  | L4 | 46.2 min | 42.9x realtime | 66 JSON + SRT + TXT (42,633 segments, 295k words) |
96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  ### Data
98
 
99
  | Script | Description |
100
  |--------|-------------|
101
  | `download-ia.py` | Download audio from Internet Archive into a mounted bucket |
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  ## Notes
104
 
105
  - **Gated model**: Accept terms at the [model page](https://huggingface.co/CohereLabs/cohere-transcribe-03-2026) before use.
106
  - **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)).
107
  - **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.
 
 
 
5
  - audio
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
 
 
30
  -v hf://buckets/user/transcripts:/output \
31
  https://huggingface.co/datasets/uv-scripts/transcription/raw/main/cohere-transcribe.py \
32
  /input /output --language en --compile
33
+
34
+ # Or: transcribe + figure out WHO said what (speaker diarization + timestamps)
35
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN \
36
+ -e UV_TORCH_BACKEND=cu128 \
37
+ -v hf://buckets/user/audio-files:/input:ro \
38
+ -v hf://buckets/user/transcripts:/output \
39
+ https://huggingface.co/datasets/uv-scripts/transcription/raw/main/moss-transcribe-diarize.py \
40
+ /input /output --emit-txt
41
  ```
42
 
43
  No download/upload step. Buckets are mounted directly as volumes via [hf-mount](https://github.com/huggingface/hf-mount).
 
53
  | `cohere-transcribe.py` | Cohere Transcribe (2B) | transformers | `.txt` | 161x RT (A100) |
54
  | `cohere-transcribe-vllm.py` | Cohere Transcribe (2B) | vLLM nightly | `.txt` | 214x RT (A100) |
55
  | `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) |
56
+ | `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) |
57
+ | `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) |
58
 
59
  **`cohere-transcribe.py`** (recommended for plain text) — uses `model.transcribe()` with automatic long-form chunking, overlap, and reassembly. Stable dependencies.
60
 
 
62
 
63
  **`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`).
64
 
65
+ **`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.
66
+
67
+ **`moss-transcribe-diarize-server.py`** — same model at **~12x the throughput** for many files: serves it behind sglang-omni inside the job and posts files concurrently (continuous batching). Splits long tapes into ≤55-min clips to fit the context window (speaker labels reset between clips, recorded as `part` on each segment) and automatically continues from the last timestamp when the model stops early, reporting `coverage_s` per file. Needs `a100-large` — 24 GB cards OOM on long-tape KV. The `hf jobs run` command lives in the script docstring (server + driver in one job).
68
+
69
  #### Options — `cohere-transcribe.py` / `cohere-transcribe-vllm.py`
70
 
71
  | Flag | Default | Description |
 
91
  | `--batch-size-transcribe` | 16 | ASR batch size (where backend supports it) |
92
  | `--max-files` | all | Limit files to process (for testing) |
93
 
94
+ #### Options — `moss-transcribe-diarize-server.py`
95
+
96
+ | Flag | Default | Description |
97
+ |------|---------|-------------|
98
+ | `--concurrency` | 4 | Concurrent transcription requests (KV-cache bound; 6 works on A100) |
99
+ | `--part-minutes` | 55 | Clip length for splitting long audio (longest that fits the context window). Speaker labels reset between clips |
100
+ | `--server` | `http://127.0.0.1:8000` | sgl-omni server URL (in-job localhost by default) |
101
+ | `--request-timeout` | 3600 | Per-request timeout in seconds |
102
+ | `--emit-txt` | off | Also write `.txt` transcripts |
103
+ | `--max-files` | all | Limit files to process (for testing) |
104
+
105
+ #### Options — `moss-transcribe-diarize.py`
106
+
107
+ | Flag | Default | Description |
108
+ |------|---------|-------------|
109
+ | `--max-new-tokens` | 0 (auto) | Token budget per file. Auto scales with audio duration (min 5120, max 65536). Output JSON sets `"truncated": true` if the budget was hit — re-run with a higher value |
110
+ | `--hotwords` | none | Comma-separated terms (names, companies, jargon) appended to the prompt to bias recognition |
111
+ | `--prompt` | built-in | Full prompt override (replaces the built-in transcribe+diarize prompt) |
112
+ | `--emit-txt` | off | Also write `.txt` transcripts (`[start - end] SPEAKER: text` per line) |
113
+ | `--emit-srt` | off | Also write `.srt` subtitles with speaker prefixes |
114
+ | `--max-files` | all | Limit files to process (for testing) |
115
+
116
  #### Benchmarks
117
 
118
  CBS Suspense (1940s radio drama), 66 episodes, 33 hours of audio.
 
130
  |-----|------|------|--------|
131
  | L4 | 46.2 min | 42.9x realtime | 66 JSON + SRT + TXT (42,633 segments, 295k words) |
132
 
133
+ **`moss-transcribe-diarize.py`** (Apollo 11 mission audio, one 74-min multi-speaker tape):
134
+
135
+ | GPU | Time | RTFx | Output |
136
+ |-----|------|------|--------|
137
+ | A10G | 23.3 min | 3.2x realtime | 743 segments, 7 speakers, 23k tokens, no truncation |
138
+
139
+ Long files are generation-bound (the whole diarized transcript is decoded in one pass), so RTFx drops as recordings grow; short clips run far faster. `l4x1` also works — same class of GPU.
140
+
141
+ **`moss-transcribe-diarize-server.py`** (Apollo 11 mission audio from the [Internet Archive](https://archive.org/details/Apollo11Audio) — the full collection in one job):
142
+
143
+ | GPU | Audio | Time | RTFx | Cost | Output |
144
+ |-----|-------|------|------|------|--------|
145
+ | A100 | 174.5 h (103 tapes) | 3.8 h | 47.4x realtime aggregate | $9.46 | 45k speaker segments, 97% coverage |
146
+
147
+ Result published as [`davanstrien/apollo-11-diarized`](https://huggingface.co/datasets/davanstrien/apollo-11-diarized) with a searchable demo at [`davanstrien/apollo-11-search`](https://huggingface.co/spaces/davanstrien/apollo-11-search).
148
+
149
  ### Data
150
 
151
  | Script | Description |
152
  |--------|-------------|
153
  | `download-ia.py` | Download audio from Internet Archive into a mounted bucket |
154
 
155
+ ## Serve as a live endpoint
156
+
157
+ MOSS-Transcribe-Diarize can be served as an OpenAI-compatible transcription API on Jobs (see [Serving on Jobs](https://huggingface.co/docs/hub/jobs-serving)). Two verified paths; both expose `/v1/audio/transcriptions` at `https://<job-id>--8000.hf.jobs` (requests need an HF token with read access to your namespace).
158
+
159
+ **vLLM** (simplest; returns the raw `[start][Sxx]text[end]` transcript). Model support was merged into vLLM on 2026-07-08 — after the v0.24.0 release — so use a commit-pinned nightly image until the next release (then plain `vllm/vllm-openai:latest` works). The image needs the audio extras installed first:
160
+
161
+ ```bash
162
+ hf jobs run --detach --expose 8000 --flavor l4x1 -s HF_TOKEN --timeout 2h \
163
+ vllm/vllm-openai:nightly-2c17d33f4291a55b447317640c81eb61077b1b00 -- \
164
+ bash -c "pip install librosa soundfile && vllm serve OpenMOSS-Team/MOSS-Transcribe-Diarize --trust-remote-code"
165
+ ```
166
+
167
+ Parse the response `text` into segments with `parse_transcript` from the model's [GitHub package](https://github.com/OpenMOSS/MOSS-Transcribe-Diarize).
168
+
169
+ **sglang-omni** (upstream's recommended production server; adds `response_format=verbose_json` with parsed speaker segments). Its prebuilt image predates this model, so install it at job start over a current [sglang nightly image](https://hub.docker.com/r/lmsysorg/sglang/tags) — the tag below is the tested pin; newer nightlies should also work. The clone + fresh-venv sequence is [upstream's documented install](https://github.com/sgl-project/sglang-omni/blob/main/docs/get_started/installation.md) and adds under a minute:
170
+
171
+ ```bash
172
+ hf jobs run --detach --expose 8000 --flavor l4x1 -s HF_TOKEN --timeout 2h \
173
+ lmsysorg/sglang:nightly-dev-cu13-20260709-074bb928 -- \
174
+ bash -c "pip install -q uv 2>/dev/null; git clone --depth 1 https://github.com/sgl-project/sglang-omni.git && cd sglang-omni && uv venv .venv -p 3.12 && . .venv/bin/activate && uv pip install . && sgl-omni serve --model-path OpenMOSS-Team/MOSS-Transcribe-Diarize --host 0.0.0.0 --port 8000 --max-running-requests 16 --mem-fraction-static 0.80"
175
+ ```
176
+
177
+ Query either server the same way (`response_format=verbose_json` on sglang-omni only; raise `max_new_tokens`, e.g. `65536`, for long recordings). **Caution — long audio on the serve path**: sglang-omni silently truncates input past ~62 minutes (observed deterministically at ~62.5 min on the same tape that transcribes fully via the transformers recipe, regardless of `max_new_tokens`). Split longer recordings before posting — `moss-transcribe-diarize-server.py` does this automatically:
178
+
179
+ ```bash
180
+ curl -X POST https://<job-id>--8000.hf.jobs/v1/audio/transcriptions \
181
+ -H "Authorization: Bearer $HF_TOKEN" \
182
+ -F model=OpenMOSS-Team/MOSS-Transcribe-Diarize \
183
+ -F file=@meeting.wav \
184
+ -F response_format=verbose_json \
185
+ -F max_new_tokens=65536
186
+ ```
187
+
188
+ The job — and its billing — stops at `--timeout` or `hf jobs cancel <job_id>`.
189
+
190
  ## Notes
191
 
192
  - **Gated model**: Accept terms at the [model page](https://huggingface.co/CohereLabs/cohere-transcribe-03-2026) before use.
193
  - **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)).
194
  - **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.
195
+ - **moss-transcribe-diarize**: not gated (Apache 2.0). Uses `trust_remote_code=True` (model code lives in the [model repo](https://huggingface.co/OpenMOSS-Team/MOSS-Transcribe-Diarize)); inference helpers install from the model's [GitHub repo](https://github.com/OpenMOSS/MOSS-Transcribe-Diarize) pinned to a commit (the package isn't on PyPI). Generation time scales with audio length — long multi-speaker recordings emit tens of thousands of tokens, so watch the `truncated` flag in the output JSON.
196
+ - **sglang-omni install**: the `lmsysorg/sglang-omni:dev` image predates this model — don't use it. Install from git over a current `lmsysorg/sglang` nightly image as shown above, and follow the clone + fresh-venv sequence exactly: installing outside the repo skips its `[tool.uv]` dependency overrides and fails on a protobuf conflict. Once they publish a fresh image, `sgl-omni serve` alone will do.
cohere-transcribe.py CHANGED
@@ -26,14 +26,14 @@ Input: Output:
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 hf://buckets/user/audio-input:/input:ro \\
35
  -v hf://buckets/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
@@ -97,14 +97,14 @@ def main():
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 hf://buckets/user/audio-bucket:/input:ro \\
106
  -v hf://buckets/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")
@@ -267,19 +267,19 @@ if __name__ == "__main__":
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 hf://buckets/user/audio-input:/input:ro \\")
279
  print(" -v hf://buckets/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()
 
26
  Examples:
27
 
28
  # Local test (requires CUDA GPU)
29
+ uv run cohere-transcribe.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 hf://buckets/user/audio-input:/input:ro \\
35
  -v hf://buckets/user/transcripts:/output \\
36
+ cohere-transcribe.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
 
97
  Languages: en, de, fr, it, es, pt, el, nl, pl, ar, vi, zh, ja, ko
98
 
99
  Examples:
100
+ uv run cohere-transcribe.py ./audio ./output --language en
101
+ uv run cohere-transcribe.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 hf://buckets/user/audio-bucket:/input:ro \\
106
  -v hf://buckets/user/transcripts:/output \\
107
+ cohere-transcribe.py /input /output --language en --compile
108
  """,
109
  )
110
  parser.add_argument("input_dir", help="Directory containing audio files")
 
267
  print("Designed for HF Buckets mounted as volumes.")
268
  print()
269
  print("Usage:")
270
+ print(" uv run cohere-transcribe.py INPUT_DIR OUTPUT_DIR --language en")
271
  print()
272
  print("Examples:")
273
+ print(" uv run cohere-transcribe.py ./audio ./output --language en")
274
+ print(" uv run cohere-transcribe.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 hf://buckets/user/audio-input:/input:ro \\")
279
  print(" -v hf://buckets/user/transcripts:/output \\")
280
+ print(" cohere-transcribe.py /input /output --language en --compile")
281
  print()
282
+ print("For full help: uv run cohere-transcribe.py --help")
283
  sys.exit(0)
284
 
285
  main()
moss-transcribe-diarize-server.py ADDED
@@ -0,0 +1,417 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.10"
3
+ # dependencies = [
4
+ # "requests",
5
+ # "librosa",
6
+ # "soundfile",
7
+ # ]
8
+ # ///
9
+
10
+ """
11
+ High-throughput transcription + diarization via an in-job sgl-omni server.
12
+
13
+ Same model and outputs as moss-transcribe-diarize.py, but serves
14
+ MOSS-Transcribe-Diarize behind sglang-omni inside the job and posts files
15
+ concurrently — continuous batching decodes many tapes at once (measured
16
+ 47.4x realtime aggregate on a100-large: 174.5 h of audio in 3.8 h for
17
+ $9.46, vs 3.2x realtime for the sequential transformers recipe).
18
+
19
+ This script is the *driver* half: it expects the server on localhost
20
+ (started by the job command below), splits long audio to fit the model's
21
+ context window, posts files concurrently, and writes JSON (+ .txt).
22
+
23
+ Requires a GPU with enough KV-cache room for long audio — use a100-large
24
+ (80 GB). 24 GB cards (l4x1, a10g) OOM on tapes over ~30 min.
25
+
26
+ Run on HF Jobs (single command — installs sglang-omni per upstream docs,
27
+ starts the server, then runs this driver against it):
28
+
29
+ hf jobs run --detach --flavor a100-large -s HF_TOKEN --timeout 8h \\
30
+ -v hf://buckets/user/audio-files:/input:ro \\
31
+ -v hf://buckets/user/transcripts:/output \\
32
+ lmsysorg/sglang:nightly-dev-cu13-20260709-074bb928 -- \\
33
+ bash -c "pip install -q uv; git clone --depth 1 https://github.com/sgl-project/sglang-omni.git && cd sglang-omni && uv venv .venv -p 3.12 && . .venv/bin/activate && uv pip install . && (sgl-omni serve --model-path OpenMOSS-Team/MOSS-Transcribe-Diarize --host 0.0.0.0 --port 8000 --max-running-requests 16 --mem-fraction-static 0.80 &) && uv run https://huggingface.co/datasets/uv-scripts/transcription/raw/main/moss-transcribe-diarize-server.py /input /output --emit-txt"
34
+
35
+ Input: Output:
36
+ /input/tape1.mp3 -> /output/tape1.json (segments; parts merged)
37
+ /input/sub/tape2.mp3 -> /output/sub/tape2.json
38
+
39
+ Model: OpenMOSS-Team/MOSS-Transcribe-Diarize (0.9B, Apache 2.0)
40
+ - Long tapes are split into clips that fit the model's context window;
41
+ speaker labels are consistent WITHIN a clip but reset BETWEEN clips
42
+ (clip index is recorded on every segment as "part").
43
+ - The model occasionally stops generating early (EOS mid-tape); the driver
44
+ detects short coverage and automatically continues from the last
45
+ timestamp. Compare coverage_s vs duration_s in the output JSON.
46
+ """
47
+
48
+ import argparse
49
+ import concurrent.futures
50
+ import json
51
+ import logging
52
+ import re
53
+ import sys
54
+ import tempfile
55
+ import time
56
+ from pathlib import Path
57
+
58
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
59
+ logger = logging.getLogger(__name__)
60
+
61
+ MODEL = "OpenMOSS-Team/MOSS-Transcribe-Diarize"
62
+
63
+ AUDIO_EXTENSIONS = {".mp3", ".wav", ".flac", ".ogg", ".m4a", ".wma", ".aac", ".opus"}
64
+
65
+ SAMPLE_RATE = 16000
66
+
67
+ # Context budget. The model's window is 131072 tokens and the server
68
+ # reserves max_new_tokens from it, so input audio gets
69
+ # (131072 - max_new_tokens - margin) tokens. Audio tokenizes at ~17.5
70
+ # tokens/sec (30s Whisper chunks -> temporal merge), so requesting 65536
71
+ # output tokens silently truncates input past ~62 min. We split audio into
72
+ # parts that fit alongside a generation budget sized to the part.
73
+ CONTEXT_TOKENS = 131072
74
+ AUDIO_TOKENS_PER_SECOND = 17.5
75
+ CONTEXT_MARGIN_TOKENS = 2048
76
+ GENERATION_TOKENS_PER_AUDIO_SECOND = 20 # same over-provision as sibling script
77
+ MIN_GENERATION_TOKENS = 5120
78
+
79
+ # Longest part where input + generation + margin fits the window:
80
+ # d*17.5 + max(5120, d*20) + 2048 <= 131072 -> d ~ 3440s. Stay under it.
81
+ DEFAULT_PART_SECONDS = 3300 # 55 min
82
+
83
+
84
+ def generation_budget(duration_s: float) -> int:
85
+ """Output-token budget for a clip, capped so input still fits the window."""
86
+ want = max(
87
+ MIN_GENERATION_TOKENS, int(duration_s * GENERATION_TOKENS_PER_AUDIO_SECOND)
88
+ )
89
+ room = (
90
+ CONTEXT_TOKENS
91
+ - CONTEXT_MARGIN_TOKENS
92
+ - int(duration_s * AUDIO_TOKENS_PER_SECOND)
93
+ )
94
+ return max(MIN_GENERATION_TOKENS, min(want, room))
95
+
96
+
97
+ def discover_audio_files(input_dir: Path) -> list[Path]:
98
+ return [
99
+ p
100
+ for p in sorted(input_dir.rglob("*"))
101
+ if p.is_file() and p.suffix.lower() in AUDIO_EXTENSIONS
102
+ ]
103
+
104
+
105
+ def transcribe_clip(server: str, clip: Path, duration_s: float, timeout_s: int) -> dict:
106
+ import requests
107
+
108
+ with open(clip, "rb") as f:
109
+ resp = requests.post(
110
+ f"{server}/v1/audio/transcriptions",
111
+ data={
112
+ "model": MODEL,
113
+ "response_format": "verbose_json",
114
+ "max_new_tokens": generation_budget(duration_s),
115
+ },
116
+ files={"file": (clip.name, f)},
117
+ timeout=timeout_s,
118
+ )
119
+ resp.raise_for_status()
120
+ return resp.json()
121
+
122
+
123
+ SPEAKER_RE = re.compile(r"^\[(S\d+)\]\s*")
124
+
125
+
126
+ def parse_verbose_segments(
127
+ payload: dict, offset_s: float, part_index: int
128
+ ) -> list[dict]:
129
+ """Normalize sgl-omni verbose_json segments; shift by part offset."""
130
+ out = []
131
+ for seg in payload.get("segments", []):
132
+ m = SPEAKER_RE.match(seg["text"])
133
+ out.append(
134
+ {
135
+ "start": round(seg["start"] + offset_s, 2),
136
+ "end": round(seg["end"] + offset_s, 2),
137
+ "speaker": m.group(1) if m else None,
138
+ "text": SPEAKER_RE.sub("", seg["text"]).strip(),
139
+ "part": part_index,
140
+ }
141
+ )
142
+ return out
143
+
144
+
145
+ def write_txt(segments: list[dict], path: Path):
146
+ lines = [
147
+ f"[{s['start']:.2f} - {s['end']:.2f}] {s['speaker'] or '?'}: {s['text']}"
148
+ for s in segments
149
+ ]
150
+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")
151
+
152
+
153
+ def wait_for_server(server: str, timeout_s: int = 1800):
154
+ import requests
155
+
156
+ logger.info(f"Waiting for server at {server}...")
157
+ deadline = time.time() + timeout_s
158
+ while time.time() < deadline:
159
+ try:
160
+ if requests.get(f"{server}/health", timeout=5).status_code == 200:
161
+ logger.info("Server is ready")
162
+ return
163
+ except requests.RequestException:
164
+ pass
165
+ time.sleep(10)
166
+ logger.error(f"Server did not become ready within {timeout_s}s")
167
+ sys.exit(1)
168
+
169
+
170
+ # A clip's transcript should reach near its end. If generation stops more
171
+ # than this many seconds short (the model sometimes emits EOS early — and
172
+ # always does past ~62 min of input), transcribe the remainder as a new clip.
173
+ COVERAGE_SLACK_S = 240
174
+ MIN_CONTINUATION_PROGRESS_S = 60
175
+
176
+
177
+ def process_file(
178
+ file_path: Path,
179
+ input_dir: Path,
180
+ output_dir: Path,
181
+ server: str,
182
+ part_seconds: int,
183
+ request_timeout: int,
184
+ emit_txt: bool,
185
+ workdir: Path,
186
+ ) -> dict:
187
+ import librosa
188
+ import soundfile
189
+
190
+ rel = file_path.relative_to(input_dir)
191
+ start_time = time.time()
192
+
193
+ audio, _ = librosa.load(str(file_path), sr=SAMPLE_RATE, mono=True)
194
+ duration = len(audio) / SAMPLE_RATE
195
+
196
+ # Work queue of (offset_s) positions still needing transcription. Each
197
+ # round transcribes up to part_seconds from the offset; if the model
198
+ # stops early (early EOS or the serve stack's ~62-min input cap), the
199
+ # uncovered remainder is re-queued as a continuation. Speaker labels are
200
+ # consistent within a clip and reset between clips ("part" index).
201
+ segments: list[dict] = []
202
+ offset = 0.0
203
+ part_index = 0
204
+ while duration - offset > COVERAGE_SLACK_S / 2:
205
+ clip_dur = min(part_seconds, duration - offset)
206
+ if offset == 0.0 and clip_dur >= duration:
207
+ clip_path = file_path # single-clip file: send as-is
208
+ else:
209
+ clip_path = workdir / f"{file_path.stem}.part{part_index:02d}.wav"
210
+ lo = int(offset * SAMPLE_RATE)
211
+ hi = int((offset + clip_dur) * SAMPLE_RATE)
212
+ soundfile.write(str(clip_path), audio[lo:hi], SAMPLE_RATE)
213
+
214
+ payload = transcribe_clip(server, clip_path, clip_dur, request_timeout)
215
+ if clip_path != file_path:
216
+ clip_path.unlink(missing_ok=True)
217
+ clip_segments = parse_verbose_segments(payload, offset, part_index)
218
+ segments.extend(clip_segments)
219
+
220
+ covered = (
221
+ (max(s["end"] for s in clip_segments) - offset) if clip_segments else 0.0
222
+ )
223
+ part_index += 1
224
+ if clip_dur - covered <= COVERAGE_SLACK_S:
225
+ offset += clip_dur # clip fully covered — next part
226
+ elif covered >= MIN_CONTINUATION_PROGRESS_S:
227
+ logger.info(
228
+ f" {rel}: early stop at {offset + covered:.0f}s of "
229
+ f"{offset + clip_dur:.0f}s — continuing from there"
230
+ )
231
+ offset += covered
232
+ else:
233
+ # No meaningful progress (e.g. trailing static) — skip this clip
234
+ # to avoid looping; the gap is visible in the coverage stats.
235
+ logger.warning(
236
+ f" {rel}: no progress on clip at {offset:.0f}s "
237
+ f"({len(clip_segments)} segments) — skipping {clip_dur:.0f}s"
238
+ )
239
+ offset += clip_dur
240
+
241
+ coverage_s = round(max((s["end"] for s in segments), default=0.0), 1)
242
+ speakers_per_part = {
243
+ p: sorted({s["speaker"] for s in segments if s["part"] == p and s["speaker"]})
244
+ for p in sorted({s["part"] for s in segments})
245
+ }
246
+ record = {
247
+ "file": str(rel),
248
+ "model": MODEL,
249
+ "duration_s": round(duration, 1),
250
+ "coverage_s": coverage_s,
251
+ "num_parts": part_index,
252
+ "segments": segments,
253
+ "num_segments": len(segments),
254
+ "speakers_per_part": speakers_per_part,
255
+ }
256
+
257
+ json_path = output_dir / rel.with_suffix(".json")
258
+ json_path.parent.mkdir(parents=True, exist_ok=True)
259
+ json_path.write_text(
260
+ json.dumps(record, ensure_ascii=False, indent=2), encoding="utf-8"
261
+ )
262
+ if emit_txt:
263
+ write_txt(segments, json_path.with_suffix(".txt"))
264
+
265
+ elapsed = time.time() - start_time
266
+ logger.info(
267
+ f" {rel}: {duration / 60:.0f} min, {part_index} clip(s), "
268
+ f"{len(segments)} segments, coverage {coverage_s / max(duration, 1) * 100:.0f}% "
269
+ f"in {elapsed:.0f}s"
270
+ )
271
+ return {
272
+ "file": str(rel),
273
+ "duration_s": round(duration, 1),
274
+ "coverage_s": coverage_s,
275
+ "num_parts": part_index,
276
+ "num_segments": len(segments),
277
+ "elapsed_s": round(elapsed, 1),
278
+ }
279
+
280
+
281
+ def main():
282
+ parser = argparse.ArgumentParser(
283
+ description="Concurrent transcription + diarization via in-job sgl-omni server.",
284
+ formatter_class=argparse.RawDescriptionHelpFormatter,
285
+ epilog="See module docstring for the full `hf jobs run` command.",
286
+ )
287
+ parser.add_argument("input_dir", help="Directory containing audio files")
288
+ parser.add_argument("output_dir", help="Directory to write transcript JSON files")
289
+ parser.add_argument(
290
+ "--server",
291
+ default="http://127.0.0.1:8000",
292
+ help="sgl-omni server base URL (default: in-job localhost:8000)",
293
+ )
294
+ parser.add_argument(
295
+ "--concurrency",
296
+ type=int,
297
+ default=4,
298
+ help="Concurrent transcription requests (default: 4; KV-cache bound)",
299
+ )
300
+ parser.add_argument(
301
+ "--part-minutes",
302
+ type=float,
303
+ default=DEFAULT_PART_SECONDS / 60,
304
+ help="Split audio into parts of this length (default: 55 min — the "
305
+ "longest that fits the model's context window with generation room). "
306
+ "Speaker labels reset between parts.",
307
+ )
308
+ parser.add_argument(
309
+ "--request-timeout",
310
+ type=int,
311
+ default=3600,
312
+ help="Per-request timeout in seconds (default: 3600)",
313
+ )
314
+ parser.add_argument(
315
+ "--emit-txt", action="store_true", help="Also write .txt transcripts"
316
+ )
317
+ parser.add_argument(
318
+ "--max-files", type=int, default=None, help="Limit files (for testing)"
319
+ )
320
+
321
+ args = parser.parse_args()
322
+
323
+ input_dir = Path(args.input_dir)
324
+ output_dir = Path(args.output_dir)
325
+ if not input_dir.is_dir():
326
+ logger.error(f"Input directory does not exist: {input_dir}")
327
+ sys.exit(1)
328
+ output_dir.mkdir(parents=True, exist_ok=True)
329
+
330
+ files = discover_audio_files(input_dir)
331
+ if not files:
332
+ logger.error(f"No audio files found in {input_dir}")
333
+ sys.exit(1)
334
+ if args.max_files:
335
+ files = files[: args.max_files]
336
+
337
+ # Resume: outputs are written per file, so a rerun after a timeout or
338
+ # crash only processes what's missing.
339
+ done = {
340
+ f
341
+ for f in files
342
+ if (output_dir / f.relative_to(input_dir).with_suffix(".json")).exists()
343
+ }
344
+ if done:
345
+ logger.info(f"Skipping {len(done)} file(s) with existing output JSON")
346
+ files = [f for f in files if f not in done]
347
+ if not files:
348
+ logger.info("Nothing to do — all outputs exist")
349
+ return
350
+ logger.info(f"Found {len(files)} audio file(s) to process")
351
+
352
+ wait_for_server(args.server)
353
+
354
+ part_seconds = int(args.part_minutes * 60)
355
+ start_time = time.time()
356
+ results = []
357
+ with tempfile.TemporaryDirectory() as tmp:
358
+ workdir = Path(tmp)
359
+ with concurrent.futures.ThreadPoolExecutor(
360
+ max_workers=args.concurrency
361
+ ) as pool:
362
+ futures = {
363
+ pool.submit(
364
+ process_file,
365
+ f,
366
+ input_dir,
367
+ output_dir,
368
+ args.server,
369
+ part_seconds,
370
+ args.request_timeout,
371
+ args.emit_txt,
372
+ workdir,
373
+ ): f
374
+ for f in files
375
+ }
376
+ for fut in concurrent.futures.as_completed(futures):
377
+ f = futures[fut]
378
+ try:
379
+ results.append(fut.result())
380
+ except Exception as exc:
381
+ logger.error(f" {f.name} FAILED: {exc}")
382
+ results.append({"file": f.name, "error": str(exc)})
383
+
384
+ elapsed = time.time() - start_time
385
+
386
+ summary_path = output_dir / "summary.jsonl"
387
+ with open(summary_path, "w", encoding="utf-8") as f:
388
+ for r in results:
389
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
390
+
391
+ ok = [r for r in results if "error" not in r]
392
+ total_audio = sum(r["duration_s"] for r in ok)
393
+ elapsed_str = f"{elapsed / 60:.1f} min" if elapsed > 60 else f"{elapsed:.1f}s"
394
+ logger.info("=" * 50)
395
+ logger.info(f"Done! {len(ok)}/{len(files)} file(s) in {elapsed_str}")
396
+ if total_audio:
397
+ logger.info(f" Audio: {total_audio / 3600:.1f} h total")
398
+ logger.info(f" RTFx: {total_audio / elapsed:.1f}x realtime (aggregate)")
399
+ if len(ok) < len(files):
400
+ logger.warning(f" Failed: {len(files) - len(ok)} file(s) — see {summary_path}")
401
+ logger.info(f" Summary: {summary_path}")
402
+
403
+
404
+ if __name__ == "__main__":
405
+ if len(sys.argv) == 1:
406
+ print("=" * 60)
407
+ print("Concurrent Transcription + Diarization (sgl-omni server)")
408
+ print("=" * 60)
409
+ print("\nDriver for an in-job sgl-omni server: splits long audio to")
410
+ print("fit the model's context window, posts files concurrently,")
411
+ print("writes JSON segments with timestamps + speaker labels.")
412
+ print("\nSee module docstring for the full `hf jobs run` command")
413
+ print("(server + driver in one job, a100-large recommended).")
414
+ print("\nFor full help: uv run moss-transcribe-diarize-server.py --help")
415
+ sys.exit(0)
416
+
417
+ main()
moss-transcribe-diarize.py ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.12"
3
+ # dependencies = [
4
+ # "moss-transcribe-diarize @ git+https://github.com/OpenMOSS/MOSS-Transcribe-Diarize@b5ad0f8386b155ddb89f9332ba3ca71891900357",
5
+ # "transformers>=5.0,<6",
6
+ # "torch>=2.8",
7
+ # "huggingface-hub",
8
+ # "librosa",
9
+ # "soundfile",
10
+ # ]
11
+ # ///
12
+
13
+ """
14
+ Transcribe + diarize audio files using MOSS-Transcribe-Diarize (0.9B).
15
+
16
+ Joint transcription, speaker attribution, and timestamps in a single
17
+ generation pass — no separate ASR/diarization/alignment stages. The model
18
+ handles long-form audio internally (128k context, up to ~90 min per file),
19
+ so files are never pre-chunked: speaker labels ([S01], [S02], ...) stay
20
+ consistent across the whole recording.
21
+
22
+ Designed to work with HF Buckets mounted as volumes via `hf jobs uv run -v ...`.
23
+
24
+ Input: Output:
25
+ /input/meeting.mp3 -> /output/meeting.json (segments)
26
+ /input/sub/interview.mp4 -> /output/sub/interview.json
27
+ (+ .txt / .srt with --emit-txt / --emit-srt)
28
+
29
+ Examples:
30
+
31
+ # Local test (requires CUDA GPU)
32
+ uv run moss-transcribe-diarize.py ./audio ./output --emit-txt
33
+
34
+ # HF Jobs with bucket volumes
35
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
36
+ -e UV_TORCH_BACKEND=cu128 \\
37
+ -v hf://buckets/user/audio-files:/input:ro \\
38
+ -v hf://buckets/user/transcripts:/output \\
39
+ https://huggingface.co/datasets/uv-scripts/transcription/raw/main/moss-transcribe-diarize.py \\
40
+ /input /output --emit-txt --emit-srt
41
+
42
+ Model: OpenMOSS-Team/MOSS-Transcribe-Diarize (0.9B, Apache 2.0, not gated)
43
+ - Languages: en, zh (no --language flag needed)
44
+ - Also accepts video containers (mp4, mov, mkv, ...) — audio track is decoded
45
+ - Hotword biasing: --hotwords "Acme Corp,Kubernetes,Dr. Chen"
46
+ - Inference helpers installed from the model's GitHub repo (not on PyPI),
47
+ pinned to a commit for reproducibility
48
+ """
49
+
50
+ import argparse
51
+ import json
52
+ import logging
53
+ import sys
54
+ import time
55
+ from pathlib import Path
56
+
57
+ import torch
58
+
59
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
60
+ logger = logging.getLogger(__name__)
61
+
62
+ MODEL = "OpenMOSS-Team/MOSS-Transcribe-Diarize"
63
+ # The git-pinned helper package above and the model's remote code are
64
+ # co-released, so pin the model revision they were verified against.
65
+ # Loosen once upstream stabilizes (model is days old and actively updated).
66
+ REVISION = "d7231bbae2587a4af278735eb765b318c4f64edd"
67
+
68
+ AUDIO_EXTENSIONS = {".mp3", ".wav", ".flac", ".ogg", ".m4a", ".wma", ".aac", ".opus"}
69
+ VIDEO_EXTENSIONS = {".mp4", ".m4v", ".mov", ".mkv", ".webm", ".avi", ".flv", ".wmv"}
70
+ MEDIA_EXTENSIONS = AUDIO_EXTENSIONS | VIDEO_EXTENSIONS
71
+
72
+ # Auto max_new_tokens: model default 5120, ceiling 65536 (docs' long-form value).
73
+ # ~100 tokens covers well under 10s of dense multi-speaker speech, so 20 tok/s
74
+ # of audio is a safe over-provision; generation stops at EOS anyway.
75
+ MAX_NEW_TOKENS_FLOOR = 5120
76
+ MAX_NEW_TOKENS_CEILING = 65536
77
+ TOKENS_PER_AUDIO_SECOND = 20
78
+
79
+ PROGRESS_LOG_EVERY_TOKENS = 4096
80
+
81
+
82
+ def check_cuda_availability():
83
+ if not torch.cuda.is_available():
84
+ logger.error("CUDA is not available. This script requires a GPU.")
85
+ sys.exit(1)
86
+ logger.info(f"CUDA available. GPU: {torch.cuda.get_device_name(0)}")
87
+
88
+
89
+ def discover_media_files(input_dir: Path) -> list[Path]:
90
+ """Walk input_dir recursively, returning sorted list of audio/video files."""
91
+ files = []
92
+ for path in sorted(input_dir.rglob("*")):
93
+ if path.is_file() and path.suffix.lower() in MEDIA_EXTENSIONS:
94
+ files.append(path)
95
+ return files
96
+
97
+
98
+ def get_media_duration(file_path: Path) -> float | None:
99
+ """Get duration in seconds; PyAV fallback covers video containers."""
100
+ try:
101
+ import librosa
102
+
103
+ return librosa.get_duration(path=str(file_path))
104
+ except Exception:
105
+ pass
106
+ try:
107
+ import av
108
+
109
+ with av.open(str(file_path)) as container:
110
+ if container.duration is not None:
111
+ return container.duration / av.time_base
112
+ except Exception:
113
+ pass
114
+ return None
115
+
116
+
117
+ def auto_max_new_tokens(duration_s: float | None) -> int:
118
+ """Scale the token budget with audio length; unknown duration gets the ceiling."""
119
+ if duration_s is None:
120
+ return MAX_NEW_TOKENS_CEILING
121
+ return min(
122
+ MAX_NEW_TOKENS_CEILING,
123
+ max(MAX_NEW_TOKENS_FLOOR, int(duration_s * TOKENS_PER_AUDIO_SECOND)),
124
+ )
125
+
126
+
127
+ def write_txt(segments, path: Path):
128
+ """Readable transcript: one `[start - end] SPEAKER: text` line per segment."""
129
+ lines = [
130
+ f"[{seg.start:.2f} - {seg.end:.2f}] {seg.speaker}: {seg.text}"
131
+ for seg in segments
132
+ ]
133
+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")
134
+
135
+
136
+ def main():
137
+ parser = argparse.ArgumentParser(
138
+ description="Transcribe + diarize audio using MOSS-Transcribe-Diarize.",
139
+ formatter_class=argparse.RawDescriptionHelpFormatter,
140
+ epilog="""
141
+ Languages: en, zh (auto — no language flag)
142
+
143
+ Examples:
144
+ uv run moss-transcribe-diarize.py ./audio ./output --emit-txt
145
+ uv run moss-transcribe-diarize.py ./audio ./output --hotwords "Acme,Dr. Chen"
146
+ uv run moss-transcribe-diarize.py /input /output --max-files 1 --max-new-tokens 2048
147
+
148
+ HF Jobs with bucket volumes:
149
+ hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
150
+ -e UV_TORCH_BACKEND=cu128 \\
151
+ -v hf://buckets/user/audio-bucket:/input:ro \\
152
+ -v hf://buckets/user/transcripts:/output \\
153
+ moss-transcribe-diarize.py /input /output --emit-txt --emit-srt
154
+ """,
155
+ )
156
+ parser.add_argument("input_dir", help="Directory containing audio/video files")
157
+ parser.add_argument("output_dir", help="Directory to write transcript JSON files")
158
+ parser.add_argument(
159
+ "--max-new-tokens",
160
+ type=int,
161
+ default=0,
162
+ help="Max generated tokens per file. 0 = auto-scale with audio duration "
163
+ f"(min {MAX_NEW_TOKENS_FLOOR}, max {MAX_NEW_TOKENS_CEILING})",
164
+ )
165
+ parser.add_argument(
166
+ "--hotwords",
167
+ default=None,
168
+ help="Comma-separated terms (names, products, jargon) appended to the "
169
+ "prompt to bias recognition",
170
+ )
171
+ parser.add_argument(
172
+ "--prompt",
173
+ default=None,
174
+ help="Full prompt override (replaces the built-in transcribe+diarize "
175
+ "prompt; overrides --hotwords)",
176
+ )
177
+ parser.add_argument(
178
+ "--emit-txt",
179
+ action="store_true",
180
+ help="Also write .txt transcripts ([start - end] SPEAKER: text per line)",
181
+ )
182
+ parser.add_argument(
183
+ "--emit-srt",
184
+ action="store_true",
185
+ help="Also write .srt subtitles with speaker prefixes",
186
+ )
187
+ parser.add_argument(
188
+ "--max-files",
189
+ type=int,
190
+ default=None,
191
+ help="Limit number of files to process (for testing)",
192
+ )
193
+ parser.add_argument(
194
+ "--verbose",
195
+ action="store_true",
196
+ help="Print resolved package versions",
197
+ )
198
+
199
+ args = parser.parse_args()
200
+
201
+ check_cuda_availability()
202
+
203
+ input_dir = Path(args.input_dir)
204
+ output_dir = Path(args.output_dir)
205
+
206
+ if not input_dir.is_dir():
207
+ logger.error(f"Input directory does not exist: {input_dir}")
208
+ sys.exit(1)
209
+
210
+ output_dir.mkdir(parents=True, exist_ok=True)
211
+
212
+ # Discover media files
213
+ logger.info(f"Scanning {input_dir} for audio/video files...")
214
+ files = discover_media_files(input_dir)
215
+ if not files:
216
+ logger.error(f"No media files found in {input_dir}")
217
+ logger.error(f"Supported extensions: {', '.join(sorted(MEDIA_EXTENSIONS))}")
218
+ sys.exit(1)
219
+
220
+ if args.max_files:
221
+ files = files[: args.max_files]
222
+
223
+ logger.info(f"Found {len(files)} file(s)")
224
+
225
+ # Load model
226
+ logger.info(f"Loading {MODEL}...")
227
+ from moss_transcribe_diarize import parse_transcript
228
+ from moss_transcribe_diarize.inference_utils import (
229
+ DEFAULT_PROMPT,
230
+ build_transcription_messages,
231
+ generate_transcription,
232
+ )
233
+ from transformers import AutoModelForCausalLM, AutoProcessor
234
+
235
+ device = torch.device("cuda:0")
236
+ dtype = torch.bfloat16
237
+
238
+ model = (
239
+ AutoModelForCausalLM.from_pretrained(
240
+ MODEL, revision=REVISION, trust_remote_code=True, dtype="auto"
241
+ )
242
+ .to(dtype=dtype)
243
+ .to(device)
244
+ .eval()
245
+ )
246
+ processor = AutoProcessor.from_pretrained(
247
+ MODEL, revision=REVISION, trust_remote_code=True
248
+ )
249
+ logger.info("Model loaded")
250
+
251
+ if args.prompt:
252
+ prompt = args.prompt
253
+ elif args.hotwords:
254
+ # Hotword convention from the model card: append a 热词提示 (hotword
255
+ # hint) line to the default prompt.
256
+ terms = ", ".join(t.strip() for t in args.hotwords.split(",") if t.strip())
257
+ prompt = f"{DEFAULT_PROMPT}热词提示:{terms}"
258
+ logger.info(f"Hotwords: {terms}")
259
+ else:
260
+ prompt = DEFAULT_PROMPT
261
+
262
+ # Transcribe files one at a time (no pre-chunking: the model handles
263
+ # long-form internally, which is what keeps speaker labels consistent).
264
+ # Outputs are written per file so partial progress survives job timeouts.
265
+ start_time = time.time()
266
+ total_audio_duration = 0.0
267
+ results = []
268
+
269
+ for i, file_path in enumerate(files, 1):
270
+ rel = file_path.relative_to(input_dir)
271
+ duration = get_media_duration(file_path)
272
+ max_new_tokens = (
273
+ args.max_new_tokens
274
+ if args.max_new_tokens > 0
275
+ else auto_max_new_tokens(duration)
276
+ )
277
+
278
+ duration_str = f"{duration:.0f}s" if duration else "unknown length"
279
+ logger.info(
280
+ f"[{i}/{len(files)}] {rel} ({duration_str}, "
281
+ f"max_new_tokens={max_new_tokens})..."
282
+ )
283
+
284
+ def log_progress(n, _budget=max_new_tokens):
285
+ if n % PROGRESS_LOG_EVERY_TOKENS == 0:
286
+ logger.info(f" ... {n}/{_budget} tokens")
287
+
288
+ file_start = time.time()
289
+ messages = build_transcription_messages(file_path, prompt=prompt)
290
+ result = generate_transcription(
291
+ model,
292
+ processor,
293
+ messages,
294
+ max_new_tokens=max_new_tokens,
295
+ do_sample=False,
296
+ device=device,
297
+ dtype=dtype,
298
+ token_callback=log_progress,
299
+ )
300
+ file_elapsed = time.time() - file_start
301
+
302
+ raw_text = result["text"]
303
+ generated_tokens = result["generated_tokens"]
304
+ truncated = generated_tokens >= max_new_tokens
305
+ if truncated:
306
+ logger.warning(
307
+ f" Hit max_new_tokens={max_new_tokens} — transcript is likely "
308
+ f"incomplete. Re-run with a higher --max-new-tokens."
309
+ )
310
+
311
+ segments = parse_transcript(raw_text)
312
+ speakers = sorted({seg.speaker for seg in segments})
313
+
314
+ record = {
315
+ "file": str(rel),
316
+ "model": MODEL,
317
+ "duration_s": round(duration, 1) if duration else None,
318
+ "raw_transcript": raw_text,
319
+ "segments": [
320
+ {
321
+ "start": seg.start,
322
+ "end": seg.end,
323
+ "speaker": seg.speaker,
324
+ "text": seg.text,
325
+ }
326
+ for seg in segments
327
+ ],
328
+ "num_segments": len(segments),
329
+ "num_speakers": len(speakers),
330
+ "generated_tokens": generated_tokens,
331
+ "truncated": truncated,
332
+ }
333
+
334
+ json_path = output_dir / rel.with_suffix(".json")
335
+ json_path.parent.mkdir(parents=True, exist_ok=True)
336
+ json_path.write_text(
337
+ json.dumps(record, ensure_ascii=False, indent=2), encoding="utf-8"
338
+ )
339
+
340
+ if args.emit_txt:
341
+ write_txt(segments, json_path.with_suffix(".txt"))
342
+
343
+ if args.emit_srt:
344
+ from moss_transcribe_diarize.subtitle import (
345
+ export_srt,
346
+ subtitle_segments_from_transcript_segments,
347
+ )
348
+
349
+ srt_text = export_srt(
350
+ subtitle_segments_from_transcript_segments(segments),
351
+ show_speaker=True,
352
+ )
353
+ json_path.with_suffix(".srt").write_text(srt_text, encoding="utf-8")
354
+
355
+ if duration:
356
+ total_audio_duration += duration
357
+
358
+ results.append(
359
+ {
360
+ "file": str(rel),
361
+ "duration_s": round(duration, 1) if duration else None,
362
+ "num_segments": len(segments),
363
+ "num_speakers": len(speakers),
364
+ "generated_tokens": generated_tokens,
365
+ "truncated": truncated,
366
+ "elapsed_s": round(file_elapsed, 1),
367
+ }
368
+ )
369
+ logger.info(
370
+ f" -> {json_path.name}: {len(segments)} segments, "
371
+ f"{len(speakers)} speaker(s), {generated_tokens} tokens, "
372
+ f"{file_elapsed:.0f}s"
373
+ )
374
+
375
+ elapsed = time.time() - start_time
376
+
377
+ # Write summary
378
+ summary_path = output_dir / "summary.jsonl"
379
+ with open(summary_path, "w", encoding="utf-8") as f:
380
+ for r in results:
381
+ f.write(json.dumps(r, ensure_ascii=False) + "\n")
382
+
383
+ # Report
384
+ elapsed_str = f"{elapsed / 60:.1f} min" if elapsed > 60 else f"{elapsed:.1f}s"
385
+ truncated_count = sum(1 for r in results if r["truncated"])
386
+ logger.info("=" * 50)
387
+ logger.info(f"Done! Processed {len(files)} file(s) in {elapsed_str}")
388
+ logger.info(f" Output: {output_dir}")
389
+ if total_audio_duration > 0:
390
+ rtfx = total_audio_duration / elapsed
391
+ logger.info(f" Audio: {total_audio_duration / 60:.1f} min total")
392
+ logger.info(f" RTFx: {rtfx:.1f}x realtime")
393
+ if truncated_count:
394
+ logger.warning(f" Truncated: {truncated_count} file(s) hit max_new_tokens")
395
+ logger.info(f" Summary: {summary_path}")
396
+
397
+ if args.verbose:
398
+ import importlib.metadata
399
+
400
+ logger.info("--- Package versions ---")
401
+ for pkg in [
402
+ "moss-transcribe-diarize",
403
+ "transformers",
404
+ "torch",
405
+ "av",
406
+ "librosa",
407
+ "soundfile",
408
+ ]:
409
+ try:
410
+ logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
411
+ except importlib.metadata.PackageNotFoundError:
412
+ logger.info(f" {pkg}: not installed")
413
+
414
+
415
+ if __name__ == "__main__":
416
+ if len(sys.argv) == 1:
417
+ print("=" * 60)
418
+ print("Transcription + Diarization with MOSS-Transcribe-Diarize")
419
+ print("=" * 60)
420
+ print("\nTranscribe audio/video from a directory -> JSON segments")
421
+ print("with timestamps and speaker labels ([S01], [S02], ...).")
422
+ print("One pass per file — no chunking, labels stay consistent.")
423
+ print("Designed for HF Buckets mounted as volumes.")
424
+ print()
425
+ print("Usage:")
426
+ print(" uv run moss-transcribe-diarize.py INPUT_DIR OUTPUT_DIR")
427
+ print()
428
+ print("Examples:")
429
+ print(" uv run moss-transcribe-diarize.py ./audio ./output --emit-txt")
430
+ print(
431
+ " uv run moss-transcribe-diarize.py ./audio ./output --hotwords 'Acme,Dr. Chen'"
432
+ )
433
+ print()
434
+ print("HF Jobs with bucket volumes:")
435
+ print(" hf jobs uv run --flavor l4x1 -s HF_TOKEN \\")
436
+ print(" -e UV_TORCH_BACKEND=cu128 \\")
437
+ print(" -v hf://buckets/user/audio-files:/input:ro \\")
438
+ print(" -v hf://buckets/user/transcripts:/output \\")
439
+ print(" moss-transcribe-diarize.py /input /output --emit-txt --emit-srt")
440
+ print()
441
+ print("For full help: uv run moss-transcribe-diarize.py --help")
442
+ sys.exit(0)
443
+
444
+ main()