Abdelrahman2922 commited on
Commit
8d6afae
·
verified ·
1 Parent(s): 3731ef1

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. omnivoice/cli/__init__.py +0 -0
  2. omnivoice/cli/demo.py +548 -0
  3. omnivoice/cli/infer.py +158 -0
  4. omnivoice/cli/infer_batch.py +545 -0
  5. omnivoice/cli/train.py +74 -0
  6. omnivoice/data/__init__.py +0 -0
  7. omnivoice/data/batching.py +191 -0
  8. omnivoice/data/collator.py +165 -0
  9. omnivoice/data/dataset.py +544 -0
  10. omnivoice/data/processor.py +258 -0
  11. omnivoice/eval/__init__.py +4 -0
  12. omnivoice/eval/models/ecapa_tdnn_wavlm.py +374 -0
  13. omnivoice/eval/models/utmos.py +370 -0
  14. omnivoice/eval/mos/utmos.py +299 -0
  15. omnivoice/eval/speaker_similarity/sim.py +321 -0
  16. omnivoice/eval/utils.py +82 -0
  17. omnivoice/eval/wer/common.py +88 -0
  18. omnivoice/eval/wer/fleurs.py +517 -0
  19. omnivoice/eval/wer/hubert.py +318 -0
  20. omnivoice/eval/wer/minimax.py +596 -0
  21. omnivoice/eval/wer/norm_config_module.py +291 -0
  22. omnivoice/eval/wer/punctuations.lst +188 -0
  23. omnivoice/eval/wer/seedtts.py +413 -0
  24. omnivoice/eval/wer/sensevoice.py +344 -0
  25. omnivoice/eval/wer/text_norm_omni.py +113 -0
  26. omnivoice/models/__init__.py +0 -0
  27. omnivoice/models/omnivoice.py +1598 -0
  28. omnivoice/scripts/__init__.py +0 -0
  29. omnivoice/scripts/denoise_audio.py +1049 -0
  30. omnivoice/scripts/extract_audio_tokens.py +625 -0
  31. omnivoice/scripts/extract_audio_tokens_add_noise.py +819 -0
  32. omnivoice/scripts/jsonl_to_webdataset.py +445 -0
  33. omnivoice/training/__init__.py +0 -0
  34. omnivoice/training/builder.py +236 -0
  35. omnivoice/training/checkpoint.py +180 -0
  36. omnivoice/training/config.py +104 -0
  37. omnivoice/training/trainer.py +353 -0
  38. omnivoice/utils/__init__.py +0 -0
  39. omnivoice/utils/audio.py +343 -0
  40. omnivoice/utils/common.py +56 -0
  41. omnivoice/utils/data_utils.py +68 -0
  42. omnivoice/utils/duration.py +282 -0
  43. omnivoice/utils/lang_map.py +698 -0
  44. omnivoice/utils/text.py +219 -0
  45. omnivoice/utils/voice_design.py +66 -0
  46. sync_data/configs/config.json +40 -0
  47. sync_data/configs/data_saudi.json +16 -0
  48. sync_data/data/dev_raw.jsonl +15 -0
  49. sync_data/data/train_raw.jsonl +280 -0
  50. sync_data/tokens/dev/data.lst +15 -0
omnivoice/cli/__init__.py ADDED
File without changes
omnivoice/cli/demo.py ADDED
@@ -0,0 +1,548 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ """
18
+ Gradio demo for OmniVoice.
19
+
20
+ Supports voice cloning and voice design.
21
+
22
+ Usage:
23
+ omnivoice-demo --model /path/to/checkpoint --port 8000
24
+ """
25
+
26
+ import argparse
27
+ import logging
28
+ from typing import Any, Dict
29
+
30
+ import gradio as gr
31
+ import numpy as np
32
+ import torch
33
+
34
+ from omnivoice import OmniVoice, OmniVoiceGenerationConfig
35
+ from omnivoice.utils.lang_map import LANG_NAMES, lang_display_name
36
+
37
+
38
+ def get_best_device():
39
+ """Auto-detect the best available device: CUDA > MPS > CPU."""
40
+ if torch.cuda.is_available():
41
+ return "cuda"
42
+ if torch.backends.mps.is_available():
43
+ return "mps"
44
+ return "cpu"
45
+
46
+
47
+ # ---------------------------------------------------------------------------
48
+ # Language list — all 600+ supported languages
49
+ # ---------------------------------------------------------------------------
50
+ _ALL_LANGUAGES = ["Auto"] + sorted(lang_display_name(n) for n in LANG_NAMES)
51
+
52
+
53
+ # ---------------------------------------------------------------------------
54
+ # Voice Design instruction templates
55
+ # ---------------------------------------------------------------------------
56
+ # Each option is displayed as "English / 中文".
57
+ # The model expects English for accents and Chinese for dialects.
58
+ _CATEGORIES = {
59
+ "Gender / 性别": ["Male / 男", "Female / 女"],
60
+ "Age / 年龄": [
61
+ "Child / 儿童",
62
+ "Teenager / 少年",
63
+ "Young Adult / 青年",
64
+ "Middle-aged / 中年",
65
+ "Elderly / 老年",
66
+ ],
67
+ "Pitch / 音调": [
68
+ "Very Low Pitch / 极低音调",
69
+ "Low Pitch / 低音调",
70
+ "Moderate Pitch / 中音调",
71
+ "High Pitch / 高音调",
72
+ "Very High Pitch / 极高音调",
73
+ ],
74
+ "Style / 风格": ["Whisper / 耳语"],
75
+ "English Accent / 英文口音": [
76
+ "American Accent / 美式口音",
77
+ "Australian Accent / 澳大利亚口音",
78
+ "British Accent / 英国口音",
79
+ "Chinese Accent / 中国口音",
80
+ "Canadian Accent / 加拿大口音",
81
+ "Indian Accent / 印度口音",
82
+ "Korean Accent / 韩国口音",
83
+ "Portuguese Accent / 葡萄牙口音",
84
+ "Russian Accent / 俄罗斯口音",
85
+ "Japanese Accent / 日本口音",
86
+ ],
87
+ "Chinese Dialect / 中文方言": [
88
+ "Henan Dialect / 河南话",
89
+ "Shaanxi Dialect / 陕西话",
90
+ "Sichuan Dialect / 四川话",
91
+ "Guizhou Dialect / 贵州话",
92
+ "Yunnan Dialect / 云南话",
93
+ "Guilin Dialect / 桂林话",
94
+ "Jinan Dialect / 济南话",
95
+ "Shijiazhuang Dialect / 石家庄话",
96
+ "Gansu Dialect / 甘肃话",
97
+ "Ningxia Dialect / 宁夏话",
98
+ "Qingdao Dialect / 青岛话",
99
+ "Northeast Dialect / 东北话",
100
+ ],
101
+ }
102
+
103
+ _ATTR_INFO = {
104
+ "English Accent / 英文口音": "Only effective for English speech.",
105
+ "Chinese Dialect / 中文方言": "Only effective for Chinese speech.",
106
+ }
107
+
108
+ # ---------------------------------------------------------------------------
109
+ # Argument parser
110
+ # ---------------------------------------------------------------------------
111
+
112
+
113
+ def build_parser() -> argparse.ArgumentParser:
114
+ parser = argparse.ArgumentParser(
115
+ prog="omnivoice-demo",
116
+ description="Launch a Gradio demo for OmniVoice.",
117
+ formatter_class=argparse.RawTextHelpFormatter,
118
+ )
119
+ parser.add_argument(
120
+ "--model",
121
+ default="k2-fsa/OmniVoice",
122
+ help="Model checkpoint path or HuggingFace repo id.",
123
+ )
124
+ parser.add_argument(
125
+ "--device", default=None, help="Device to use. Auto-detected if not specified."
126
+ )
127
+ parser.add_argument("--ip", default="0.0.0.0", help="Server IP (default: 0.0.0.0).")
128
+ parser.add_argument(
129
+ "--port", type=int, default=7860, help="Server port (default: 7860)."
130
+ )
131
+ parser.add_argument(
132
+ "--root-path",
133
+ default=None,
134
+ help="Root path for reverse proxy.",
135
+ )
136
+ parser.add_argument(
137
+ "--share", action="store_true", default=False, help="Create public link."
138
+ )
139
+ parser.add_argument(
140
+ "--no-asr",
141
+ action="store_true",
142
+ default=False,
143
+ help="Skip loading Whisper ASR model. Reference text auto-transcription"
144
+ " will be unavailable.",
145
+ )
146
+ parser.add_argument(
147
+ "--asr-model",
148
+ default="openai/whisper-large-v3-turbo",
149
+ help="ASR model path or HuggingFace repo id"
150
+ " (default: openai/whisper-large-v3-turbo).",
151
+ )
152
+ return parser
153
+
154
+
155
+ # ---------------------------------------------------------------------------
156
+ # Build demo
157
+ # ---------------------------------------------------------------------------
158
+
159
+
160
+ def build_demo(
161
+ model: OmniVoice,
162
+ checkpoint: str,
163
+ generate_fn=None,
164
+ ) -> gr.Blocks:
165
+
166
+ sampling_rate = model.sampling_rate
167
+
168
+ # -- shared generation core --
169
+ def _gen_core(
170
+ text,
171
+ language,
172
+ ref_audio,
173
+ instruct,
174
+ num_step,
175
+ guidance_scale,
176
+ denoise,
177
+ speed,
178
+ duration,
179
+ preprocess_prompt,
180
+ postprocess_output,
181
+ mode,
182
+ ref_text=None,
183
+ ):
184
+ if not text or not text.strip():
185
+ return None, "Please enter the text to synthesize."
186
+
187
+ gen_config = OmniVoiceGenerationConfig(
188
+ num_step=int(num_step or 32),
189
+ guidance_scale=float(guidance_scale) if guidance_scale is not None else 2.0,
190
+ denoise=bool(denoise) if denoise is not None else True,
191
+ preprocess_prompt=bool(preprocess_prompt),
192
+ postprocess_output=bool(postprocess_output),
193
+ )
194
+
195
+ lang = language if (language and language != "Auto") else None
196
+
197
+ kw: Dict[str, Any] = dict(
198
+ text=text.strip(), language=lang, generation_config=gen_config
199
+ )
200
+
201
+ if speed is not None and float(speed) != 1.0:
202
+ kw["speed"] = float(speed)
203
+ if duration is not None and float(duration) > 0:
204
+ kw["duration"] = float(duration)
205
+
206
+ if mode == "clone":
207
+ if not ref_audio:
208
+ return None, "Please upload a reference audio."
209
+ kw["voice_clone_prompt"] = model.create_voice_clone_prompt(
210
+ ref_audio=ref_audio,
211
+ ref_text=ref_text,
212
+ )
213
+
214
+ if instruct and instruct.strip():
215
+ kw["instruct"] = instruct.strip()
216
+
217
+ try:
218
+ audio = model.generate(**kw)
219
+ except Exception as e:
220
+ return None, f"Error: {type(e).__name__}: {e}"
221
+
222
+ waveform = (audio[0] * 32767).astype(np.int16)
223
+ return (sampling_rate, waveform), "Done."
224
+
225
+ # Allow external wrappers (e.g. spaces.GPU for ZeroGPU Spaces)
226
+ _gen = generate_fn if generate_fn is not None else _gen_core
227
+
228
+ # =====================================================================
229
+ # UI
230
+ # =====================================================================
231
+ theme = gr.themes.Soft(
232
+ font=["Inter", "Arial", "sans-serif"],
233
+ )
234
+ css = """
235
+ .gradio-container {max-width: 100% !important; font-size: 16px !important;}
236
+ .gradio-container h1 {font-size: 1.5em !important;}
237
+ .gradio-container .prose {font-size: 1.1em !important;}
238
+ .compact-audio audio {height: 60px !important;}
239
+ .compact-audio .waveform {min-height: 80px !important;}
240
+ """
241
+
242
+ # Reusable: language dropdown component
243
+ def _lang_dropdown(label="Language (optional) / 语种 (可选)", value="Auto"):
244
+ return gr.Dropdown(
245
+ label=label,
246
+ choices=_ALL_LANGUAGES,
247
+ value=value,
248
+ allow_custom_value=False,
249
+ interactive=True,
250
+ info="Keep as Auto to auto-detect the language.",
251
+ )
252
+
253
+ # Reusable: optional generation settings accordion
254
+ def _gen_settings():
255
+ with gr.Accordion("Generation Settings (optional)", open=False):
256
+ sp = gr.Slider(
257
+ 0.5,
258
+ 1.5,
259
+ value=1.0,
260
+ step=0.05,
261
+ label="Speed",
262
+ info="1.0 = normal. >1 faster, <1 slower. Ignored if Duration is set.",
263
+ )
264
+ du = gr.Number(
265
+ value=None,
266
+ label="Duration (seconds)",
267
+ info=(
268
+ "Leave empty to use speed."
269
+ " Set a fixed duration to override speed."
270
+ ),
271
+ )
272
+ ns = gr.Slider(
273
+ 4,
274
+ 64,
275
+ value=32,
276
+ step=1,
277
+ label="Inference Steps",
278
+ info="Default: 32. Lower = faster, higher = better quality.",
279
+ )
280
+ dn = gr.Checkbox(
281
+ label="Denoise",
282
+ value=True,
283
+ info="Default: enabled. Uncheck to disable denoising.",
284
+ )
285
+ gs = gr.Slider(
286
+ 0.0,
287
+ 4.0,
288
+ value=2.0,
289
+ step=0.1,
290
+ label="Guidance Scale (CFG)",
291
+ info="Default: 2.0.",
292
+ )
293
+ pp = gr.Checkbox(
294
+ label="Preprocess Prompt",
295
+ value=True,
296
+ info="apply silence removal and trimming to the reference "
297
+ "audio, add punctuation in the end of reference text (if not already)",
298
+ )
299
+ po = gr.Checkbox(
300
+ label="Postprocess Output",
301
+ value=True,
302
+ info="Remove long silences from generated audio.",
303
+ )
304
+ return ns, gs, dn, sp, du, pp, po
305
+
306
+ with gr.Blocks(theme=theme, css=css, title="OmniVoice Demo") as demo:
307
+ gr.Markdown(
308
+ """
309
+ # OmniVoice Demo
310
+
311
+ State-of-the-art text-to-speech model for **600+ languages**, supporting:
312
+
313
+ - **Voice Clone** — Clone any voice from a reference audio
314
+ - **Voice Design** — Create custom voices with speaker attributes
315
+
316
+ Built with [OmniVoice](https://github.com/k2-fsa/OmniVoice)
317
+ by Xiaomi AI Lab Next-gen Kaldi team.
318
+ """
319
+ )
320
+
321
+ with gr.Tabs():
322
+ # ==============================================================
323
+ # Voice Clone
324
+ # ==============================================================
325
+ with gr.TabItem("Voice Clone"):
326
+ with gr.Row():
327
+ with gr.Column(scale=1):
328
+ vc_text = gr.Textbox(
329
+ label="Text to Synthesize / 待合成文本",
330
+ lines=4,
331
+ placeholder="Enter the text you want to synthesize...",
332
+ )
333
+ vc_ref_audio = gr.Audio(
334
+ label="Reference Audio / 参考音频",
335
+ type="filepath",
336
+ elem_classes="compact-audio",
337
+ )
338
+ gr.Markdown(
339
+ "<span style='font-size:0.85em;color:#888;'>"
340
+ "Recommended: 3–10 seconds audio. "
341
+ "</span>"
342
+ )
343
+ vc_ref_text = gr.Textbox(
344
+ label=("Reference Text (optional)" " / 参考音频文本(可选)"),
345
+ lines=2,
346
+ placeholder="Transcript of the reference audio. Leave empty"
347
+ " to auto-transcribe via ASR models.",
348
+ )
349
+ vc_lang = _lang_dropdown("Language (optional) / 语种 (可选)")
350
+ with gr.Accordion("Instruct (optional)", open=False):
351
+ vc_instruct = gr.Textbox(label="Instruct", lines=2)
352
+ (
353
+ vc_ns,
354
+ vc_gs,
355
+ vc_dn,
356
+ vc_sp,
357
+ vc_du,
358
+ vc_pp,
359
+ vc_po,
360
+ ) = _gen_settings()
361
+ vc_btn = gr.Button("Generate / 生成", variant="primary")
362
+ with gr.Column(scale=1):
363
+ vc_audio = gr.Audio(
364
+ label="Output Audio / 合成结果",
365
+ type="numpy",
366
+ )
367
+ vc_status = gr.Textbox(label="Status / 状态", lines=2)
368
+
369
+ def _clone_fn(
370
+ text, lang, ref_aud, ref_text, instruct, ns, gs, dn, sp, du, pp, po
371
+ ):
372
+ return _gen(
373
+ text,
374
+ lang,
375
+ ref_aud,
376
+ instruct,
377
+ ns,
378
+ gs,
379
+ dn,
380
+ sp,
381
+ du,
382
+ pp,
383
+ po,
384
+ mode="clone",
385
+ ref_text=ref_text or None,
386
+ )
387
+
388
+ vc_btn.click(
389
+ _clone_fn,
390
+ inputs=[
391
+ vc_text,
392
+ vc_lang,
393
+ vc_ref_audio,
394
+ vc_ref_text,
395
+ vc_instruct,
396
+ vc_ns,
397
+ vc_gs,
398
+ vc_dn,
399
+ vc_sp,
400
+ vc_du,
401
+ vc_pp,
402
+ vc_po,
403
+ ],
404
+ outputs=[vc_audio, vc_status],
405
+ )
406
+
407
+ # ==============================================================
408
+ # Voice Design
409
+ # ==============================================================
410
+ with gr.TabItem("Voice Design"):
411
+ with gr.Row():
412
+ with gr.Column(scale=1):
413
+ vd_text = gr.Textbox(
414
+ label="Text to Synthesize / 待合成文本",
415
+ lines=4,
416
+ placeholder="Enter the text you want to synthesize...",
417
+ )
418
+ vd_lang = _lang_dropdown()
419
+
420
+ _AUTO = "Auto"
421
+ vd_groups = []
422
+ for _cat, _choices in _CATEGORIES.items():
423
+ vd_groups.append(
424
+ gr.Dropdown(
425
+ label=_cat,
426
+ choices=[_AUTO] + _choices,
427
+ value=_AUTO,
428
+ info=_ATTR_INFO.get(_cat),
429
+ )
430
+ )
431
+
432
+ (
433
+ vd_ns,
434
+ vd_gs,
435
+ vd_dn,
436
+ vd_sp,
437
+ vd_du,
438
+ vd_pp,
439
+ vd_po,
440
+ ) = _gen_settings()
441
+ vd_btn = gr.Button("Generate / 生成", variant="primary")
442
+ with gr.Column(scale=1):
443
+ vd_audio = gr.Audio(
444
+ label="Output Audio / 合成结果",
445
+ type="numpy",
446
+ )
447
+ vd_status = gr.Textbox(label="Status / 状态", lines=2)
448
+
449
+ def _build_instruct(groups):
450
+ """Extract instruct text from UI dropdowns.
451
+
452
+ Language unification and validation is handled by
453
+ _resolve_instruct inside _preprocess_all.
454
+ """
455
+ selected = [g for g in groups if g and g != "Auto"]
456
+ if not selected:
457
+ return None
458
+ parts = []
459
+ for v in selected:
460
+ if " / " in v:
461
+ en, zh = v.split(" / ", 1)
462
+ # Dialects have no English equivalent
463
+ if "Dialect" in v.split(" / ")[0]:
464
+ parts.append(zh.strip())
465
+ else:
466
+ parts.append(en.strip())
467
+ else:
468
+ parts.append(v)
469
+ return ", ".join(parts)
470
+
471
+ def _design_fn(text, lang, ns, gs, dn, sp, du, pp, po, *groups):
472
+ return _gen(
473
+ text,
474
+ lang,
475
+ None,
476
+ _build_instruct(groups),
477
+ ns,
478
+ gs,
479
+ dn,
480
+ sp,
481
+ du,
482
+ pp,
483
+ po,
484
+ mode="design",
485
+ )
486
+
487
+ vd_btn.click(
488
+ _design_fn,
489
+ inputs=[
490
+ vd_text,
491
+ vd_lang,
492
+ vd_ns,
493
+ vd_gs,
494
+ vd_dn,
495
+ vd_sp,
496
+ vd_du,
497
+ vd_pp,
498
+ vd_po,
499
+ ]
500
+ + vd_groups,
501
+ outputs=[vd_audio, vd_status],
502
+ )
503
+
504
+ return demo
505
+
506
+
507
+ # ---------------------------------------------------------------------------
508
+ # Main
509
+ # ---------------------------------------------------------------------------
510
+
511
+
512
+ def main(argv=None) -> int:
513
+ logging.basicConfig(
514
+ level=logging.INFO,
515
+ format="%(asctime)s %(name)s %(levelname)s: %(message)s",
516
+ )
517
+ parser = build_parser()
518
+ args = parser.parse_args(argv)
519
+
520
+ device = args.device or get_best_device()
521
+
522
+ checkpoint = args.model
523
+ if not checkpoint:
524
+ parser.print_help()
525
+ return 0
526
+ logging.info(f"Loading model from {checkpoint}, device={device} ...")
527
+ model = OmniVoice.from_pretrained(
528
+ checkpoint,
529
+ device_map=device,
530
+ dtype=torch.float16,
531
+ load_asr=not args.no_asr,
532
+ asr_model_name=args.asr_model,
533
+ )
534
+ print("Model loaded.")
535
+
536
+ demo = build_demo(model, checkpoint)
537
+
538
+ demo.queue().launch(
539
+ server_name=args.ip,
540
+ server_port=args.port,
541
+ share=args.share,
542
+ root_path=args.root_path,
543
+ )
544
+ return 0
545
+
546
+
547
+ if __name__ == "__main__":
548
+ raise SystemExit(main())
omnivoice/cli/infer.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Single-item inference CLI for OmniVoice.
2
+
3
+ Generates audio from a single text input using voice cloning,
4
+ voice design, or auto voice.
5
+
6
+ Usage:
7
+ # Voice cloning
8
+ omnivoice-infer --model k2-fsa/OmniVoice \
9
+ --text "Hello, this is a text for text-to-speech." \
10
+ --ref_audio ref.wav --ref_text "Reference transcript." --output out.wav
11
+
12
+ # Voice design
13
+ omnivoice-infer --model k2-fsa/OmniVoice \
14
+ --text "Hello, this is a text for text-to-speech." \
15
+ --instruct "male, British accent" --output out.wav
16
+
17
+ # Auto voice
18
+ omnivoice-infer --model k2-fsa/OmniVoice \
19
+ --text "Hello, this is a text for text-to-speech." --output out.wav
20
+ """
21
+
22
+ import argparse
23
+ import logging
24
+
25
+ import torch
26
+
27
+ import soundfile as sf
28
+
29
+ from omnivoice.models.omnivoice import OmniVoice
30
+ from omnivoice.utils.common import str2bool
31
+
32
+
33
+ def get_best_device():
34
+ """Auto-detect the best available device: CUDA > MPS > CPU."""
35
+ if torch.cuda.is_available():
36
+ return "cuda"
37
+ if torch.backends.mps.is_available():
38
+ return "mps"
39
+ return "cpu"
40
+
41
+
42
+ def get_parser() -> argparse.ArgumentParser:
43
+ parser = argparse.ArgumentParser(
44
+ description="OmniVoice single-item inference",
45
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
46
+ )
47
+ parser.add_argument(
48
+ "--model",
49
+ type=str,
50
+ default="k2-fsa/OmniVoice",
51
+ help="Model checkpoint path or HuggingFace repo id.",
52
+ )
53
+ parser.add_argument(
54
+ "--text",
55
+ type=str,
56
+ required=True,
57
+ help="Text to synthesize.",
58
+ )
59
+ parser.add_argument(
60
+ "--output",
61
+ type=str,
62
+ required=True,
63
+ help="Output WAV file path.",
64
+ )
65
+ # Voice cloning
66
+ parser.add_argument(
67
+ "--ref_audio",
68
+ type=str,
69
+ default=None,
70
+ help="Reference audio file path for voice cloning.",
71
+ )
72
+ parser.add_argument(
73
+ "--ref_text",
74
+ type=str,
75
+ default=None,
76
+ help="Reference text describing the reference audio.",
77
+ )
78
+ # Voice design
79
+ parser.add_argument(
80
+ "--instruct",
81
+ type=str,
82
+ default=None,
83
+ help="Style instruction for voice design mode.",
84
+ )
85
+ parser.add_argument(
86
+ "--language",
87
+ type=str,
88
+ default=None,
89
+ help="Language name (e.g. 'English') or code (e.g. 'en').",
90
+ )
91
+ # Generation parameters
92
+ parser.add_argument("--num_step", type=int, default=32)
93
+ parser.add_argument("--guidance_scale", type=float, default=2.0)
94
+ parser.add_argument("--speed", type=float, default=1.0)
95
+ parser.add_argument(
96
+ "--duration",
97
+ type=float,
98
+ default=None,
99
+ help="Fixed output duration in seconds. If set, overrides the "
100
+ "model's duration estimation. The speed factor is automatically "
101
+ "adjusted to match while preserving language-aware pacing.",
102
+ )
103
+ parser.add_argument("--t_shift", type=float, default=0.1)
104
+ parser.add_argument("--denoise", type=str2bool, default=True)
105
+ parser.add_argument(
106
+ "--postprocess_output",
107
+ type=str2bool,
108
+ default=True,
109
+ )
110
+ parser.add_argument("--layer_penalty_factor", type=float, default=5.0)
111
+ parser.add_argument("--position_temperature", type=float, default=5.0)
112
+ parser.add_argument("--class_temperature", type=float, default=0.0)
113
+ parser.add_argument(
114
+ "--device",
115
+ type=str,
116
+ default=None,
117
+ help="Device to use for inference. Auto-detected if not specified.",
118
+ )
119
+ return parser
120
+
121
+
122
+ def main():
123
+ formatter = "%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s"
124
+ logging.basicConfig(format=formatter, level=logging.INFO, force=True)
125
+
126
+ args = get_parser().parse_args()
127
+
128
+ device = args.device or get_best_device()
129
+ logging.info(f"Loading model from {args.model} on {device} ...")
130
+ model = OmniVoice.from_pretrained(
131
+ args.model, device_map=device, dtype=torch.float16
132
+ )
133
+
134
+ logging.info(f"Generating audio for: {args.text[:80]}...")
135
+ audios = model.generate(
136
+ text=args.text,
137
+ language=args.language,
138
+ ref_audio=args.ref_audio,
139
+ ref_text=args.ref_text,
140
+ instruct=args.instruct,
141
+ duration=args.duration,
142
+ num_step=args.num_step,
143
+ guidance_scale=args.guidance_scale,
144
+ speed=args.speed,
145
+ t_shift=args.t_shift,
146
+ denoise=args.denoise,
147
+ postprocess_output=args.postprocess_output,
148
+ layer_penalty_factor=args.layer_penalty_factor,
149
+ position_temperature=args.position_temperature,
150
+ class_temperature=args.class_temperature,
151
+ )
152
+
153
+ sf.write(args.output, audios[0], model.sampling_rate)
154
+ logging.info(f"Saved to {args.output}")
155
+
156
+
157
+ if __name__ == "__main__":
158
+ main()
omnivoice/cli/infer_batch.py ADDED
@@ -0,0 +1,545 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Batch inference CLI for OmniVoice.
19
+
20
+ Distributes TTS generation across multiple GPUs for large-scale tasks.
21
+ Reads a JSONL test list, generates audio in parallel, and saves results.
22
+
23
+ Usage:
24
+ omnivoice-infer-batch --model k2-fsa/OmniVoice \
25
+ --test_list test.jsonl --res_dir results/
26
+
27
+ Test list format (JSONL, one JSON object per line):
28
+ Required fields: "id", "text"
29
+ Voice cloning: "ref_audio", "ref_text"
30
+ Voice design: "instruct"
31
+ Optional: "language_id", "duration", "speed"
32
+ """
33
+
34
+ import argparse
35
+ import logging
36
+ import multiprocessing as mp
37
+ import os
38
+ import signal
39
+ import time
40
+ import traceback
41
+ from concurrent.futures import ProcessPoolExecutor, as_completed
42
+ from typing import List, Optional, Tuple
43
+
44
+ import torch
45
+ from tqdm import tqdm
46
+
47
+ from omnivoice.models.omnivoice import OmniVoice
48
+ import soundfile as sf
49
+
50
+ from omnivoice.utils.audio import load_audio
51
+ from omnivoice.utils.common import str2bool
52
+ from omnivoice.utils.data_utils import read_test_list
53
+ from omnivoice.utils.duration import RuleDurationEstimator
54
+
55
+
56
+ def get_best_device():
57
+ """Auto-detect the best available device: CUDA > MPS > CPU."""
58
+ if torch.cuda.is_available():
59
+ return "cuda", torch.cuda.device_count()
60
+ if torch.backends.mps.is_available():
61
+ return "mps", 1
62
+ return "cpu", 1
63
+
64
+
65
+ worker_model = None
66
+ SAMPLING_RATE = 24000
67
+
68
+
69
+ def get_parser():
70
+ parser = argparse.ArgumentParser(description="Infer OmniVoice Model")
71
+ parser.add_argument(
72
+ "--model",
73
+ type=str,
74
+ default="k2-fsa/OmniVoice",
75
+ help="Path to the model checkpoint (local dir or HF repo id). "
76
+ "Audio tokenizer is expected at <checkpoint>/audio_tokenizer/.",
77
+ )
78
+ parser.add_argument(
79
+ "--test_list",
80
+ type=str,
81
+ required=True,
82
+ help="Path to the JSONL file containing test samples. "
83
+ "Each line is a JSON object with the following fields: "
84
+ '"id" (str, required): unique name for the output file; '
85
+ '"text" (str, required): text to synthesize; '
86
+ '"ref_audio" (str): path to reference audio for voice cloning; '
87
+ '"ref_text" (str): transcript of the reference audio; '
88
+ '"instruct" (str): instruction for voice design (used when ref_audio is absent); '
89
+ '"language_id" (str): language code, e.g. "en"; '
90
+ '"duration" (float): target duration in seconds; '
91
+ '"speed" (float): speaking speed multiplier. '
92
+ "Only id and text are required; all other fields are optional.",
93
+ )
94
+ parser.add_argument(
95
+ "--res_dir",
96
+ type=str,
97
+ required=True,
98
+ help="Directory to save the generated audio files.",
99
+ )
100
+ parser.add_argument(
101
+ "--num_step",
102
+ type=int,
103
+ default=32,
104
+ help="Number of steps for iterative decoding.",
105
+ )
106
+ parser.add_argument(
107
+ "--guidance_scale",
108
+ type=float,
109
+ default=2.0,
110
+ help="Scale for Classifier-Free Guidance.",
111
+ )
112
+ parser.add_argument(
113
+ "--t_shift",
114
+ type=float,
115
+ default=0.1,
116
+ help="Shift t to smaller ones if t_shift < 1.0",
117
+ )
118
+ parser.add_argument(
119
+ "--nj_per_gpu",
120
+ type=int,
121
+ default=1,
122
+ help="Number of worker processes to spawn per GPU.",
123
+ )
124
+ parser.add_argument(
125
+ "--audio_chunk_duration",
126
+ type=float,
127
+ default=15.0,
128
+ help="Maximum duration of audio chunk (in seconds) for splitting. "
129
+ '"Not split" if <= 0.',
130
+ )
131
+ parser.add_argument(
132
+ "--audio_chunk_threshold",
133
+ type=float,
134
+ default=30.0,
135
+ help=(
136
+ "The duration threshold (in seconds) to decide"
137
+ " whether to split audio into chunks."
138
+ ),
139
+ )
140
+ parser.add_argument(
141
+ "--batch_duration",
142
+ type=float,
143
+ default=1000.0,
144
+ help="Maximum total duration (reference + generated) per batch (seconds).",
145
+ )
146
+ parser.add_argument(
147
+ "--batch_size",
148
+ type=int,
149
+ default=0,
150
+ help="Fixed batch size (number of samples per batch). "
151
+ "If > 0, use fixed-size batching instead of duration-based batching.",
152
+ )
153
+ parser.add_argument(
154
+ "--warmup",
155
+ type=int,
156
+ default=0,
157
+ help="Number of dummy inference runs per worker before real inference "
158
+ "starts, to warm up CUDA kernels and caches.",
159
+ )
160
+ parser.add_argument(
161
+ "--preprocess_prompt",
162
+ type=str2bool,
163
+ default=True,
164
+ help="Whether to preprocess reference audio (silence removal, trimming). "
165
+ "Set to False to keep raw audio.",
166
+ )
167
+ parser.add_argument(
168
+ "--postprocess_output",
169
+ type=str2bool,
170
+ default=True,
171
+ help="Whether to post-process generated audio (remove silence).",
172
+ )
173
+ parser.add_argument(
174
+ "--layer_penalty_factor",
175
+ type=float,
176
+ default=5.0,
177
+ help="The penalty factor for layer-wise sampling.",
178
+ )
179
+ parser.add_argument(
180
+ "--position_temperature",
181
+ type=float,
182
+ default=5.0,
183
+ help="The temperature for position selection.",
184
+ )
185
+ parser.add_argument(
186
+ "--class_temperature",
187
+ type=float,
188
+ default=0.0,
189
+ help="The temperature for class token sampling.",
190
+ )
191
+ parser.add_argument(
192
+ "--denoise",
193
+ type=str2bool,
194
+ default=True,
195
+ help="Whether to add <|denoise|> token in the reference.",
196
+ )
197
+ parser.add_argument(
198
+ "--lang_id",
199
+ type=str,
200
+ default=None,
201
+ help="Language id to use when test_list JSONL entries do not contain "
202
+ "a language_id field.",
203
+ )
204
+ return parser
205
+
206
+
207
+ def process_init(rank_queue, model_checkpoint, warmup=0):
208
+ """Initializer for each worker process.
209
+
210
+ Loads model (with tokenizers and duration estimator) onto a specific GPU
211
+ via ``OmniVoice.from_pretrained()``.
212
+ """
213
+ global worker_model
214
+
215
+ torch.set_num_threads(2)
216
+ torch.set_num_interop_threads(2)
217
+
218
+ formatter = (
219
+ "%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] "
220
+ "[Worker %(process)d] %(message)s"
221
+ )
222
+ logging.basicConfig(format=formatter, level=logging.INFO, force=True)
223
+
224
+ rank = rank_queue.get()
225
+ device_type, device_id = rank
226
+ if device_type == "cpu":
227
+ worker_device = "cpu"
228
+ elif device_type == "mps":
229
+ worker_device = "mps"
230
+ else:
231
+ worker_device = f"cuda:{device_id}"
232
+
233
+ logging.info(f"Initializing worker on device: {worker_device}")
234
+
235
+ worker_model = OmniVoice.from_pretrained(
236
+ model_checkpoint,
237
+ device_map=worker_device,
238
+ dtype=torch.float16,
239
+ )
240
+
241
+ if warmup > 0:
242
+ logging.info(f"Running {warmup} warmup iterations on {worker_device}")
243
+ dummy_ref_audio = (
244
+ torch.randn(1, SAMPLING_RATE),
245
+ SAMPLING_RATE,
246
+ ) # 1s dummy audio
247
+ for i in range(warmup):
248
+ worker_model.generate(
249
+ text=["hello"],
250
+ language=["en"],
251
+ ref_audio=[dummy_ref_audio],
252
+ ref_text=["hello"],
253
+ )
254
+ logging.info(f"Warmup complete on {worker_device}")
255
+
256
+ logging.info(f"Worker on {worker_device} initialized successfully.")
257
+
258
+
259
+ def estimate_sample_total_duration(
260
+ duration_estimator: RuleDurationEstimator,
261
+ text: str,
262
+ ref_text: Optional[str],
263
+ ref_audio_path: Optional[str],
264
+ gen_duration: Optional[float] = None,
265
+ ) -> float:
266
+ """Estimate total duration (ref + generated) for a single sample.
267
+
268
+ When ``ref_audio_path`` is ``None`` (instruct / voice-design mode),
269
+ the reference duration is treated as 0 and only the estimated generated
270
+ duration contributes to the total.
271
+ """
272
+ if ref_audio_path is not None:
273
+ ref_wav = load_audio(ref_audio_path, SAMPLING_RATE)
274
+ ref_duration = ref_wav.shape[-1] / SAMPLING_RATE
275
+ else:
276
+ ref_duration = 0
277
+
278
+ if gen_duration is None:
279
+ if ref_audio_path is not None:
280
+ gen_duration = duration_estimator.estimate_duration(
281
+ text, ref_text or "", ref_duration, low_threshold=2.0
282
+ )
283
+ else:
284
+ gen_duration = duration_estimator.estimate_duration(
285
+ text, "Nice to meet you.", 0.5, low_threshold=2.0
286
+ )
287
+
288
+ total_duration = ref_duration + gen_duration
289
+ return total_duration
290
+
291
+
292
+ def _sort_samples_by_duration(
293
+ samples: List[Tuple],
294
+ duration_estimator: RuleDurationEstimator,
295
+ ) -> List[Tuple[Tuple, float]]:
296
+ """Return (sample, total_duration) pairs sorted by duration descending."""
297
+ sample_with_duration = []
298
+ for sample in samples:
299
+ _, ref_text, ref_audio_path, text, _, dur, _, _ = sample
300
+ total_duration = estimate_sample_total_duration(
301
+ duration_estimator, text, ref_text, ref_audio_path, gen_duration=dur
302
+ )
303
+ sample_with_duration.append((sample, total_duration))
304
+ sample_with_duration.sort(key=lambda x: x[1], reverse=True)
305
+ return sample_with_duration
306
+
307
+
308
+ def cluster_samples_by_duration(
309
+ samples: List[Tuple],
310
+ duration_estimator: RuleDurationEstimator,
311
+ batch_duration: float,
312
+ ) -> List[List[Tuple]]:
313
+ sample_with_duration = _sort_samples_by_duration(samples, duration_estimator)
314
+ batches = []
315
+ current_batch = []
316
+ current_total_duration = 0.0
317
+
318
+ for sample, duration in sample_with_duration:
319
+ if duration > batch_duration:
320
+ batches.append([sample])
321
+ continue
322
+
323
+ if current_total_duration + duration <= batch_duration:
324
+ current_batch.append(sample)
325
+ current_total_duration += duration
326
+ else:
327
+ batches.append(current_batch)
328
+ current_batch = [sample]
329
+ current_total_duration = duration
330
+
331
+ if current_batch:
332
+ batches.append(current_batch)
333
+
334
+ logging.info(f"Clustered {len(samples)} samples into {len(batches)} batches")
335
+ return batches
336
+
337
+
338
+ def cluster_samples_by_batch_size(
339
+ samples: List[Tuple],
340
+ duration_estimator: RuleDurationEstimator,
341
+ batch_size: int,
342
+ ) -> List[List[Tuple]]:
343
+ """Split samples into fixed-size batches, sorted by duration to minimize padding."""
344
+ sample_with_duration = _sort_samples_by_duration(samples, duration_estimator)
345
+ sorted_samples = [s for s, _ in sample_with_duration]
346
+
347
+ batches = [
348
+ sorted_samples[i : i + batch_size]
349
+ for i in range(0, len(sorted_samples), batch_size)
350
+ ]
351
+ logging.info(
352
+ f"Split {len(samples)} samples into {len(batches)} batches "
353
+ f"(fixed batch_size={batch_size}, sorted by duration)"
354
+ )
355
+ return batches
356
+
357
+
358
+ def run_inference_batch(
359
+ batch_samples: List[Tuple],
360
+ res_dir: str,
361
+ **gen_kwargs,
362
+ ) -> List[Tuple]:
363
+ global worker_model
364
+
365
+ save_names = []
366
+ ref_texts = []
367
+ ref_audio_paths = []
368
+ texts = []
369
+ langs = []
370
+ durations = []
371
+ speeds = []
372
+ instructs = []
373
+
374
+ for sample in batch_samples:
375
+ save_name, ref_text, ref_audio_path, text, lang_id, dur, spd, instruct = sample
376
+ save_names.append(save_name)
377
+ ref_texts.append(ref_text)
378
+ ref_audio_paths.append(ref_audio_path)
379
+ texts.append(text)
380
+ langs.append(lang_id)
381
+ durations.append(dur)
382
+ speeds.append(spd)
383
+ instructs.append(instruct)
384
+
385
+ start_time = time.time()
386
+ audios = worker_model.generate(
387
+ text=texts,
388
+ language=langs,
389
+ ref_audio=ref_audio_paths if any(p is not None for p in ref_audio_paths) else None,
390
+ ref_text=ref_texts if any(t is not None for t in ref_texts) else None,
391
+ duration=durations if any(d is not None for d in durations) else None,
392
+ speed=speeds if any(s is not None for s in speeds) else None,
393
+ instruct=instructs if any(i is not None for i in instructs) else None,
394
+ **gen_kwargs,
395
+ )
396
+ batch_synth_time = time.time() - start_time
397
+
398
+ results = []
399
+ for save_name, audio in zip(save_names, audios):
400
+ save_path = os.path.join(res_dir, save_name + ".wav")
401
+ sf.write(save_path, audio, worker_model.sampling_rate)
402
+ audio_duration = audio.shape[-1] / worker_model.sampling_rate
403
+ results.append(
404
+ (
405
+ save_name,
406
+ batch_synth_time / len(batch_samples),
407
+ audio_duration,
408
+ "success",
409
+ )
410
+ )
411
+
412
+ return results
413
+
414
+
415
+ def main():
416
+ formatter = "%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s"
417
+ logging.basicConfig(format=formatter, level=logging.INFO, force=True)
418
+ mp.set_start_method("spawn", force=True)
419
+
420
+ args = get_parser().parse_args()
421
+ os.makedirs(args.res_dir, exist_ok=True)
422
+
423
+ device_type, num_devices = get_best_device()
424
+ if device_type == "cpu":
425
+ logging.warning(
426
+ "No GPU found. Falling back to CPU inference. This might be slow."
427
+ )
428
+
429
+ num_processes = num_devices * args.nj_per_gpu
430
+ logging.info(
431
+ f"Using {device_type} ({num_devices} device(s))."
432
+ f" Spawning {num_processes} worker processes."
433
+ )
434
+
435
+ manager = mp.Manager()
436
+ rank_queue = manager.Queue()
437
+ for rank in list(range(num_devices)) * args.nj_per_gpu:
438
+ rank_queue.put((device_type, rank))
439
+
440
+ samples_raw = read_test_list(args.test_list)
441
+ samples = []
442
+ for s in samples_raw:
443
+ lang_id = args.lang_id if args.lang_id is not None else s.get("language_id")
444
+ samples.append(
445
+ (
446
+ s["id"],
447
+ s.get("ref_text"),
448
+ s.get("ref_audio"),
449
+ s["text"],
450
+ lang_id,
451
+ s.get("duration"),
452
+ s.get("speed"),
453
+ s.get("instruct"),
454
+ )
455
+ )
456
+
457
+ total_synthesis_time = []
458
+ total_audio_duration = []
459
+
460
+ try:
461
+ with ProcessPoolExecutor(
462
+ max_workers=num_processes,
463
+ initializer=process_init,
464
+ initargs=(rank_queue, args.model, args.warmup),
465
+ ) as executor:
466
+ futures = []
467
+
468
+ logging.info("Running batch inference")
469
+
470
+ # Split samples by mode (voice-clone vs non-voice-clone) before
471
+ # clustering so that each batch is homogeneous. Mixing ref_audio
472
+ # and non-ref_audio samples in the same batch would crash in
473
+ # generate() → create_voice_clone_prompt().
474
+ clone_samples = [s for s in samples if s[2] is not None]
475
+ other_samples = [s for s in samples if s[2] is None]
476
+
477
+ duration_estimator = RuleDurationEstimator()
478
+ batches = []
479
+ for subset in (clone_samples, other_samples):
480
+ if not subset:
481
+ continue
482
+ if args.batch_size > 0:
483
+ batches.extend(
484
+ cluster_samples_by_batch_size(
485
+ subset, duration_estimator, args.batch_size
486
+ )
487
+ )
488
+ else:
489
+ batches.extend(
490
+ cluster_samples_by_duration(
491
+ subset, duration_estimator, args.batch_duration
492
+ )
493
+ )
494
+
495
+ args_dict = vars(args)
496
+
497
+ for batch in batches:
498
+ futures.append(
499
+ executor.submit(
500
+ run_inference_batch, batch_samples=batch, **args_dict
501
+ )
502
+ )
503
+
504
+ for future in tqdm(
505
+ as_completed(futures), total=len(futures), desc="Processing samples"
506
+ ):
507
+ try:
508
+ result = future.result()
509
+ for s_name, synth_time, audio_dur, status in result:
510
+ total_synthesis_time.append(synth_time)
511
+ total_audio_duration.append(audio_dur)
512
+ rtf = synth_time / audio_dur if audio_dur > 0 else float("inf")
513
+ logging.debug(
514
+ f"Processed {s_name}: Audio Duration={audio_dur:.2f}s, "
515
+ f"Synthesis Time={synth_time:.2f}s, RTF={rtf:.4f}"
516
+ )
517
+ except Exception as e:
518
+ logging.error(f"Failed to process sample: {e}")
519
+ detailed_error = traceback.format_exc()
520
+ logging.error(f"Detailed error: {detailed_error}")
521
+
522
+ except (Exception, KeyboardInterrupt) as e:
523
+ logging.critical(
524
+ f"An unrecoverable error occurred: {e}. Terminating all processes."
525
+ )
526
+ detailed_error_info = traceback.format_exc()
527
+ logging.error(f"--- DETAILED TRACEBACK ---\n{detailed_error_info}")
528
+ os.killpg(os.getpgid(os.getpid()), signal.SIGKILL)
529
+
530
+ total_synthesis_time = sum(total_synthesis_time)
531
+ total_audio_duration = sum(total_audio_duration)
532
+ logging.info("--- Summary ---")
533
+ logging.info(f"Total audio duration: {total_audio_duration:.2f}s")
534
+ logging.info(f"Total synthesis time: {total_synthesis_time:.2f}s")
535
+ if total_audio_duration > 0:
536
+ average_rtf = total_synthesis_time / total_audio_duration
537
+ logging.info(f"Average RTF: {average_rtf:.4f}")
538
+ else:
539
+ logging.warning("No speech was generated. RTF cannot be computed.")
540
+
541
+ logging.info("Done!")
542
+
543
+
544
+ if __name__ == "__main__":
545
+ main()
omnivoice/cli/train.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Training CLI for OmniVoice.
19
+
20
+ Launches distributed training via HuggingFace Accelerate.
21
+ Supports pre-training on Emilia data and finetuning on custom data.
22
+
23
+ Usage:
24
+ accelerate launch --gpu_ids 0,1,2,3 --num_processes 4 \\
25
+ -m omnivoice.cli.train \\
26
+ --train_config train_config.json \\
27
+ --data_config data_config.json \\
28
+ --output_dir output/
29
+
30
+ See examples/run_emilia.sh and examples/run_finetune.sh for full pipelines.
31
+ """
32
+
33
+ import argparse
34
+
35
+ from omnivoice.training.builder import build_dataloaders, build_model_and_tokenizer
36
+ from omnivoice.training.config import TrainingConfig
37
+ from omnivoice.training.trainer import OmniTrainer
38
+
39
+
40
+ def main():
41
+ parser = argparse.ArgumentParser(description="OmniVoice Training Entry Point")
42
+ parser.add_argument(
43
+ "--train_config", type=str, required=True, help="Path to config JSON"
44
+ )
45
+ parser.add_argument(
46
+ "--output_dir", type=str, required=True, help="Where to save checkpoints"
47
+ )
48
+ parser.add_argument(
49
+ "--data_config", type=str, required=True, help="Path to data config JSON"
50
+ )
51
+ args = parser.parse_args()
52
+
53
+ # 1. Load Configuration
54
+ config = TrainingConfig.from_json(args.train_config)
55
+ config.output_dir = args.output_dir
56
+ config.data_config = args.data_config
57
+
58
+ # 2. Build Components
59
+ model, tokenizer = build_model_and_tokenizer(config)
60
+ train_loader, eval_loader = build_dataloaders(config, tokenizer)
61
+
62
+ # 3. Initialize Trainer and Start
63
+ trainer = OmniTrainer(
64
+ model=model,
65
+ config=config,
66
+ train_dataloader=train_loader,
67
+ eval_dataloader=eval_loader,
68
+ tokenizer=tokenizer,
69
+ )
70
+ trainer.train()
71
+
72
+
73
+ if __name__ == "__main__":
74
+ main()
omnivoice/data/__init__.py ADDED
File without changes
omnivoice/data/batching.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Batching strategies for streaming/iterable datasets.
19
+
20
+ Provides length-based grouping and packing for efficient training with
21
+ variable-length audio.
22
+
23
+ Key classes:
24
+ - ``PackingIterableDataset``: Packs multiple samples into fixed-length sequences
25
+ for training. Used by ``omnivoice.training.builder`` with flex_attention.
26
+ - ``StreamLengthGroupDataset``: Groups samples by length into buckets. Used by
27
+ data processing scripts (e.g. ``omnivoice/scripts/``) and by
28
+ ``omnivoice.training.builder`` when ``attn_implementation != "flex_attention"``.
29
+ """
30
+
31
+ import bisect
32
+ import logging
33
+ from typing import Any, Dict, Iterator, List, Optional
34
+
35
+ import numpy as np
36
+
37
+ from omnivoice.data.dataset import IterableDataReader, WrappedIterableDataset
38
+
39
+
40
+ class StreamLengthGroupDataset(WrappedIterableDataset):
41
+ """A streaming dataset that groups samples by their lengths into buckets.
42
+
43
+ By default, length is measured as audio duration in seconds from a raw
44
+ waveform field. Pass a custom ``length_fn`` to use a different measure —
45
+ e.g. ``lambda s: s["length"]`` for processed training data, in which case
46
+ ``batch_duration`` and ``min/max_length`` should use the same units.
47
+
48
+ If ``processor`` is provided, each raw sample is processed before length
49
+ measurement and bucketing, and the yielded batches contain **processed**
50
+ samples. This allows accurate bucketing by post-processing token length
51
+ (used in the SDPA training path).
52
+ """
53
+
54
+ def __init__(
55
+ self,
56
+ dataset: IterableDataReader,
57
+ batch_duration: float,
58
+ min_length: float = 0.5,
59
+ max_length: float = 30.0,
60
+ num_buckets: int = 20,
61
+ audio_key: str = "audio",
62
+ drop_last: bool = False,
63
+ max_sample: Optional[int] = None,
64
+ length_fn: Optional[Any] = None,
65
+ processor: Optional[Any] = None,
66
+ ):
67
+ self.dataset = dataset
68
+ self.batch_duration = batch_duration
69
+ self.min_length = min_length
70
+ self.max_length = max_length
71
+ self.num_buckets = num_buckets
72
+ self.audio_key = audio_key
73
+ self.drop_last = drop_last
74
+ self.max_sample = max_sample if max_sample is not None else float("inf")
75
+ self.length_fn = length_fn
76
+ self.processor = processor
77
+
78
+ self.boundaries = np.linspace(min_length, max_length, num_buckets + 1)[1:]
79
+
80
+ def set_epoch(self, epoch: int):
81
+ """
82
+ Set the epoch for shuffling.
83
+ """
84
+ self.dataset.set_epoch(epoch)
85
+
86
+ def _get_bucket_id(self, length: float) -> int:
87
+
88
+ return bisect.bisect_left(self.boundaries, length)
89
+
90
+ def __iter__(self) -> Iterator[List[Dict[str, Any]]]:
91
+ buckets = [[] for _ in range(self.num_buckets)]
92
+ bucket_max_len = [0.0] * self.num_buckets
93
+
94
+ for sample in self.dataset:
95
+ if self.processor is not None:
96
+ try:
97
+ sample = self.processor(sample)
98
+ except Exception as e:
99
+ logging.warning(f"Error processing sample: {e}")
100
+ continue
101
+
102
+ if self.length_fn is not None:
103
+ duration = self.length_fn(sample)
104
+ else:
105
+ audio = sample[self.audio_key]
106
+ duration = audio.size(-1) / self.dataset.sample_rate
107
+
108
+ if duration < self.min_length or duration > self.max_length:
109
+ # logging.warning(f"Skipping sample with duration {duration:.2f}s")
110
+ continue
111
+
112
+ b_id = self._get_bucket_id(duration)
113
+ buckets[b_id].append(sample)
114
+
115
+ if duration > bucket_max_len[b_id]:
116
+ bucket_max_len[b_id] = duration
117
+
118
+ if (
119
+ bucket_max_len[b_id] * (len(buckets[b_id]) + 1) >= self.batch_duration
120
+ or len(buckets[b_id]) >= self.max_sample
121
+ ):
122
+ yield buckets[b_id]
123
+ buckets[b_id] = []
124
+ bucket_max_len[b_id] = 0.0
125
+
126
+ if not self.drop_last:
127
+ for b_idx, bucket in enumerate(buckets):
128
+ if bucket:
129
+ yield bucket
130
+ buckets[b_idx] = []
131
+
132
+
133
+ class PackingIterableDataset(WrappedIterableDataset):
134
+ """
135
+ An IterableDataset that dynamically processes samples using a processor
136
+ and packs them into batches based on the real token count.
137
+
138
+ Args:
139
+ dataset (Iterable): The raw dataset to process.
140
+ processor (Callable): A processor to process each sample.
141
+ batch_tokens (int): Maximum number of tokens per batch.
142
+ """
143
+
144
+ def __init__(
145
+ self,
146
+ dataset: IterableDataReader,
147
+ processor: Any,
148
+ batch_tokens: int,
149
+ ):
150
+ self.dataset = dataset
151
+ self.processor = processor
152
+ self.batch_tokens = batch_tokens
153
+ self.skip_batches = 0
154
+
155
+ def set_epoch(self, epoch: int):
156
+ """
157
+ Set the epoch for shuffling.
158
+ """
159
+ self.dataset.set_epoch(epoch)
160
+
161
+ def __iter__(self) -> Iterator[List[Dict[str, Any]]]:
162
+ current_batch = []
163
+ current_token_count = 0
164
+
165
+ for raw_sample in self.dataset:
166
+ # Process the sample using the processor
167
+ try:
168
+ processed_sample = self.processor(raw_sample)
169
+ except Exception as e:
170
+ logging.warning(f"Error processing sample {raw_sample}: {e}")
171
+ continue
172
+
173
+ sample_length = processed_sample["length"]
174
+
175
+ if sample_length > self.batch_tokens:
176
+ continue
177
+
178
+ # Check if adding this sample exceeds the batch token limit
179
+ if current_token_count + sample_length > self.batch_tokens:
180
+ # Yield the current batch and start a new one
181
+ yield current_batch
182
+ current_batch = []
183
+ current_token_count = 0
184
+
185
+ # Add the processed sample to the current batch
186
+ current_batch.append(processed_sample)
187
+ current_token_count += sample_length
188
+
189
+ # Yield the last batch if it's not empty
190
+ if current_batch:
191
+ yield current_batch
omnivoice/data/collator.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Data collators for OmniVoice training.
19
+
20
+ Two strategies are available:
21
+
22
+ - ``PackingDataCollator``: Concatenates samples into a single long sequence
23
+ (sequence packing). Used with flex_attention. Batch shape is ``[1, C, L]``.
24
+ - ``PaddingDataCollator``: Pads samples to the same length and stacks them.
25
+ Used with SDPA/eager attention. Batch shape is ``[B, C, max_len]``.
26
+ """
27
+
28
+ from typing import Any, Dict, List
29
+
30
+ import torch
31
+
32
+
33
+ class PaddingDataCollator:
34
+ """Pads a list of processed samples to the same length and stacks them.
35
+
36
+ Produces a standard ``[B, C, max_len]`` batch suitable for SDPA/eager
37
+ attention, where B is the number of samples in the batch, C is the number
38
+ of audio codebook layers, and max_len is the longest sequence in the batch.
39
+
40
+ A 4D boolean attention mask of shape ``[B, 1, max_len, max_len]`` is included.
41
+ Each query position can attend to all non-padding key positions (bidirectional),
42
+ matching the masked-diffusion training objective. When passed as a 4D tensor,
43
+ HuggingFace models use it directly without adding an additional causal mask.
44
+
45
+ No ``document_ids`` are emitted — each sample occupies its own batch row.
46
+ """
47
+
48
+ def __init__(self, processor, batch_tokens: int):
49
+ self.batch_tokens = batch_tokens
50
+ self.processor = processor
51
+
52
+ def __call__(self, processed_samples: List[Dict[str, Any]]) -> Dict[str, Any]:
53
+ pad_id = self.processor.text_tokenizer.pad_token_id
54
+ max_len = max(s["length"] for s in processed_samples)
55
+ B = len(processed_samples)
56
+
57
+ padded_input_ids = []
58
+ padded_labels = []
59
+ padded_audio_mask = []
60
+ padded_position_ids = []
61
+ # valid[b, j] = True if position j is a real (non-padding) token for sample b
62
+ valid = torch.zeros(B, max_len, dtype=torch.bool)
63
+
64
+ for i, s in enumerate(processed_samples):
65
+ length = s["length"]
66
+ pad = max_len - length
67
+
68
+ padded_input_ids.append(
69
+ torch.nn.functional.pad(s["input_ids"], (0, pad), value=pad_id)
70
+ ) # [C, max_len]
71
+ padded_labels.append(
72
+ torch.nn.functional.pad(s["labels"], (0, pad), value=-100)
73
+ ) # [C, max_len]
74
+ padded_audio_mask.append(
75
+ torch.nn.functional.pad(s["audio_mask"], (0, pad), value=False)
76
+ ) # [max_len]
77
+ padded_position_ids.append(
78
+ torch.nn.functional.pad(
79
+ torch.arange(length, dtype=torch.long), (0, pad), value=0
80
+ )
81
+ ) # [max_len]
82
+ valid[i, :length] = True
83
+
84
+ # Stack into [B, C, max_len] / [B, max_len]
85
+ input_ids = torch.stack(padded_input_ids, dim=0) # [B, C, max_len]
86
+ labels = torch.stack(padded_labels, dim=0) # [B, C, max_len]
87
+ audio_mask = torch.stack(padded_audio_mask, dim=0) # [B, max_len]
88
+ position_ids = torch.stack(padded_position_ids, dim=0) # [B, max_len]
89
+
90
+ # 4D bidirectional attention mask: mask[b, 0, i, j] = valid[b, j]
91
+ # All query positions attend to all non-padding key positions.
92
+ attention_mask = valid[:, None, None, :].expand(B, 1, max_len, max_len).contiguous()
93
+
94
+ return {
95
+ "input_ids": input_ids, # [B, C, max_len]
96
+ "labels": labels, # [B, C, max_len]
97
+ "audio_mask": audio_mask, # [B, max_len]
98
+ "position_ids": position_ids, # [B, max_len]
99
+ "attention_mask": attention_mask, # [B, 1, max_len, max_len]
100
+ }
101
+
102
+
103
+ class PackingDataCollator:
104
+ def __init__(self, processor, batch_tokens: int):
105
+ self.batch_tokens = batch_tokens
106
+ self.processor = processor
107
+
108
+ def __call__(self, processed_samples: List[Dict[str, Any]]) -> Dict[str, Any]:
109
+
110
+ target_length = self.batch_tokens
111
+
112
+ input_ids = torch.cat(
113
+ [s["input_ids"] for s in processed_samples], dim=1
114
+ ) # [C, Total_Len], C is the number of codebook layers of the audio tokenizer
115
+ labels = torch.cat(
116
+ [s["labels"] for s in processed_samples], dim=1
117
+ ) # [C, Total_Len]
118
+ audio_mask = torch.cat(
119
+ [s["audio_mask"] for s in processed_samples], dim=0
120
+ ) # [Total_Len]
121
+
122
+ position_ids = torch.cat(
123
+ [torch.arange(s["length"], dtype=torch.long) for s in processed_samples],
124
+ dim=0,
125
+ ) # [Total_Len]
126
+
127
+ pad_length = target_length - input_ids.shape[1]
128
+
129
+ input_ids = torch.nn.functional.pad(
130
+ input_ids,
131
+ pad=(0, pad_length),
132
+ value=self.processor.text_tokenizer.pad_token_id,
133
+ )
134
+
135
+ labels = torch.nn.functional.pad(labels, pad=(0, pad_length), value=-100)
136
+
137
+ audio_mask = torch.nn.functional.pad(
138
+ audio_mask, pad=(0, pad_length), value=False
139
+ )
140
+
141
+ position_ids = torch.nn.functional.pad(
142
+ position_ids, pad=(0, pad_length), value=0
143
+ )
144
+
145
+ return_list = {
146
+ "input_ids": input_ids.unsqueeze(0), # [1, C, L]
147
+ "labels": labels.unsqueeze(0), # [1, C, L]
148
+ "audio_mask": audio_mask.unsqueeze(0), # [1, L]
149
+ "position_ids": position_ids.unsqueeze(0), # [1, L]
150
+ }
151
+
152
+ document_ids_list = []
153
+
154
+ for i, s in enumerate(processed_samples):
155
+ seq_len = s["length"]
156
+ document_ids_list.append(torch.full((seq_len,), i, dtype=torch.int32))
157
+
158
+ document_ids = torch.cat(document_ids_list, dim=0)
159
+
160
+ document_ids = torch.nn.functional.pad(
161
+ document_ids, pad=(0, pad_length), value=-1
162
+ )
163
+ return_list["document_ids"] = document_ids.unsqueeze(0) # [1, L]
164
+
165
+ return return_list
omnivoice/data/dataset.py ADDED
@@ -0,0 +1,544 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Dataset and data-loading utilities for training and evaluation.
19
+
20
+ Provides WebDataset-based iterable datasets, manifest parsing, and audio/token
21
+ loading. Used by ``omnivoice.training.builder.build_dataloaders()`` to construct
22
+ train and eval data loaders.
23
+
24
+ Key functions:
25
+ - ``prepare_data_manifests_from_json()``: Parses a data config JSON into train/dev
26
+ manifests.
27
+
28
+ Key classes:
29
+ - ``WebDatasetReader``: Reads audio/text pairs from WebDataset tar shards as an
30
+ iterable dataset.
31
+ - ``MuxWebDatasetReader``: Multiplexes multiple WebDataset readers for
32
+ multilingual data.
33
+ - ``JsonlDatasetReader``: Reads audio/text pairs from a JSONL manifest file.
34
+ Used by data processing scripts (e.g. ``omnivoice/scripts/``).
35
+ - ``SampleDecoder``: Decodes individual samples (audio or tokens + labels).
36
+ """
37
+
38
+ import io
39
+ import json
40
+ import logging
41
+ import os
42
+ import random
43
+ from typing import Any, Dict, Iterator, List, Optional, Tuple
44
+
45
+ import torch
46
+ import torch.distributed as dist
47
+ import webdataset as wds
48
+
49
+ from omnivoice.utils.audio import load_audio, load_audio_bytes
50
+ from torch.utils.data import IterableDataset
51
+
52
+
53
+ def load_audio_webdataset(data, sample_rate: int = 24000, device="cpu"):
54
+ """
55
+ Load audio from bytes data and resample to the target sample rate if needed.
56
+ Return a tensor of shape (1, num_samples)
57
+ """
58
+ audio = torch.from_numpy(load_audio_bytes(data, sample_rate))
59
+ audio = audio.to(device)
60
+ return audio
61
+
62
+
63
+ def prepare_data_manifests_from_json(
64
+ data_config: str,
65
+ ) -> Tuple[List[Tuple[str, str, int, float]], List[Tuple[str, str, int, float]]]:
66
+ """
67
+ Prepare data manifests from a json file.
68
+ A typical multilingual json file is in the following format:
69
+ {
70
+ "train":
71
+ [
72
+ {
73
+ "language_id": "en",
74
+ "manifest_path": [
75
+ "/Emilia/EN/data.lst"
76
+ ],
77
+ "repeat": 1
78
+ },
79
+ {
80
+ "language_id": "zh",
81
+ "manifest_path": [
82
+ "/Emilia/ZH/data.lst"
83
+ ],
84
+ "repeat": 1
85
+ }
86
+ ],
87
+ "dev":
88
+ [
89
+ {
90
+ "language_id": "en",
91
+ "manifest_path": [
92
+ "/Emilia/EN-dev/data.lst"
93
+ ],
94
+ "repeat": 1
95
+ },
96
+ {
97
+ "language_id": "zh",
98
+ "manifest_path": [
99
+ "/Emilia/ZH-dev/data.lst"
100
+ ],
101
+ "repeat": 1
102
+ }
103
+ ]
104
+ }
105
+
106
+ "language_id" is not used, just for better organization of multilingual data.
107
+ "repeat" is an optional field, default to 1, which indicates how many times
108
+ the manifest should be repeated.
109
+
110
+ The simplist format is like:
111
+ {
112
+ "train":
113
+ [
114
+ {
115
+ "manifest_path": [
116
+ "/Emilia/EN/data.lst",
117
+ "/Emilia/ZH/data.lst"
118
+ ],
119
+ }
120
+ ],
121
+ "dev":
122
+ [
123
+ {
124
+ "manifest_path": [
125
+ "/Emilia/EN-dev/data.lst",
126
+ "/Emilia/ZH-dev/data.lst"
127
+ ],
128
+ }
129
+ ]
130
+
131
+ data.lst format (items separated by space):
132
+ /path/to/data.tar /path/to/label.jsonl num_items num_seconds
133
+ """
134
+ train_manifests = []
135
+ dev_manifests = []
136
+ with open(data_config, "r", encoding="utf-8") as f:
137
+ data = json.load(f)
138
+ for item in data["train"]:
139
+ manifest_paths = item["manifest_path"]
140
+ repeat = item.get("repeat", 1)
141
+ for manifest_path in manifest_paths:
142
+ # assert manifest_path is a file
143
+ assert os.path.isfile(manifest_path), f"{manifest_path} is not a file."
144
+ train_manifests.extend(
145
+ webdataset_manifest_reader(manifest_path) * repeat
146
+ )
147
+ if "dev" in data:
148
+ for item in data["dev"]:
149
+ manifest_paths = item["manifest_path"]
150
+ repeat = item.get("repeat", 1)
151
+ for manifest_path in manifest_paths:
152
+ dev_manifests.extend(
153
+ webdataset_manifest_reader(manifest_path) * repeat
154
+ )
155
+ return train_manifests, dev_manifests
156
+
157
+
158
+ def webdataset_manifest_reader(
159
+ manifest_path: str,
160
+ ) -> List[Tuple[str, str]]:
161
+ """
162
+ Read a manifest file containing webdataset tar paths and label jsonl paths.
163
+ Each line in the manifest file is in the format of:
164
+ /path/to/data.tar /path/to/label.jsonl num_items num_seconds
165
+ """
166
+ manifests = []
167
+ with open(manifest_path, "r", encoding="utf-8") as f:
168
+ for line in f:
169
+ line = line.strip()
170
+ if not line:
171
+ continue
172
+ parts = line.split()
173
+ if len(parts) != 4:
174
+ raise ValueError(
175
+ f"Invalid manifest line: {line}. "
176
+ f"Each line must contain "
177
+ "tar_path, label_jsonl_path, num_items, num_seconds."
178
+ )
179
+ tar_path, label_jsonl_path, num_items, num_seconds = (
180
+ parts[0],
181
+ parts[1],
182
+ int(parts[2]),
183
+ float(parts[3]),
184
+ )
185
+ manifests.append((tar_path, label_jsonl_path, num_items, num_seconds))
186
+ return manifests
187
+
188
+
189
+ class SampleDecoder:
190
+ """
191
+ Decode a sample from webdataset, including loading audio/tokens and fetching label.
192
+ """
193
+
194
+ def __init__(
195
+ self,
196
+ tar_to_label: Dict,
197
+ sample_rate: int = 24000,
198
+ audio_format: Optional[Tuple[str]] = None,
199
+ normalize_audio: bool = True,
200
+ ):
201
+ """
202
+ Args:
203
+ tar_to_label:
204
+ A dict mapping from audio tar file to label tar file.
205
+ sample_rate:
206
+ Target sample rate for audio. Required if audio is loaded.
207
+ audio_format:
208
+ Tuple of audio file extensions to look for in the sample.
209
+ """
210
+ self.tar_to_label = tar_to_label
211
+ self.sample_rate = sample_rate
212
+ self.label_dataset = None
213
+ if audio_format is None:
214
+ self.audio_format = ("flac", "wav", "mp3")
215
+ else:
216
+ self.audio_format = audio_format
217
+ self.normalize_audio = normalize_audio
218
+
219
+ def __call__(self, sample):
220
+ return_dict = {}
221
+ src = sample["__url__"]
222
+ key = sample["__key__"]
223
+ if (
224
+ self.label_dataset is None
225
+ or self.label_dataset.path != self.tar_to_label[src]
226
+ ):
227
+ self.label_dataset = LabelDataset(self.tar_to_label[src])
228
+
229
+ audio = torch.empty(0)
230
+ if "npy" in sample:
231
+ audio_tokens = torch.from_numpy(sample["npy"])
232
+ return_dict["audio_tokens"] = audio_tokens
233
+ else:
234
+ for ext in self.audio_format:
235
+ if ext in sample:
236
+ # load audio (1, num_samples)
237
+ audio = load_audio_webdataset(
238
+ sample[ext], sample_rate=self.sample_rate
239
+ )
240
+ if self.normalize_audio:
241
+ audio = (audio / (audio.abs().max() + 1e-7)) * 0.9
242
+ break
243
+ return_dict["audio"] = audio
244
+ return_dict["audio_duration"] = audio.size(-1) / self.sample_rate
245
+
246
+ label = self.label_dataset[key]
247
+
248
+ return_dict["label"] = label
249
+ return return_dict
250
+
251
+
252
+ class LabelDataset:
253
+ def __init__(self, jsonl_path: str):
254
+ """
255
+ Load labels from a jsonl file.
256
+ Args:
257
+ jsonl_path:
258
+ Path to the jsonl file containing labels.
259
+ Each line in the manifest file is in the format of:
260
+ {"idx": "idx", "text": "transcription text"}
261
+ """
262
+ self._labels = {}
263
+ self.path = jsonl_path
264
+ if not os.path.exists(jsonl_path):
265
+ raise FileNotFoundError(f"Label jsonl file {jsonl_path} does not exist.")
266
+ with open(jsonl_path, "r", encoding="utf-8") as f:
267
+ for line in f:
268
+ line = line.strip()
269
+ if not line:
270
+ continue
271
+ item = json.loads(line)
272
+ if "id" in item:
273
+ self._labels[item["id"]] = item
274
+
275
+ def __getitem__(self, key):
276
+ return self._labels[key]
277
+
278
+
279
+ class IterableDataReader:
280
+ "Interfaces for classes reading data."
281
+
282
+ sample_rate: int
283
+
284
+ def set_epoch(self, epoch: int):
285
+ raise NotImplementedError
286
+
287
+ def __iter__(self) -> Iterator[Dict[str, Any]]:
288
+ raise NotImplementedError
289
+
290
+ def __len__(self) -> int:
291
+ raise NotImplementedError
292
+
293
+
294
+ class WrappedIterableDataset(IterableDataset):
295
+ "IterableDataset interfaces in this project."
296
+
297
+ def set_epoch(self, epoch: int):
298
+ raise NotImplementedError
299
+
300
+ def __iter__(self) -> Iterator[List[Dict[str, Any]]]:
301
+ raise NotImplementedError
302
+
303
+
304
+ class WebDatasetReader(IterableDataReader):
305
+ def __init__(
306
+ self,
307
+ manifests: List[Tuple[str, str, int, float]],
308
+ evaluation: bool = False,
309
+ shuffle_buffer_size: int = 20000,
310
+ sample_rate: int = 24000,
311
+ ):
312
+ self.shuffle_buffer_size = shuffle_buffer_size
313
+ self.evaluation = evaluation
314
+ self.epoch = 0
315
+
316
+ self.orig_urls = []
317
+ self.tar_to_label = {}
318
+ self.num_items = 0
319
+ self.num_seconds = 0.0
320
+ for tar_path, label_jsonl_path, num_items, num_seconds in manifests:
321
+ self.orig_urls.append(tar_path)
322
+ self.tar_to_label[tar_path] = label_jsonl_path
323
+ self.num_items += num_items
324
+ self.num_seconds += num_seconds
325
+ self.urls = self.orig_urls.copy()
326
+ self.sample_decoder = SampleDecoder(
327
+ tar_to_label=self.tar_to_label,
328
+ sample_rate=sample_rate,
329
+ )
330
+ self.sample_rate = sample_rate
331
+
332
+ def set_epoch(self, epoch: int):
333
+ """
334
+ Set the epoch for shuffling.
335
+ """
336
+ self.epoch = epoch
337
+ self.urls = self.orig_urls.copy()
338
+ if not self.evaluation:
339
+ random.Random(epoch).shuffle(self.urls)
340
+
341
+ def __iter__(self) -> Iterator[Dict[str, Any]]:
342
+
343
+ dataset = wds.WebDataset(
344
+ self.urls,
345
+ shardshuffle=False,
346
+ workersplitter=wds.split_by_worker,
347
+ nodesplitter=wds.split_by_node,
348
+ )
349
+
350
+ pipeline = dataset.decode().map(self.sample_decoder)
351
+ if not self.evaluation:
352
+ pipeline = pipeline.shuffle(self.shuffle_buffer_size, seed=self.epoch)
353
+ return iter(pipeline)
354
+
355
+ def __len__(self) -> int:
356
+ return self.num_items
357
+
358
+
359
+ class JsonlDatasetReader(IterableDataReader):
360
+ """Read raw JSONL and load audio files, matching WebDatasetReader output format.
361
+
362
+ Each JSONL line should be a JSON object with at least:
363
+ {"id": "...", "audio_path": "/path/to/audio.wav", ...}
364
+
365
+ Yields dicts of the form: {"audio": Tensor(1, T), "label": dict}
366
+ """
367
+
368
+ def __init__(
369
+ self,
370
+ jsonl_path: str,
371
+ sample_rate: int = 24_000,
372
+ shuffle: bool = True,
373
+ shuffle_seed: int = 42,
374
+ normalize_audio: bool = True,
375
+ ):
376
+ self.jsonl_path = jsonl_path
377
+ self.sample_rate = sample_rate
378
+ self.shuffle = shuffle
379
+ self.shuffle_seed = shuffle_seed
380
+ self.normalize_audio = normalize_audio
381
+
382
+ def set_epoch(self, epoch: int):
383
+ self.shuffle_seed = epoch
384
+
385
+ def _read_lines(self) -> list[dict]:
386
+ entries = []
387
+ with open(self.jsonl_path, "r", encoding="utf-8") as f:
388
+ for line in f:
389
+ line = line.strip()
390
+ if line:
391
+ entries.append(json.loads(line))
392
+ if self.shuffle:
393
+ random.seed(self.shuffle_seed)
394
+ random.shuffle(entries)
395
+ logging.info(
396
+ f"Shuffled {len(entries)} JSONL entries (seed={self.shuffle_seed})"
397
+ )
398
+ return entries
399
+
400
+ def _stream_lines(self):
401
+ with open(self.jsonl_path, "r", encoding="utf-8") as f:
402
+ for line in f:
403
+ line = line.strip()
404
+ if line:
405
+ yield json.loads(line)
406
+
407
+ def __iter__(self):
408
+ source = self._read_lines() if self.shuffle else self._stream_lines()
409
+
410
+ # Split data across distributed ranks (multi-GPU / DDP)
411
+ if dist.is_initialized():
412
+ rank = dist.get_rank()
413
+ world_size = dist.get_world_size()
414
+ source = [item for i, item in enumerate(source) if i % world_size == rank]
415
+
416
+ # Split data across DataLoader workers to avoid duplication
417
+ worker_info = torch.utils.data.get_worker_info()
418
+ if worker_info is not None:
419
+ source = (
420
+ item
421
+ for i, item in enumerate(source)
422
+ if i % worker_info.num_workers == worker_info.id
423
+ )
424
+
425
+ for meta in source:
426
+ audio_path = meta.get("audio_path")
427
+ if not audio_path or not os.path.exists(audio_path):
428
+ logging.warning(
429
+ f"Skipping {meta.get('id', '?')}: audio_path missing or not found"
430
+ )
431
+ continue
432
+ try:
433
+ waveform = torch.from_numpy(
434
+ load_audio(audio_path, self.sample_rate)
435
+ )
436
+ if self.normalize_audio:
437
+ waveform = (waveform / (waveform.abs().max() + 1e-7)) * 0.9
438
+ meta["audio_duration"] = waveform.shape[1] / self.sample_rate
439
+ yield {"audio": waveform, "label": meta}
440
+ except Exception as e:
441
+ logging.warning(f"Skipping {meta.get('id', '?')}: {e}")
442
+
443
+
444
+ class MuxWebDatasetReader(IterableDataReader):
445
+ def __init__(
446
+ self,
447
+ readers: List[WebDatasetReader],
448
+ weights: Optional[List[float]] = None,
449
+ stop_early: bool = False,
450
+ seed: int = 0,
451
+ ):
452
+ self.readers = readers
453
+ self.stop_early = stop_early
454
+ self.mux_iterator = LazyIteratorMultiplexer(
455
+ *readers,
456
+ stop_early=stop_early,
457
+ weights=weights,
458
+ seed=seed,
459
+ )
460
+
461
+ def set_epoch(self, epoch: int):
462
+ """
463
+ Set the epoch for shuffling.
464
+ """
465
+ for reader in self.readers:
466
+ reader.set_epoch(epoch)
467
+
468
+ def __iter__(self) -> Iterator[Dict[str, Any]]:
469
+ return iter(self.mux_iterator)
470
+
471
+
472
+ class LazyIteratorMultiplexer:
473
+ """
474
+ A wrapper over multiple iterators that enables to combine
475
+ lazy manifests in Lhotse. During iteration, unlike
476
+ :class:`.LazyIteratorChain`,
477
+ :class:`.LazyIteratorMultiplexer` at each step randomly
478
+ selects the iterable used to yield an item.
479
+
480
+ Since the iterables might be of different length, we provide
481
+ a ``weights`` parameter to let the user decide which iterables
482
+ should be sampled more frequently than others.
483
+ When an iterable is exhausted, we will keep sampling from the other iterables, until
484
+ we exhaust them all, unless ``stop_early`` is set to ``True``.
485
+ """
486
+
487
+ def __init__(
488
+ self,
489
+ *iterators: IterableDataReader,
490
+ stop_early: bool = False,
491
+ weights: Optional[List[float]] = None,
492
+ seed: int = 0,
493
+ ) -> None:
494
+ self.iterators = list(iterators)
495
+ self.stop_early = stop_early
496
+ self.seed = seed
497
+
498
+ assert (
499
+ len(self.iterators) > 1
500
+ ), "There have to be at least two iterables to multiplex."
501
+
502
+ if weights is None:
503
+ if all(hasattr(it, "__len__") for it in self.iterators):
504
+ lengths = [len(it) for it in self.iterators]
505
+ total_length = sum(lengths)
506
+ self.weights = [length / total_length for length in lengths]
507
+ else:
508
+ self.weights = [1] * len(self.iterators)
509
+ else:
510
+ self.weights = weights
511
+
512
+ assert len(self.iterators) == len(self.weights)
513
+
514
+ def __iter__(self):
515
+
516
+ rng = random.Random(self.seed)
517
+ iters = [iter(it) for it in self.iterators]
518
+ exhausted = [False for _ in range(len(iters))]
519
+
520
+ def should_continue():
521
+ if self.stop_early:
522
+ return not any(exhausted)
523
+ else:
524
+ return not all(exhausted)
525
+
526
+ while should_continue():
527
+ active_indexes, active_weights = zip(
528
+ *[
529
+ (i, w)
530
+ for i, (is_exhausted, w) in enumerate(zip(exhausted, self.weights))
531
+ if not is_exhausted
532
+ ]
533
+ )
534
+ idx = rng.choices(active_indexes, weights=active_weights, k=1)[0]
535
+ selected = iters[idx]
536
+ try:
537
+ item = next(selected)
538
+ yield item
539
+ except StopIteration:
540
+ exhausted[idx] = True
541
+ continue
542
+
543
+ def __len__(self) -> int:
544
+ return sum(len(iterator) for iterator in self.iterators)
omnivoice/data/processor.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Training sample processor for OmniVoice.
19
+
20
+ Converts raw audio/text samples into model-ready tensors: applies prompt/mask
21
+ tokenization, randomly drops conditioning, and injects language/instruct tokens.
22
+ Used by ``omnivoice.training.builder`` to build the data pipeline.
23
+
24
+ Contains two processor classes:
25
+ - ``OmniVoiceSampleProcessor``: Full processor used for training.
26
+ - ``OmniVoiceSimpleSampleProcessor``: Simplified processor (not used for training).
27
+ """
28
+
29
+ import random
30
+ from typing import Any, Dict
31
+
32
+ import torch
33
+
34
+
35
+ class OmniVoiceSampleProcessor:
36
+ """
37
+ Handles the logic of processing a raw sample into tensors
38
+ (masking, tokenization, etc.).
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ text_tokenizer: Any,
44
+ num_channels: int,
45
+ audio_mask_id: int,
46
+ prompt_ratio_range: tuple,
47
+ mask_ratio_range: tuple,
48
+ drop_cond_ratio: float,
49
+ language_ratio: float,
50
+ use_pinyin_ratio: float,
51
+ instruct_ratio: float,
52
+ only_instruct_ratio: float,
53
+ ):
54
+ self.text_tokenizer = text_tokenizer
55
+ self.num_channels = num_channels
56
+ self.audio_mask_id = audio_mask_id
57
+ self.prompt_ratio_range = prompt_ratio_range
58
+ self.mask_ratio_range = mask_ratio_range
59
+ self.drop_cond_ratio = drop_cond_ratio
60
+
61
+ self.language_ratio = language_ratio
62
+ self.use_pinyin_ratio = use_pinyin_ratio
63
+ self.instruct_ratio = instruct_ratio
64
+ self.only_instruct_ratio = only_instruct_ratio
65
+
66
+ def __call__(self, sample: Dict[str, Any]) -> Dict[str, Any]:
67
+
68
+ # clean_start_token_idx is only used for prompt denoising training,
69
+ # where the prompt region is augmented with noises and the model
70
+ # needs to learn to recover the clean prompt.
71
+ # clean_start_token_idx indicates the start index of the clean generated token.
72
+ if "clean_start_token_idx" in sample["label"]:
73
+ drop_cond = False
74
+ else:
75
+ drop_cond = random.uniform(0, 1) < self.drop_cond_ratio
76
+
77
+ if drop_cond:
78
+ prompt_ratio = 0.0
79
+ drop_text = True
80
+ use_language = False
81
+ use_instruct = False
82
+ else:
83
+ prompt_ratio = random.uniform(*self.prompt_ratio_range)
84
+ drop_text = False
85
+ use_language = random.uniform(0, 1) < self.language_ratio
86
+ use_instruct = random.uniform(0, 1) < self.instruct_ratio
87
+ if use_instruct and random.uniform(0, 1) < self.only_instruct_ratio:
88
+ prompt_ratio = 0.0
89
+
90
+ mask_ratio = random.uniform(*self.mask_ratio_range)
91
+
92
+ # --- Style ---
93
+ style = ""
94
+ if use_language:
95
+ language = sample["label"].get("language_id", "None")
96
+ else:
97
+ language = "None"
98
+ if use_instruct:
99
+ instruct = sample["label"].get("instruct", "None")
100
+ else:
101
+ instruct = "None"
102
+
103
+ if "clean_start_token_idx" in sample["label"]:
104
+ style += "<|denoise|>"
105
+
106
+ style += f"<|lang_start|>{language}<|lang_end|>"
107
+ style += f"<|instruct_start|>{instruct}<|instruct_end|>"
108
+
109
+ style_inputs = self.text_tokenizer(style, return_tensors="pt").input_ids.repeat(
110
+ self.num_channels, 1
111
+ )
112
+ style_labels = torch.full(
113
+ style_inputs.shape, -100
114
+ ) # Style prompt does not compute loss
115
+
116
+ # --- Text ---
117
+ if (
118
+ "text_pinyin" in sample["label"]
119
+ and random.uniform(0, 1) < self.use_pinyin_ratio
120
+ ):
121
+ text = sample["label"]["text_pinyin"]
122
+ else:
123
+ text = sample["label"]["text"]
124
+ text_inputs = self.text_tokenizer(
125
+ f"<|text_start|>{text}<|text_end|>", return_tensors="pt"
126
+ ).input_ids.repeat(self.num_channels, 1)
127
+ text_labels = torch.full(text_inputs.shape, -100) # Text does not compute loss
128
+
129
+ # --- Audio ---
130
+ audio_tokens = sample["audio_tokens"].long()
131
+
132
+ # Masking Logic
133
+ if "clean_start_token_idx" in sample["label"]:
134
+ prompt_length = sample["label"]["clean_start_token_idx"]
135
+ else:
136
+ prompt_length = int(audio_tokens.shape[1] * prompt_ratio)
137
+
138
+ audio_inputs = audio_tokens.clone()
139
+ audio_labels = audio_tokens.clone()
140
+
141
+ # Apply masking
142
+ maskable_region = audio_tokens[:, prompt_length:]
143
+ token_mask = torch.rand(maskable_region.shape) < mask_ratio
144
+ audio_inputs[:, prompt_length:][token_mask] = self.audio_mask_id
145
+ audio_labels[:, prompt_length:][
146
+ ~token_mask
147
+ ] = -100 # Only compute loss on masked tokens
148
+ if not drop_cond:
149
+ audio_labels[:, :prompt_length] = -100 # No loss on prompt region
150
+
151
+ # --- Concatenation ---
152
+ if drop_text:
153
+ input_ids = audio_inputs
154
+ labels = audio_labels
155
+ total_length = input_ids.shape[1]
156
+ audio_mask = torch.ones(total_length, dtype=torch.bool)
157
+ else:
158
+ input_ids = torch.cat([style_inputs, text_inputs, audio_inputs], dim=1)
159
+ labels = torch.cat([style_labels, text_labels, audio_labels], dim=1)
160
+ total_length = input_ids.shape[1]
161
+ audio_start_idx = style_inputs.shape[1] + text_inputs.shape[1]
162
+ audio_mask = torch.zeros(total_length, dtype=torch.bool)
163
+ audio_mask[audio_start_idx:] = True
164
+
165
+ return_dict = {
166
+ "input_ids": input_ids, # [C, L]
167
+ "labels": labels, # [C, L]
168
+ "audio_mask": audio_mask, # [L]
169
+ "length": total_length,
170
+ }
171
+
172
+ return return_dict
173
+
174
+
175
+ class OmniVoiceSimpleSampleProcessor:
176
+ """
177
+ Handles the logic of processing a raw sample into tensors
178
+ (masking, tokenization, etc.).
179
+ This is a simpler version that does not include language, instructions,
180
+ or denoising prompts.
181
+ We do not use it for training as OmniVoiceSampleProcessor can cover this case.
182
+ We keep it as a reference implementation for users to understand the basic logics.
183
+ """
184
+
185
+ def __init__(
186
+ self,
187
+ text_tokenizer: Any,
188
+ num_channels: int,
189
+ audio_mask_id: int,
190
+ prompt_ratio_range: tuple,
191
+ mask_ratio_range: tuple,
192
+ drop_cond_ratio: float,
193
+ ):
194
+ self.text_tokenizer = text_tokenizer
195
+ self.num_channels = num_channels
196
+ self.audio_mask_id = audio_mask_id
197
+ self.prompt_ratio_range = prompt_ratio_range
198
+ self.mask_ratio_range = mask_ratio_range
199
+ self.drop_cond_ratio = drop_cond_ratio
200
+
201
+ def __call__(self, sample: Dict[str, Any]) -> Dict[str, Any]:
202
+ drop_cond = random.uniform(0, 1) < self.drop_cond_ratio
203
+ mask_ratio = random.uniform(*self.mask_ratio_range)
204
+
205
+ if drop_cond:
206
+ prompt_ratio = 0.0
207
+ else:
208
+ prompt_ratio = random.uniform(*self.prompt_ratio_range)
209
+
210
+ # --- Text ---
211
+ text = sample["label"]["text"]
212
+ text_inputs = self.text_tokenizer(
213
+ f"<|text_start|>{text}<|text_end|>", return_tensors="pt"
214
+ ).input_ids.repeat(self.num_channels, 1)
215
+ text_labels = torch.full(text_inputs.shape, -100) # Text does not compute loss
216
+
217
+ # --- Audio ---
218
+ audio_tokens = sample["audio_tokens"].long()
219
+
220
+ # Masking Logic
221
+ prompt_length = int(audio_tokens.shape[1] * prompt_ratio)
222
+ audio_inputs = audio_tokens.clone()
223
+ audio_labels = audio_tokens.clone()
224
+
225
+ # Apply masking
226
+ maskable_region = audio_tokens[:, prompt_length:]
227
+ token_mask = torch.rand(maskable_region.shape) < mask_ratio
228
+ audio_inputs[:, prompt_length:][token_mask] = self.audio_mask_id
229
+ audio_labels[:, prompt_length:][
230
+ ~token_mask
231
+ ] = -100 # Only compute loss on masked tokens
232
+
233
+ if not drop_cond:
234
+ # No loss on prompt region
235
+ audio_labels[:, :prompt_length] = -100
236
+
237
+ # --- Concatenation ---
238
+ if drop_cond:
239
+ input_ids = audio_inputs
240
+ labels = audio_labels
241
+ total_length = input_ids.shape[1]
242
+ audio_mask = torch.ones(total_length, dtype=torch.bool)
243
+ else:
244
+ input_ids = torch.cat([text_inputs, audio_inputs], dim=1)
245
+ labels = torch.cat([text_labels, audio_labels], dim=1)
246
+ total_length = input_ids.shape[1]
247
+ audio_start_idx = text_inputs.shape[1]
248
+ audio_mask = torch.zeros(total_length, dtype=torch.bool)
249
+ audio_mask[audio_start_idx:] = True
250
+
251
+ return_dict = {
252
+ "input_ids": input_ids, # [C, L]
253
+ "labels": labels, # [C, L]
254
+ "audio_mask": audio_mask, # [L]
255
+ "length": total_length,
256
+ }
257
+
258
+ return return_dict
omnivoice/eval/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ import warnings
2
+
3
+ # Suppress specific warnings from zhconv that are not relevant to WER calculation
4
+ warnings.filterwarnings("ignore", category=UserWarning)
omnivoice/eval/models/ecapa_tdnn_wavlm.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ import os
19
+
20
+ import torch
21
+ import torch.nn as nn
22
+ import torch.nn.functional as F
23
+
24
+
25
+ class ECAPA_TDNN_WAVLM(nn.Module):
26
+ def __init__(
27
+ self,
28
+ feat_dim=80,
29
+ channels=512,
30
+ emb_dim=192,
31
+ global_context_att=False,
32
+ sr=16000,
33
+ ssl_model_path=None,
34
+ ):
35
+ super().__init__()
36
+ self.sr = sr
37
+
38
+ if ssl_model_path is None:
39
+ self.feature_extract = torch.hub.load("s3prl/s3prl", "wavlm_large")
40
+ else:
41
+ self.feature_extract = torch.hub.load(
42
+ os.path.dirname(ssl_model_path),
43
+ "wavlm_local",
44
+ source="local",
45
+ ckpt=os.path.join(ssl_model_path, "wavlm_large.pt"),
46
+ )
47
+
48
+ if len(self.feature_extract.model.encoder.layers) == 24 and hasattr(
49
+ self.feature_extract.model.encoder.layers[23].self_attn,
50
+ "fp32_attention",
51
+ ):
52
+ self.feature_extract.model.encoder.layers[
53
+ 23
54
+ ].self_attn.fp32_attention = False
55
+ if len(self.feature_extract.model.encoder.layers) == 24 and hasattr(
56
+ self.feature_extract.model.encoder.layers[11].self_attn,
57
+ "fp32_attention",
58
+ ):
59
+ self.feature_extract.model.encoder.layers[
60
+ 11
61
+ ].self_attn.fp32_attention = False
62
+
63
+ self.feat_num = self.get_feat_num()
64
+ self.feature_weight = nn.Parameter(torch.zeros(self.feat_num))
65
+
66
+ self.instance_norm = nn.InstanceNorm1d(feat_dim)
67
+ # self.channels = [channels] * 4 + [channels * 3]
68
+ self.channels = [channels] * 4 + [1536]
69
+
70
+ self.layer1 = Conv1dReluBn(feat_dim, self.channels[0], kernel_size=5, padding=2)
71
+ self.layer2 = SE_Res2Block(
72
+ self.channels[0],
73
+ self.channels[1],
74
+ kernel_size=3,
75
+ stride=1,
76
+ padding=2,
77
+ dilation=2,
78
+ scale=8,
79
+ se_bottleneck_dim=128,
80
+ )
81
+ self.layer3 = SE_Res2Block(
82
+ self.channels[1],
83
+ self.channels[2],
84
+ kernel_size=3,
85
+ stride=1,
86
+ padding=3,
87
+ dilation=3,
88
+ scale=8,
89
+ se_bottleneck_dim=128,
90
+ )
91
+ self.layer4 = SE_Res2Block(
92
+ self.channels[2],
93
+ self.channels[3],
94
+ kernel_size=3,
95
+ stride=1,
96
+ padding=4,
97
+ dilation=4,
98
+ scale=8,
99
+ se_bottleneck_dim=128,
100
+ )
101
+
102
+ # self.conv = nn.Conv1d(self.channels[-1], self.channels[-1], kernel_size=1)
103
+ cat_channels = channels * 3
104
+ self.conv = nn.Conv1d(cat_channels, self.channels[-1], kernel_size=1)
105
+ self.pooling = AttentiveStatsPool(
106
+ self.channels[-1],
107
+ attention_channels=128,
108
+ global_context_att=global_context_att,
109
+ )
110
+ self.bn = nn.BatchNorm1d(self.channels[-1] * 2)
111
+ self.linear = nn.Linear(self.channels[-1] * 2, emb_dim)
112
+
113
+ def get_feat_num(self):
114
+ self.feature_extract.eval()
115
+ wav = [torch.randn(self.sr).to(next(self.feature_extract.parameters()).device)]
116
+ with torch.no_grad():
117
+ features = self.feature_extract(wav)
118
+ select_feature = features["hidden_states"]
119
+ if isinstance(select_feature, (list, tuple)):
120
+ return len(select_feature)
121
+ else:
122
+ return 1
123
+
124
+ def get_feat(self, x):
125
+ with torch.no_grad():
126
+ x = self.feature_extract([sample for sample in x])
127
+
128
+ x = x["hidden_states"]
129
+ if isinstance(x, (list, tuple)):
130
+ x = torch.stack(x, dim=0)
131
+ else:
132
+ x = x.unsqueeze(0)
133
+ norm_weights = (
134
+ F.softmax(self.feature_weight, dim=-1)
135
+ .unsqueeze(-1)
136
+ .unsqueeze(-1)
137
+ .unsqueeze(-1)
138
+ )
139
+ x = (norm_weights * x).sum(dim=0)
140
+ x = torch.transpose(x, 1, 2) + 1e-6
141
+
142
+ x = self.instance_norm(x)
143
+ return x
144
+
145
+ def forward(self, x):
146
+ x = self.get_feat(x)
147
+
148
+ out1 = self.layer1(x)
149
+ out2 = self.layer2(out1)
150
+ out3 = self.layer3(out2)
151
+ out4 = self.layer4(out3)
152
+
153
+ out = torch.cat([out2, out3, out4], dim=1)
154
+ out = F.relu(self.conv(out))
155
+ out = self.bn(self.pooling(out))
156
+ out = self.linear(out)
157
+
158
+ return out
159
+
160
+
161
+ # part of the code is borrowed from https://github.com/lawlict/ECAPA-TDNN
162
+
163
+ """ Res2Conv1d + BatchNorm1d + ReLU
164
+ """
165
+
166
+
167
+ class Res2Conv1dReluBn(nn.Module):
168
+ """
169
+ in_channels == out_channels == channels
170
+ """
171
+
172
+ def __init__(
173
+ self,
174
+ channels,
175
+ kernel_size=1,
176
+ stride=1,
177
+ padding=0,
178
+ dilation=1,
179
+ bias=True,
180
+ scale=4,
181
+ ):
182
+ super().__init__()
183
+ assert channels % scale == 0, "{} % {} != 0".format(channels, scale)
184
+ self.scale = scale
185
+ self.width = channels // scale
186
+ self.nums = scale if scale == 1 else scale - 1
187
+
188
+ self.convs = []
189
+ self.bns = []
190
+ for i in range(self.nums):
191
+ self.convs.append(
192
+ nn.Conv1d(
193
+ self.width,
194
+ self.width,
195
+ kernel_size,
196
+ stride,
197
+ padding,
198
+ dilation,
199
+ bias=bias,
200
+ )
201
+ )
202
+ self.bns.append(nn.BatchNorm1d(self.width))
203
+ self.convs = nn.ModuleList(self.convs)
204
+ self.bns = nn.ModuleList(self.bns)
205
+
206
+ def forward(self, x):
207
+ out = []
208
+ spx = torch.split(x, self.width, 1)
209
+ for i in range(self.nums):
210
+ if i == 0:
211
+ sp = spx[i]
212
+ else:
213
+ sp = sp + spx[i]
214
+ # Order: conv -> relu -> bn
215
+ sp = self.convs[i](sp)
216
+ sp = self.bns[i](F.relu(sp))
217
+ out.append(sp)
218
+ if self.scale != 1:
219
+ out.append(spx[self.nums])
220
+ out = torch.cat(out, dim=1)
221
+
222
+ return out
223
+
224
+
225
+ """ Conv1d + BatchNorm1d + ReLU
226
+ """
227
+
228
+
229
+ class Conv1dReluBn(nn.Module):
230
+ def __init__(
231
+ self,
232
+ in_channels,
233
+ out_channels,
234
+ kernel_size=1,
235
+ stride=1,
236
+ padding=0,
237
+ dilation=1,
238
+ bias=True,
239
+ ):
240
+ super().__init__()
241
+ self.conv = nn.Conv1d(
242
+ in_channels,
243
+ out_channels,
244
+ kernel_size,
245
+ stride,
246
+ padding,
247
+ dilation,
248
+ bias=bias,
249
+ )
250
+ self.bn = nn.BatchNorm1d(out_channels)
251
+
252
+ def forward(self, x):
253
+ return self.bn(F.relu(self.conv(x)))
254
+
255
+
256
+ """ The SE connection of 1D case.
257
+ """
258
+
259
+
260
+ class SE_Connect(nn.Module):
261
+ def __init__(self, channels, se_bottleneck_dim=128):
262
+ super().__init__()
263
+ self.linear1 = nn.Linear(channels, se_bottleneck_dim)
264
+ self.linear2 = nn.Linear(se_bottleneck_dim, channels)
265
+
266
+ def forward(self, x):
267
+ out = x.mean(dim=2)
268
+ out = F.relu(self.linear1(out))
269
+ out = torch.sigmoid(self.linear2(out))
270
+ out = x * out.unsqueeze(2)
271
+
272
+ return out
273
+
274
+
275
+ """ SE-Res2Block of the ECAPA-TDNN architecture.
276
+ """
277
+
278
+
279
+ # def SE_Res2Block(channels, kernel_size, stride, padding, dilation, scale):
280
+ # return nn.Sequential(
281
+ # Conv1dReluBn(channels, 512, kernel_size=1, stride=1, padding=0),
282
+ # Res2Conv1dReluBn(512, kernel_size, stride, padding, dilation, scale=scale),
283
+ # Conv1dReluBn(512, channels, kernel_size=1, stride=1, padding=0),
284
+ # SE_Connect(channels)
285
+ # )
286
+
287
+
288
+ class SE_Res2Block(nn.Module):
289
+ def __init__(
290
+ self,
291
+ in_channels,
292
+ out_channels,
293
+ kernel_size,
294
+ stride,
295
+ padding,
296
+ dilation,
297
+ scale,
298
+ se_bottleneck_dim,
299
+ ):
300
+ super().__init__()
301
+ self.Conv1dReluBn1 = Conv1dReluBn(
302
+ in_channels, out_channels, kernel_size=1, stride=1, padding=0
303
+ )
304
+ self.Res2Conv1dReluBn = Res2Conv1dReluBn(
305
+ out_channels, kernel_size, stride, padding, dilation, scale=scale
306
+ )
307
+ self.Conv1dReluBn2 = Conv1dReluBn(
308
+ out_channels, out_channels, kernel_size=1, stride=1, padding=0
309
+ )
310
+ self.SE_Connect = SE_Connect(out_channels, se_bottleneck_dim)
311
+
312
+ self.shortcut = None
313
+ if in_channels != out_channels:
314
+ self.shortcut = nn.Conv1d(
315
+ in_channels=in_channels,
316
+ out_channels=out_channels,
317
+ kernel_size=1,
318
+ )
319
+
320
+ def forward(self, x):
321
+ residual = x
322
+ if self.shortcut:
323
+ residual = self.shortcut(x)
324
+
325
+ x = self.Conv1dReluBn1(x)
326
+ x = self.Res2Conv1dReluBn(x)
327
+ x = self.Conv1dReluBn2(x)
328
+ x = self.SE_Connect(x)
329
+
330
+ return x + residual
331
+
332
+
333
+ """ Attentive weighted mean and standard deviation pooling.
334
+ """
335
+
336
+
337
+ class AttentiveStatsPool(nn.Module):
338
+ def __init__(self, in_dim, attention_channels=128, global_context_att=False):
339
+ super().__init__()
340
+ self.global_context_att = global_context_att
341
+
342
+ # Use Conv1d with stride == 1 rather than Linear,
343
+ # then we don't need to transpose inputs.
344
+ if global_context_att:
345
+ self.linear1 = nn.Conv1d(
346
+ in_dim * 3, attention_channels, kernel_size=1
347
+ ) # equals W and b in the paper
348
+ else:
349
+ self.linear1 = nn.Conv1d(
350
+ in_dim, attention_channels, kernel_size=1
351
+ ) # equals W and b in the paper
352
+ self.linear2 = nn.Conv1d(
353
+ attention_channels, in_dim, kernel_size=1
354
+ ) # equals V and k in the paper
355
+
356
+ def forward(self, x):
357
+
358
+ if self.global_context_att:
359
+ context_mean = torch.mean(x, dim=-1, keepdim=True).expand_as(x)
360
+ context_std = torch.sqrt(
361
+ torch.var(x, dim=-1, keepdim=True) + 1e-10
362
+ ).expand_as(x)
363
+ x_in = torch.cat((x, context_mean, context_std), dim=1)
364
+ else:
365
+ x_in = x
366
+
367
+ # DON'T use ReLU here! In experiments, I find ReLU hard to converge.
368
+ alpha = torch.tanh(self.linear1(x_in))
369
+ # alpha = F.relu(self.linear1(x_in))
370
+ alpha = torch.softmax(self.linear2(alpha), dim=2)
371
+ mean = torch.sum(alpha * x, dim=2)
372
+ residuals = torch.sum(alpha * (x**2), dim=2) - mean**2
373
+ std = torch.sqrt(residuals.clamp(min=1e-9))
374
+ return torch.cat([mean, std], dim=1)
omnivoice/eval/models/utmos.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """
19
+ UTMOS strong model.
20
+ Implementation from https://github.com/tarepan/SpeechMOS
21
+
22
+ """
23
+
24
+ import math
25
+ from typing import List, Optional, Tuple
26
+
27
+ import torch
28
+ import torch.nn.functional as F
29
+ from torch import Tensor, nn
30
+
31
+
32
+ class UTMOS22Strong(nn.Module):
33
+ """Saeki_2022 paper's `UTMOS strong learner` inference model
34
+ (w/o Phoneme encoder)."""
35
+
36
+ def __init__(self):
37
+ """Init."""
38
+
39
+ super().__init__() # pyright: ignore [reportUnknownMemberType]
40
+
41
+ feat_ssl, feat_domain_emb, feat_judge_emb, feat_rnn_h, feat_proj_h = (
42
+ 768,
43
+ 128,
44
+ 128,
45
+ 512,
46
+ 2048,
47
+ )
48
+ feat_cat = feat_ssl + feat_domain_emb + feat_judge_emb
49
+
50
+ # SSL/DataDomainEmb/JudgeIdEmb/BLSTM/Projection
51
+ self.wav2vec2 = Wav2Vec2Model()
52
+ self.domain_emb = nn.Parameter(
53
+ data=torch.empty(1, feat_domain_emb), requires_grad=False
54
+ )
55
+ self.judge_emb = nn.Parameter(
56
+ data=torch.empty(1, feat_judge_emb), requires_grad=False
57
+ )
58
+ self.blstm = nn.LSTM(
59
+ input_size=feat_cat,
60
+ hidden_size=feat_rnn_h,
61
+ batch_first=True,
62
+ bidirectional=True,
63
+ )
64
+ self.projection = nn.Sequential(
65
+ nn.Linear(feat_rnn_h * 2, feat_proj_h), nn.ReLU(), nn.Linear(feat_proj_h, 1)
66
+ )
67
+
68
+ def forward(self, wave: Tensor, sr: int) -> Tensor: # pylint: disable=invalid-name
69
+ """wave-to-score :: (B, T) -> (B,)"""
70
+
71
+ # Feature extraction :: (B, T) -> (B, Frame, Feat)
72
+ unit_series = self.wav2vec2(wave)
73
+ bsz, frm, _ = unit_series.size()
74
+
75
+ # DataDomain/JudgeId Embedding's Batch/Time expansion ::
76
+ # (B=1, Feat) -> (B=bsz, Frame=frm, Feat)
77
+ domain_series = self.domain_emb.unsqueeze(1).expand(bsz, frm, -1)
78
+ judge_series = self.judge_emb.unsqueeze(1).expand(bsz, frm, -1)
79
+
80
+ # Feature concatenation :: (B, Frame, Feat=f1) + (B, Frame, Feat=f2) +
81
+ # (B, Frame, Feat=f3) -> (B, Frame, Feat=f1+f2+f3)
82
+ cat_series = torch.cat([unit_series, domain_series, judge_series], dim=2)
83
+
84
+ # Frame-scale score estimation :: (B, Frame, Feat) -> (B, Frame, Feat)
85
+ # -> (B, Frame, Feat=1) - BLSTM/Projection
86
+ feat_series = self.blstm(cat_series)[0]
87
+ score_series = self.projection(feat_series)
88
+
89
+ # Utterance-scale score :: (B, Frame, Feat=1) -> (B, Feat=1)
90
+ # -> (B,) - Time averaging
91
+ utter_score = score_series.mean(dim=1).squeeze(1) * 2 + 3
92
+
93
+ return utter_score
94
+
95
+
96
+ class Wav2Vec2Model(nn.Module):
97
+ """Wav2Vev2."""
98
+
99
+ def __init__(self):
100
+ super().__init__() # pyright: ignore [reportUnknownMemberType]
101
+
102
+ feat_h1, feat_h2 = 512, 768
103
+ feature_enc_layers = (
104
+ [(feat_h1, 10, 5)] + [(feat_h1, 3, 2)] * 4 + [(feat_h1, 2, 2)] * 2
105
+ )
106
+
107
+ self.feature_extractor = ConvFeatureExtractionModel(
108
+ conv_layers=feature_enc_layers
109
+ ) # pyright: ignore [reportGeneralTypeIssues]
110
+ self.layer_norm = nn.LayerNorm(feat_h1)
111
+ self.post_extract_proj = nn.Linear(feat_h1, feat_h2)
112
+ self.dropout_input = nn.Dropout(0.1)
113
+ self.encoder = TransformerEncoder(feat_h2)
114
+
115
+ # Remnants
116
+ self.mask_emb = nn.Parameter(torch.FloatTensor(feat_h2))
117
+
118
+ def forward(self, source: Tensor):
119
+ """FeatureEncoder + ContextTransformer"""
120
+
121
+ # Feature encoding
122
+ features = self.feature_extractor(source)
123
+ features = features.transpose(1, 2)
124
+ features = self.layer_norm(features)
125
+ features = self.post_extract_proj(features)
126
+
127
+ # Context transformer
128
+ x = self.encoder(features)
129
+
130
+ return x
131
+
132
+
133
+ class ConvFeatureExtractionModel(nn.Module):
134
+ """Feature Encoder."""
135
+
136
+ def __init__(self, conv_layers: List[Tuple[int, int, int]]):
137
+ super().__init__() # pyright: ignore [reportUnknownMemberType]
138
+
139
+ def block(
140
+ n_in: int, n_out: int, k: int, stride: int, is_group_norm: bool = False
141
+ ):
142
+ if is_group_norm:
143
+ return nn.Sequential(
144
+ nn.Conv1d(n_in, n_out, k, stride=stride, bias=False),
145
+ nn.Dropout(p=0.0),
146
+ nn.GroupNorm(dim, dim, affine=True),
147
+ nn.GELU(),
148
+ )
149
+ else:
150
+ return nn.Sequential(
151
+ nn.Conv1d(n_in, n_out, k, stride=stride, bias=False),
152
+ nn.Dropout(p=0.0),
153
+ nn.GELU(),
154
+ )
155
+
156
+ in_d = 1
157
+ self.conv_layers = nn.ModuleList()
158
+ for i, params in enumerate(conv_layers):
159
+ (dim, k, stride) = params
160
+ self.conv_layers.append(block(in_d, dim, k, stride, is_group_norm=i == 0))
161
+ in_d = dim
162
+
163
+ def forward(self, series: Tensor) -> Tensor:
164
+ """:: (B, T) -> (B, Feat, Frame)"""
165
+
166
+ series = series.unsqueeze(1)
167
+ for conv in self.conv_layers:
168
+ series = conv(series)
169
+
170
+ return series
171
+
172
+
173
+ class TransformerEncoder(nn.Module):
174
+ """Transformer."""
175
+
176
+ def build_encoder_layer(self, feat: int):
177
+ """Layer builder."""
178
+ return TransformerSentenceEncoderLayer(
179
+ embedding_dim=feat,
180
+ ffn_embedding_dim=3072,
181
+ num_attention_heads=12,
182
+ activation_fn="gelu",
183
+ dropout=0.1,
184
+ attention_dropout=0.1,
185
+ activation_dropout=0.0,
186
+ layer_norm_first=False,
187
+ )
188
+
189
+ def __init__(self, feat: int):
190
+ super().__init__() # pyright: ignore [reportUnknownMemberType]
191
+
192
+ self.required_seq_len_multiple = 2
193
+
194
+ self.pos_conv = nn.Sequential(
195
+ *[
196
+ nn.utils.weight_norm(
197
+ nn.Conv1d(feat, feat, kernel_size=128, padding=128 // 2, groups=16),
198
+ name="weight",
199
+ dim=2,
200
+ ),
201
+ SamePad(128),
202
+ nn.GELU(),
203
+ ]
204
+ )
205
+ self.layer_norm = nn.LayerNorm(feat)
206
+ self.layers = nn.ModuleList([self.build_encoder_layer(feat) for _ in range(12)])
207
+
208
+ def forward(self, x: Tensor) -> Tensor:
209
+
210
+ x_conv = self.pos_conv(x.transpose(1, 2)).transpose(1, 2)
211
+ x = x + x_conv
212
+
213
+ x = self.layer_norm(x)
214
+
215
+ # pad to the sequence length dimension
216
+ x, pad_length = pad_to_multiple(
217
+ x, self.required_seq_len_multiple, dim=-2, value=0
218
+ )
219
+ if pad_length > 0:
220
+ padding_mask = x.new_zeros((x.size(0), x.size(1)), dtype=torch.bool)
221
+ padding_mask[:, -pad_length:] = True
222
+ else:
223
+ padding_mask, _ = pad_to_multiple(
224
+ None, self.required_seq_len_multiple, dim=-1, value=True
225
+ )
226
+
227
+ # :: (B, T, Feat) -> (T, B, Feat)
228
+ x = x.transpose(0, 1)
229
+ for layer in self.layers:
230
+ x = layer(x, padding_mask)
231
+ # :: (T, B, Feat) -> (B, T, Feat)
232
+ x = x.transpose(0, 1)
233
+
234
+ # undo paddding
235
+ if pad_length > 0:
236
+ x = x[:, :-pad_length]
237
+
238
+ return x
239
+
240
+
241
+ class SamePad(nn.Module):
242
+ """Tail inverse padding."""
243
+
244
+ def __init__(self, kernel_size: int):
245
+ super().__init__() # pyright: ignore [reportUnknownMemberType]
246
+ assert kernel_size % 2 == 0, "`SamePad` now support only even kernel."
247
+
248
+ def forward(self, x: Tensor) -> Tensor:
249
+ return x[:, :, :-1]
250
+
251
+
252
+ def pad_to_multiple(
253
+ x: Optional[Tensor], multiple: int, dim: int = -1, value: float = 0
254
+ ) -> Tuple[Optional[Tensor], int]:
255
+ """Tail padding."""
256
+ if x is None:
257
+ return None, 0
258
+ tsz = x.size(dim)
259
+ m = tsz / multiple
260
+ remainder = math.ceil(m) * multiple - tsz
261
+ if m.is_integer():
262
+ return x, 0
263
+ pad_offset = (0,) * (-1 - dim) * 2
264
+
265
+ return F.pad(x, (*pad_offset, 0, remainder), value=value), remainder
266
+
267
+
268
+ class TransformerSentenceEncoderLayer(nn.Module):
269
+ """Transformer Encoder Layer used in BERT/XLM style pre-trained models."""
270
+
271
+ def __init__(
272
+ self,
273
+ embedding_dim: int,
274
+ ffn_embedding_dim: int,
275
+ num_attention_heads: int,
276
+ activation_fn: str,
277
+ dropout: float,
278
+ attention_dropout: float,
279
+ activation_dropout: float,
280
+ layer_norm_first: bool,
281
+ ) -> None:
282
+ super().__init__() # pyright: ignore [reportUnknownMemberType]
283
+
284
+ assert layer_norm_first is False, "`layer_norm_first` is fixed to `False`"
285
+ assert activation_fn == "gelu", "`activation_fn` is fixed to `gelu`"
286
+
287
+ feat = embedding_dim
288
+
289
+ self.self_attn = MultiheadAttention(
290
+ feat, num_attention_heads, attention_dropout
291
+ )
292
+ self.dropout1 = nn.Dropout(dropout)
293
+ self.dropout2 = nn.Dropout(activation_dropout)
294
+ self.dropout3 = nn.Dropout(dropout)
295
+ self.fc1 = nn.Linear(feat, ffn_embedding_dim)
296
+ self.fc2 = nn.Linear(ffn_embedding_dim, feat)
297
+ self.self_attn_layer_norm = nn.LayerNorm(feat)
298
+ self.final_layer_norm = nn.LayerNorm(feat)
299
+
300
+ def forward(self, x: Tensor, self_attn_padding_mask: Optional[Tensor]):
301
+ # Res[Attn-Do]-LN
302
+ residual = x
303
+ x = self.self_attn(x, x, x, self_attn_padding_mask)
304
+ x = self.dropout1(x)
305
+ x = residual + x
306
+ x = self.self_attn_layer_norm(x)
307
+
308
+ # Res[SegFC-GELU-Do-SegFC-Do]-LN
309
+ residual = x
310
+ x = F.gelu(self.fc1(x)) # pyright: ignore [reportUnknownMemberType]
311
+ x = self.dropout2(x)
312
+ x = self.fc2(x)
313
+ x = self.dropout3(x)
314
+ x = residual + x
315
+ x = self.final_layer_norm(x)
316
+
317
+ return x
318
+
319
+
320
+ class MultiheadAttention(nn.Module):
321
+ """Multi-headed attention."""
322
+
323
+ def __init__(self, embed_dim: int, num_heads: int, dropout: float):
324
+ super().__init__() # pyright: ignore [reportUnknownMemberType]
325
+
326
+ self.embed_dim, self.num_heads, self.p_dropout = embed_dim, num_heads, dropout
327
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=True)
328
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=True)
329
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=True)
330
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=True)
331
+
332
+ def forward(
333
+ self,
334
+ query: Tensor,
335
+ key: Tensor,
336
+ value: Tensor,
337
+ key_padding_mask: Optional[Tensor],
338
+ ) -> Tensor:
339
+ """
340
+ Args:
341
+ query :: (T, B, Feat)
342
+ key_padding_mask :: (B, src_len) - mask to exclude keys that are pads
343
+ , where padding elements are indicated by 1s.
344
+ """
345
+ return F.multi_head_attention_forward(
346
+ query=query,
347
+ key=key,
348
+ value=value,
349
+ embed_dim_to_check=self.embed_dim,
350
+ num_heads=self.num_heads,
351
+ in_proj_weight=torch.empty([0]),
352
+ in_proj_bias=torch.cat(
353
+ (self.q_proj.bias, self.k_proj.bias, self.v_proj.bias)
354
+ ),
355
+ bias_k=None,
356
+ bias_v=None,
357
+ add_zero_attn=False,
358
+ dropout_p=self.p_dropout,
359
+ out_proj_weight=self.out_proj.weight,
360
+ out_proj_bias=self.out_proj.bias,
361
+ training=False,
362
+ key_padding_mask=key_padding_mask.bool()
363
+ if key_padding_mask is not None
364
+ else None,
365
+ need_weights=False,
366
+ use_separate_proj_weight=True,
367
+ q_proj_weight=self.q_proj.weight,
368
+ k_proj_weight=self.k_proj.weight,
369
+ v_proj_weight=self.v_proj.weight,
370
+ )[0]
omnivoice/eval/mos/utmos.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """
19
+ Calculate UTMOS score with automatic Mean Opinion Score (MOS) prediction system
20
+ """
21
+ import argparse
22
+ import logging
23
+ import multiprocessing as mp
24
+ import os
25
+ import sys
26
+ import traceback
27
+ import warnings
28
+ from concurrent.futures import ProcessPoolExecutor, as_completed
29
+
30
+ import numpy as np
31
+ import torch
32
+ from tqdm import tqdm
33
+
34
+ from omnivoice.eval.models.utmos import UTMOS22Strong
35
+ from omnivoice.eval.utils import load_eval_waveform
36
+ from omnivoice.utils.data_utils import read_test_list
37
+
38
+ warnings.filterwarnings("ignore")
39
+
40
+ # Global variables for workers
41
+ worker_model = None
42
+ worker_device = None
43
+ worker_sr = 16000
44
+
45
+
46
+ def get_parser() -> argparse.ArgumentParser:
47
+ parser = argparse.ArgumentParser(
48
+ description="Calculate UTMOS score using UTMOS22Strong model."
49
+ )
50
+ parser.add_argument(
51
+ "--wav-path",
52
+ type=str,
53
+ required=True,
54
+ help="Path to the directory containing evaluated speech files.",
55
+ )
56
+ parser.add_argument(
57
+ "--test-list",
58
+ type=str,
59
+ required=True,
60
+ help="Path to the JSONL test list. Each line is a JSON object "
61
+ "with fields: id, text, ref_audio, ref_text, language_id, language_name.",
62
+ )
63
+ parser.add_argument(
64
+ "--model-dir",
65
+ type=str,
66
+ required=True,
67
+ help="Local path of our evaluation model repository."
68
+ "Download from https://huggingface.co/k2-fsa/TTS_eval_models."
69
+ "Will use 'tts_eval_models/mos/utmos22_strong_step7459_v1.pt'"
70
+ " in this script",
71
+ )
72
+ parser.add_argument(
73
+ "--extension",
74
+ type=str,
75
+ default="wav",
76
+ help="Extension of the speech files. Default: wav",
77
+ )
78
+ parser.add_argument(
79
+ "--decode-path",
80
+ type=str,
81
+ default=None,
82
+ help="Path to the output file where UTMOS information will be saved. "
83
+ "If not provided, results are only printed to console.",
84
+ )
85
+ parser.add_argument(
86
+ "--nj-per-gpu",
87
+ type=int,
88
+ default=1,
89
+ help="Number of worker processes to spawn per GPU.",
90
+ )
91
+ return parser
92
+
93
+
94
+ def get_device(rank: int = 0) -> torch.device:
95
+ assert torch.cuda.is_available(), "CUDA is required but not available."
96
+ device = torch.device(f"cuda:{rank}")
97
+ torch.cuda.set_device(rank)
98
+ return device
99
+
100
+
101
+ def worker_init(
102
+ rank_queue,
103
+ model_path,
104
+ ):
105
+ """Initialize worker process with model and device."""
106
+ global worker_model, worker_device, worker_sr
107
+
108
+ # Limit CPU threads per worker
109
+ torch.set_num_threads(2)
110
+
111
+ formatter = "%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] [Worker %(process)d] %(message)s"
112
+ logging.basicConfig(format=formatter, level=logging.INFO, force=True)
113
+
114
+ rank = rank_queue.get() if rank_queue else -1
115
+
116
+ worker_device = get_device(rank)
117
+ worker_sr = 16000
118
+
119
+ logging.debug(f"Initializing UTMOS worker on {worker_device}")
120
+
121
+ # Initialize Model
122
+ worker_model = UTMOS22Strong()
123
+ try:
124
+ # Load weights to CPU first, then move to device
125
+ state_dict = torch.load(model_path, map_location="cpu")
126
+ worker_model.load_state_dict(state_dict)
127
+ except Exception as e:
128
+ logging.error(f"Failed to load model from {model_path}: {e}")
129
+ raise
130
+
131
+ worker_model.to(worker_device)
132
+ worker_model.eval()
133
+
134
+
135
+ @torch.no_grad()
136
+ def run_utmos_worker(file_idx, wav_path, language_name):
137
+ """Worker function to process a single audio file."""
138
+ try:
139
+ if not os.path.exists(wav_path):
140
+ return file_idx, wav_path, language_name, f"File not found: {wav_path}", "error"
141
+
142
+ # Load and preprocess waveform
143
+ speech = load_eval_waveform(wav_path, worker_sr, device=worker_device)
144
+
145
+ # Compute score
146
+ # UTMOS expects input shape (Batch, Time)
147
+ score = worker_model(speech.unsqueeze(0), worker_sr)
148
+
149
+ return file_idx, wav_path, language_name, score.item(), "success"
150
+
151
+ except Exception as e:
152
+ error_detail = (
153
+ f"Error processing {wav_path}: {str(e)}\n"
154
+ f"Traceback:\n{traceback.format_exc()}"
155
+ )
156
+ return file_idx, wav_path, language_name, error_detail, "error"
157
+
158
+
159
+ def main():
160
+ parser = get_parser()
161
+ args = parser.parse_args()
162
+
163
+ # Main process thread setting
164
+ torch.set_num_threads(2)
165
+
166
+ mp.set_start_method("spawn", force=True)
167
+
168
+ formatter = "%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s"
169
+ logging.basicConfig(format=formatter, level=logging.INFO, force=True)
170
+
171
+ # Validate inputs
172
+ if not os.path.isdir(args.wav_path):
173
+ logging.error(f"Invalid directory: {args.wav_path}")
174
+ sys.exit(1)
175
+
176
+ model_path = os.path.join(args.model_dir, "mos/utmos22_strong_step7459_v1.pt")
177
+ if not os.path.exists(model_path):
178
+ logging.error(f"Model file not found at {model_path}")
179
+ sys.exit(1)
180
+
181
+ # Scan directory for files
182
+ logging.info(f"Calculating UTMOS for {args.wav_path}")
183
+
184
+ wav_files = []
185
+ try:
186
+ samples = read_test_list(args.test_list)
187
+ for s in samples:
188
+ language_name = s.get("language_name") or "unknown"
189
+ eval_wav_path = os.path.join(args.wav_path, f"{s['id']}.{args.extension}")
190
+ wav_files.append((eval_wav_path, language_name))
191
+ except Exception as e:
192
+ raise ValueError(f"Error reading test list {args.test_list}: {e}")
193
+
194
+ # Setup Parallel Processing
195
+ num_gpus = torch.cuda.device_count()
196
+ assert num_gpus > 0, "No GPU found. GPU is required."
197
+ total_procs = num_gpus * args.nj_per_gpu
198
+
199
+ logging.info(
200
+ f"Starting evaluation with {total_procs} processes on {num_gpus} GPUs."
201
+ )
202
+
203
+ manager = mp.Manager()
204
+ rank_queue = manager.Queue()
205
+
206
+ for rank in list(range(num_gpus)) * args.nj_per_gpu:
207
+ rank_queue.put(rank)
208
+
209
+ scores = []
210
+
211
+ fout = None
212
+ if args.decode_path:
213
+ os.makedirs(os.path.dirname(args.decode_path), exist_ok=True)
214
+ fout = open(args.decode_path, "w", encoding="utf8")
215
+ logging.info(f"Saving detailed UTMOS results to: {args.decode_path}")
216
+ fout.write("Name\tUTMOS\n")
217
+
218
+ try:
219
+ with ProcessPoolExecutor(
220
+ max_workers=total_procs,
221
+ initializer=worker_init,
222
+ initargs=(
223
+ rank_queue,
224
+ model_path,
225
+ ),
226
+ ) as executor:
227
+ futures = []
228
+ for i, (wav_path, language_name) in enumerate(wav_files):
229
+ futures.append(
230
+ executor.submit(run_utmos_worker, i, wav_path, language_name)
231
+ )
232
+
233
+ pbar = tqdm(
234
+ as_completed(futures), total=len(wav_files), desc="Evaluating UTMOS"
235
+ )
236
+ lang_stats = {}
237
+ for future in pbar:
238
+ idx, path, language_name, result, status = future.result()
239
+ if status == "success":
240
+ if language_name not in lang_stats:
241
+ lang_stats[language_name] = []
242
+ lang_stats[language_name].append(result)
243
+ scores.append(result)
244
+ if fout:
245
+ if language_name == "unknown":
246
+ fout.write(f"{os.path.basename(path)}\t{result:.2f}\n")
247
+ else:
248
+ fout.write(
249
+ f"{language_name}\t{os.path.basename(path)}\t{result:.2f}\n"
250
+ )
251
+ else:
252
+ pbar.write(f"!!! FAILED [File {idx}]: {path} | {result}")
253
+
254
+ except (Exception, KeyboardInterrupt) as e:
255
+ logging.critical(
256
+ f"An unrecoverable error occurred: {e}. Terminating all processes."
257
+ )
258
+ detailed_error_info = traceback.format_exc()
259
+ logging.error(f"--- DETAILED TRACEBACK ---\n{detailed_error_info}")
260
+ sys.exit(1)
261
+
262
+ print("-" * 50)
263
+
264
+ if len(lang_stats) > 1:
265
+ lang_scores = []
266
+ for lang in sorted(lang_stats.keys()):
267
+ l_scores = lang_stats[lang]
268
+ l_avg = np.mean(l_scores)
269
+ lang_scores.append(l_scores)
270
+ l_count = len(l_scores)
271
+ logging.info(f"[{lang}] UTMOS score: {l_avg:.3f} ({l_count} samples)")
272
+ if fout:
273
+ fout.write(f"[{lang}] UTMOS: {l_avg:.3f} ({l_count} samples)\n")
274
+ logging.info(
275
+ f"Macro-average UTMOS over {len(lang_stats)} languages: "
276
+ f"{np.mean([np.mean(ls) for ls in lang_scores]):.3f}"
277
+ )
278
+ if fout:
279
+ fout.write(
280
+ f"\nMacro-average UTMOS over {len(lang_stats)} languages: "
281
+ f"{np.mean([np.mean(ls) for ls in lang_scores]):.3f}\n"
282
+ )
283
+
284
+ if scores:
285
+ avg_score = np.mean(scores)
286
+ logging.info(f"Processed {len(scores)}/{len(wav_files)} files.")
287
+ logging.info(f"UTMOS score: {avg_score:.2f}")
288
+ if fout:
289
+ fout.write(f"\nAverage UTMOS: {avg_score:.2f}\n")
290
+ else:
291
+ logging.error("No valid scores computed.")
292
+ print("-" * 50)
293
+
294
+ if fout:
295
+ fout.close()
296
+
297
+
298
+ if __name__ == "__main__":
299
+ main()
omnivoice/eval/speaker_similarity/sim.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """
19
+ Computes speaker similarity (SIM-o) using a WavLM-based
20
+ ECAPA-TDNN speaker verification model.
21
+ """
22
+ import argparse
23
+ import logging
24
+ import multiprocessing as mp
25
+ import os
26
+ import sys
27
+ import traceback
28
+ import warnings
29
+ from concurrent.futures import ProcessPoolExecutor, as_completed
30
+
31
+ import numpy as np
32
+ import torch
33
+ from tqdm import tqdm
34
+
35
+ from omnivoice.eval.models.ecapa_tdnn_wavlm import ECAPA_TDNN_WAVLM
36
+ from omnivoice.eval.utils import load_eval_waveform
37
+ from omnivoice.utils.data_utils import read_test_list
38
+
39
+ warnings.filterwarnings("ignore")
40
+
41
+ # Global variables for workers
42
+ worker_model = None
43
+ worker_device = None
44
+ worker_sr = 16000
45
+
46
+
47
+ def get_parser() -> argparse.ArgumentParser:
48
+ parser = argparse.ArgumentParser(
49
+ description="Calculate speaker similarity (SIM-o) score."
50
+ )
51
+ parser.add_argument(
52
+ "--wav-path",
53
+ type=str,
54
+ required=True,
55
+ help="Path to the directory containing evaluated speech files.",
56
+ )
57
+ parser.add_argument(
58
+ "--test-list",
59
+ type=str,
60
+ required=True,
61
+ help="Path to the JSONL test list. Each line is a JSON object "
62
+ "with fields: id, text, ref_audio, ref_text, language_id, language_name.",
63
+ )
64
+ parser.add_argument(
65
+ "--model-dir",
66
+ type=str,
67
+ required=True,
68
+ help="Local path of our evaluation model repository."
69
+ "Download from https://huggingface.co/k2-fsa/TTS_eval_models."
70
+ "Will use 'tts_eval_models/speaker_similarity/wavlm_large_finetune.pth'"
71
+ "and 'tts_eval_models/speaker_similarity/wavlm_large/' in this script",
72
+ )
73
+ parser.add_argument(
74
+ "--extension",
75
+ type=str,
76
+ default="wav",
77
+ help="Extension of the speech files.",
78
+ )
79
+ parser.add_argument(
80
+ "--decode-path",
81
+ type=str,
82
+ default=None,
83
+ help="Path to the output file where SIM-o information will be saved. "
84
+ "If not provided, results are only printed to console.",
85
+ )
86
+ parser.add_argument(
87
+ "--nj-per-gpu",
88
+ type=int,
89
+ default=1,
90
+ help="Number of worker processes to spawn per GPU.",
91
+ )
92
+ return parser
93
+
94
+
95
+ def get_device(rank: int = 0) -> torch.device:
96
+ assert torch.cuda.is_available(), "CUDA is required but not available."
97
+ device = torch.device(f"cuda:{rank}")
98
+ torch.cuda.set_device(rank)
99
+ return device
100
+
101
+
102
+ def worker_init(
103
+ rank_queue,
104
+ sv_model_path,
105
+ ssl_model_path,
106
+ ):
107
+ """Initialize worker process with model and device."""
108
+ global worker_model, worker_device, worker_sr
109
+
110
+ torch.set_num_threads(2)
111
+
112
+ formatter = "%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] [Worker %(process)d] %(message)s"
113
+ logging.basicConfig(format=formatter, level=logging.INFO, force=True)
114
+
115
+ rank = rank_queue.get() if rank_queue else -1
116
+
117
+ worker_device = get_device(rank)
118
+ worker_sr = 16000
119
+
120
+ logging.debug(f"Initializing SIM-o worker on {worker_device}")
121
+ # Temporarily suppress INFO logs to hide verbose WavLM config
122
+ logging.disable(logging.INFO)
123
+
124
+ # Initialize Model
125
+ try:
126
+ worker_model = ECAPA_TDNN_WAVLM(
127
+ feat_dim=1024,
128
+ channels=512,
129
+ emb_dim=256,
130
+ sr=worker_sr,
131
+ ssl_model_path=ssl_model_path,
132
+ )
133
+ state_dict = torch.load(
134
+ sv_model_path, map_location=lambda storage, loc: storage
135
+ )
136
+ worker_model.load_state_dict(state_dict["model"], strict=False)
137
+ worker_model.to(worker_device)
138
+ worker_model.eval()
139
+ finally:
140
+ # Restore normal logging
141
+ logging.disable(logging.NOTSET)
142
+
143
+
144
+ @torch.no_grad()
145
+ def get_embedding(wav_path: str) -> torch.Tensor:
146
+ """Extract embedding for a single file."""
147
+ speech = load_eval_waveform(wav_path, worker_sr, device=worker_device, max_seconds=120)
148
+ return worker_model([speech])
149
+
150
+
151
+ def run_similarity_worker(line_idx, sample, wav_dir, extension):
152
+ """Worker function to process a single pair."""
153
+ try:
154
+ wav_name = sample["id"]
155
+ ref_wav_path = sample["ref_audio"]
156
+ language_name = sample.get("language_name") or "unknown"
157
+ eval_wav_path = os.path.join(wav_dir, f"{wav_name}.{extension}")
158
+
159
+ if not os.path.exists(ref_wav_path):
160
+ return line_idx, f"Reference not found: {ref_wav_path}", None, "error"
161
+ if not os.path.exists(eval_wav_path):
162
+ return line_idx, f"Eval wav not found: {eval_wav_path}", None, "error"
163
+
164
+ # Compute embeddings pair-wise
165
+ ref_emb = get_embedding(ref_wav_path)
166
+ eval_emb = get_embedding(eval_wav_path)
167
+
168
+ # Cosine Similarity
169
+ similarity = torch.nn.functional.cosine_similarity(ref_emb, eval_emb, dim=-1)
170
+
171
+ return (
172
+ line_idx,
173
+ (ref_wav_path, eval_wav_path, language_name),
174
+ similarity.item(),
175
+ "success",
176
+ )
177
+
178
+ except Exception as e:
179
+ error_detail = f"Error: {str(e)}\nTraceback:\n{traceback.format_exc()}"
180
+ return line_idx, str(sample), error_detail, "error"
181
+
182
+
183
+ def main():
184
+ parser = get_parser()
185
+ args = parser.parse_args()
186
+
187
+ # Main process thread setting
188
+ torch.set_num_threads(2)
189
+
190
+ mp.set_start_method("spawn", force=True)
191
+
192
+ formatter = "%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s"
193
+ logging.basicConfig(format=formatter, level=logging.INFO, force=True)
194
+
195
+ # Prepare paths
196
+ sv_model_path = os.path.join(
197
+ args.model_dir, "speaker_similarity/wavlm_large_finetune.pth"
198
+ )
199
+ ssl_model_path = os.path.join(args.model_dir, "speaker_similarity/wavlm_large/")
200
+
201
+ if not os.path.exists(sv_model_path) or not os.path.exists(ssl_model_path):
202
+ logging.error("Model files not found. Please check --model-dir.")
203
+ sys.exit(1)
204
+
205
+ logging.info(f"Calculating SIM-o for {args.wav_path}")
206
+ # Read list
207
+ samples = read_test_list(args.test_list)
208
+
209
+ # Setup Parallel Processing
210
+ num_gpus = torch.cuda.device_count()
211
+ assert num_gpus > 0, "No GPU found. GPU is required."
212
+ total_procs = num_gpus * args.nj_per_gpu
213
+
214
+ logging.info(
215
+ f"Starting evaluation with {total_procs} processes " f"on {num_gpus} GPUs."
216
+ )
217
+
218
+ manager = mp.Manager()
219
+ rank_queue = manager.Queue()
220
+
221
+ for rank in list(range(num_gpus)) * args.nj_per_gpu:
222
+ rank_queue.put(rank)
223
+
224
+ scores = []
225
+
226
+ fout = None
227
+ if args.decode_path:
228
+ os.makedirs(os.path.dirname(args.decode_path), exist_ok=True)
229
+ fout = open(args.decode_path, "w", encoding="utf8")
230
+ logging.info(f"Saving detailed SIM-o results to: {args.decode_path}")
231
+ fout.write("Prompt-path\tEval-path\tSIM-o\n")
232
+
233
+ try:
234
+ with ProcessPoolExecutor(
235
+ max_workers=total_procs,
236
+ initializer=worker_init,
237
+ initargs=(
238
+ rank_queue,
239
+ sv_model_path,
240
+ ssl_model_path,
241
+ ),
242
+ ) as executor:
243
+ futures = []
244
+ for i, sample in enumerate(samples):
245
+ futures.append(
246
+ executor.submit(
247
+ run_similarity_worker, i, sample, args.wav_path, args.extension
248
+ )
249
+ )
250
+
251
+ pbar = tqdm(
252
+ as_completed(futures), total=len(samples), desc="Evaluating SIM-o"
253
+ )
254
+
255
+ lang_stats = {}
256
+
257
+ for future in pbar:
258
+ idx, context, result, status = future.result()
259
+ if status == "success":
260
+ prompt_path, eval_path, lang = context
261
+ scores.append(result)
262
+
263
+ # Accumulate per-language
264
+ if lang not in lang_stats:
265
+ lang_stats[lang] = []
266
+ lang_stats[lang].append(result)
267
+
268
+ if fout:
269
+ if lang == "unknown":
270
+ fout.write(f"{prompt_path}\t{eval_path}\t{result:.2f}\n")
271
+ else:
272
+ fout.write(
273
+ f"{lang}\t{context[0]}\t{context[1]}\t{result:.2f}\n"
274
+ )
275
+ else:
276
+ pbar.write(f"!!! FAILED [Line {idx}]: {context} | Error: {result}")
277
+
278
+ except (Exception, KeyboardInterrupt) as e:
279
+ logging.critical(
280
+ f"An unrecoverable error occurred: {e}. " f"Terminating all processes."
281
+ )
282
+ detailed_error_info = traceback.format_exc()
283
+ logging.error(f"--- DETAILED TRACEBACK ---\n{detailed_error_info}")
284
+ sys.exit(1)
285
+
286
+ print("-" * 50)
287
+ if len(lang_stats) > 1:
288
+ lang_scores = []
289
+ for lang in sorted(lang_stats.keys()):
290
+ l_scores = lang_stats[lang]
291
+ l_avg = np.mean(l_scores)
292
+ lang_scores.append(l_scores)
293
+ l_count = len(l_scores)
294
+ logging.info(f"[{lang}] SIM-o score: {l_avg:.3f} ({l_count} pairs)")
295
+ if fout:
296
+ fout.write(f"[{lang}] SIM-o: {l_avg:.3f} ({l_count} pairs)\n")
297
+ logging.info(
298
+ f"Macro-average SIM-o over {len(lang_stats)} languages: "
299
+ f"{np.mean([np.mean(ls) for ls in lang_scores]):.3f}"
300
+ )
301
+ if fout:
302
+ fout.write(
303
+ f"\nMacro-average SIM-o over {len(lang_stats)} languages: "
304
+ f"{np.mean([np.mean(ls) for ls in lang_scores]):.3f}\n"
305
+ )
306
+
307
+ if scores:
308
+ avg_score = np.mean(scores)
309
+ logging.info(f"Processed {len(scores)}/{len(samples)} pairs.")
310
+ logging.info(f"SIM-o score: {avg_score:.3f}")
311
+ if fout:
312
+ fout.write(f"\nAverage SIM-o: {avg_score:.3f}\n")
313
+ else:
314
+ logging.error("No valid scores computed.")
315
+ if fout:
316
+ fout.close()
317
+ print("-" * 50)
318
+
319
+
320
+ if __name__ == "__main__":
321
+ main()
omnivoice/eval/utils.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ import logging
19
+ from typing import Optional
20
+
21
+ import soundfile as sf
22
+ import torch
23
+ import torchaudio
24
+
25
+
26
+ def load_eval_waveform(
27
+ fname: str,
28
+ sample_rate: int,
29
+ dtype: str = "float32",
30
+ device: torch.device = torch.device("cpu"),
31
+ return_numpy: bool = False,
32
+ max_seconds: Optional[float] = None,
33
+ ) -> torch.Tensor:
34
+ """
35
+ Load an audio file, preprocess it, and convert to a PyTorch tensor.
36
+
37
+ Args:
38
+ fname (str): Path to the audio file.
39
+ sample_rate (int): Target sample rate for resampling.
40
+ dtype (str, optional): Data type to load audio as (default: "float32").
41
+ device (torch.device, optional): Device to place the resulting tensor
42
+ on (default: CPU).
43
+ return_numpy (bool): If True, returns a NumPy array instead of a
44
+ PyTorch tensor.
45
+ max_seconds (float): Maximum length (seconds) of the audio tensor.
46
+ If the audio is longer than this, it will be truncated.
47
+
48
+ Returns:
49
+ torch.Tensor: Processed audio waveform as a PyTorch tensor,
50
+ with shape (num_samples,).
51
+
52
+ Notes:
53
+ - If the audio is stereo, it will be converted to mono by averaging channels.
54
+ - If the audio's sample rate differs from the target, it will be resampled.
55
+ """
56
+ # Load audio file with specified data type
57
+ wav_data, sr = sf.read(fname, dtype=dtype)
58
+
59
+ # Convert stereo to mono if necessary
60
+ if len(wav_data.shape) == 2:
61
+ wav_data = wav_data.mean(1)
62
+
63
+ # Resample to target sample rate if needed
64
+ if sr != sample_rate:
65
+ wav_data = torchaudio.functional.resample(
66
+ torch.from_numpy(wav_data), orig_freq=sr, new_freq=sample_rate
67
+ ).numpy()
68
+
69
+ if max_seconds is not None:
70
+ # Trim to max length
71
+ max_length = int(sample_rate * max_seconds)
72
+ if len(wav_data) > max_length:
73
+ wav_data = wav_data[:max_length]
74
+ logging.warning(
75
+ f"Wav file {fname} is longer than {max_seconds}s, "
76
+ f"truncated to {max_seconds}s to avoid OOM."
77
+ )
78
+ if return_numpy:
79
+ return wav_data
80
+ else:
81
+ wav_data = torch.from_numpy(wav_data)
82
+ return wav_data.to(device)
omnivoice/eval/wer/common.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """
19
+ Shared utilities for WER evaluation scripts.
20
+ """
21
+ import logging
22
+
23
+ import numpy as np
24
+ from jiwer import compute_measures
25
+
26
+
27
+ def process_one(hypothesis: str, truth: str, post_process, lang: str = None) -> dict:
28
+ """
29
+ Computes WER and related metrics for a single hypothesis-truth pair.
30
+
31
+ Args:
32
+ hypothesis (str): The transcribed text from the ASR model.
33
+ truth (str): The ground truth transcript.
34
+ post_process (callable): Text normalization function defined by each script.
35
+ Signature: post_process(text, lang) or post_process(text).
36
+ lang (str): The language code for post_process. Pass None if post_process
37
+ does not accept a lang argument.
38
+
39
+ Returns:
40
+ dict: A dict containing:
41
+ - truth (str): Post-processed ground truth text.
42
+ - hypothesis (str): Post-processed hypothesis text.
43
+ - wer (float): Word Error Rate.
44
+ - substitutions (int): Number of substitutions.
45
+ - deletions (int): Number of deletions.
46
+ - insertions (int): Number of insertions.
47
+ - word_num (int): Number of words in the post-processed ground truth.
48
+ """
49
+ if lang is not None:
50
+ truth_processed = post_process(truth, lang)
51
+ hypothesis_processed = post_process(hypothesis, lang)
52
+ else:
53
+ truth_processed = post_process(truth)
54
+ hypothesis_processed = post_process(hypothesis)
55
+ measures = compute_measures(truth_processed, hypothesis_processed)
56
+ word_num = len(truth_processed.split(" "))
57
+ return {
58
+ "truth": truth_processed,
59
+ "hypo": hypothesis_processed,
60
+ "wer": measures["wer"],
61
+ "substitutions": measures["substitutions"],
62
+ "deletions": measures["deletions"],
63
+ "insertions": measures["insertions"],
64
+ "word_num": word_num,
65
+ }
66
+
67
+
68
+ def log_metrics(fout, prefix, i_list, d_list, s_list, w_total, ndigits=2):
69
+ """Log weighted WER metrics for a subset of results."""
70
+ metrics_wer = round(
71
+ (np.sum(s_list) + np.sum(d_list) + np.sum(i_list)) / w_total * 100, ndigits
72
+ )
73
+ metrics_inse = np.sum(i_list)
74
+ metrics_dele = np.sum(d_list)
75
+ metrics_subs = np.sum(s_list)
76
+
77
+ logging.info(f"{prefix} WER: {metrics_wer}%")
78
+ logging.info(
79
+ f"{prefix} Errors: {metrics_inse} ins, {metrics_dele} del, "
80
+ f"{metrics_subs} sub / {w_total} words"
81
+ )
82
+ if fout:
83
+ fout.write(f"{prefix} WER: {metrics_wer}%\n")
84
+ fout.write(
85
+ f"{prefix} Errors: {metrics_inse} ins, {metrics_dele} del, "
86
+ f"{metrics_subs} sub / {w_total} words\n"
87
+ )
88
+ return metrics_wer
omnivoice/eval/wer/fleurs.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Computes word error rate (WER) for FLEURS multilingual evaluation.
19
+
20
+ Uses omnilingual-asr for ASR transcription across 100+ languages.
21
+ Requires a separate environment with ``omnilingual_asr`` installed.
22
+
23
+ Usage:
24
+ python3 omnivoice/eval/wer/fleurs.py \\
25
+ --wav-path results/fleurs \\
26
+ --test-list test.jsonl \\
27
+ --decode-path results/fleurs.wer.log \\
28
+ --model-card omniASR_LLM_Unlimited_7B_v2 \\
29
+ --chunk-size 100 --batch-size 50
30
+ """
31
+ import argparse
32
+ import logging
33
+ import multiprocessing as mp
34
+ import os
35
+ import re
36
+ import sys
37
+ import traceback
38
+ import types
39
+ from collections import defaultdict
40
+ from concurrent.futures import ProcessPoolExecutor, as_completed
41
+ from pathlib import Path
42
+ from typing import List, Union
43
+
44
+ import numpy as np
45
+ import torch
46
+ from tqdm import tqdm
47
+
48
+ try:
49
+ from omnilingual_asr.models.inference.pipeline import ASRInferencePipeline
50
+ from omnilingual_asr.models.wav2vec2_llama.lang_ids import supported_langs
51
+ except ImportError:
52
+ logging.error("Please install omnilingual_asr first.")
53
+ exit(1)
54
+
55
+ # omnilingual-asr may pull a transformers version that lacks
56
+ # HiggsAudioV2TokenizerModel. Pre-register stubs to bypass
57
+ # omnivoice/__init__.py heavy imports.
58
+ if "omnivoice" not in sys.modules:
59
+ _root = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", ".."))
60
+ for _name in (
61
+ "omnivoice",
62
+ "omnivoice.eval",
63
+ "omnivoice.eval.wer",
64
+ "omnivoice.utils",
65
+ ):
66
+ if _name not in sys.modules:
67
+ _m = types.ModuleType(_name)
68
+ _m.__path__ = [os.path.join(_root, *_name.split(".")[1:])]
69
+ _m.__package__ = _name
70
+ sys.modules[_name] = _m
71
+
72
+ from omnivoice.eval.wer.common import log_metrics, process_one
73
+ from omnivoice.eval.wer.text_norm_omni import text_normalize
74
+ from omnivoice.utils.data_utils import read_test_list
75
+
76
+ # --- Global variables for worker processes ---
77
+ worker_pipe = None
78
+ worker_device = None
79
+
80
+
81
+ # fix mismatched language codes between OmniVoice and Omnilingual-ASR model
82
+ rename = {
83
+ "et": "ekk",
84
+ "ms": "zsm",
85
+ "sw": "swh",
86
+ "npi": "nep",
87
+ }
88
+
89
+
90
+ def read_language_mapping_from_tsv(
91
+ mapping_path: Path,
92
+ ) -> dict[str, Union[str, List[str]]]:
93
+ with open(mapping_path, "r", encoding="utf-8") as f:
94
+ _ = f.readline() # Skip header
95
+ language_mapping = {}
96
+ for line in f:
97
+ parts = line.strip().split("\t")
98
+ mixed_id, language_name, iso_639_3_id, duration = parts
99
+ language_mapping[iso_639_3_id] = mixed_id
100
+ return language_mapping
101
+
102
+
103
+ iso_639_3_id_to_mixed_id = read_language_mapping_from_tsv(
104
+ Path(f"{os.path.dirname(__file__)}/../../../docs/lang_id_name_map.tsv")
105
+ )
106
+
107
+ mixed_id_to_omnilingual_asr_lang = {}
108
+
109
+ for lang in supported_langs:
110
+ if lang in ("cmn_Hant",):
111
+ continue
112
+ iso_639_3_lang_code = lang.split("_")[0]
113
+ if iso_639_3_lang_code in iso_639_3_id_to_mixed_id:
114
+ mixed_id = iso_639_3_id_to_mixed_id[iso_639_3_lang_code]
115
+ mixed_id_to_omnilingual_asr_lang[mixed_id] = lang
116
+ else:
117
+ mixed_id_to_omnilingual_asr_lang[iso_639_3_lang_code] = lang
118
+
119
+
120
+ def clean_cjk_spaces(text):
121
+ """
122
+ Removes spaces adjacent to Chinese and Japanese characters while preserving
123
+ meaningful spaces in English or other languages (like Korean).
124
+ """
125
+
126
+ # Define CJK (Chinese, Japanese) Unicode ranges
127
+ # \u4e00-\u9fff: CJK Unified Ideographs (Chinese)
128
+ # \u3040-\u309f: Hiragana (Japanese)
129
+ # \u30a0-\u30ff: Katakana (Japanese)
130
+ # \u3000-\u303f: CJK Symbols and Punctuation
131
+ cjk_range = r"\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\u3000-\u303f"
132
+
133
+ # 1. Remove spaces between two CJK characters
134
+ # Example: "我 爱 你" -> "我爱你"
135
+ text = re.sub(f"([{cjk_range}])\\s+([{cjk_range}])", r"\1\2", text)
136
+
137
+ # 2. Remove spaces between a CJK character and a non-CJK character (English/Numbers)
138
+ # Example: "我 爱 you" -> "我爱you"
139
+ text = re.sub(f"([{cjk_range}])\\s+", r"\1", text)
140
+ text = re.sub(f"\\s+([{cjk_range}])", r"\1", text)
141
+
142
+ # 3. Collapse multiple spaces into one for the remaining parts (e.g., English words)
143
+ text = re.sub(r"\s+", " ", text)
144
+
145
+ return text.strip()
146
+
147
+
148
+ def get_parser():
149
+ parser = argparse.ArgumentParser(
150
+ description="Computes WER with Whisper.",
151
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
152
+ )
153
+
154
+ parser.add_argument(
155
+ "--wav-path",
156
+ type=str,
157
+ required=True,
158
+ help="Path to the directory containing speech files.",
159
+ )
160
+
161
+ parser.add_argument(
162
+ "--extension",
163
+ type=str,
164
+ default="wav",
165
+ help="Extension of the speech files. Default: wav",
166
+ )
167
+
168
+ parser.add_argument(
169
+ "--decode-path",
170
+ type=str,
171
+ default=None,
172
+ help="Path to the output file where WER information will be saved. "
173
+ "If not provided, results are only printed to console.",
174
+ )
175
+ parser.add_argument(
176
+ "--model-card",
177
+ type=str,
178
+ default="omniASR_LLM_7B",
179
+ help="Model card name for OmniASR (e.g., omniASR_LLM_7B) or local path.",
180
+ )
181
+ parser.add_argument(
182
+ "--test-list",
183
+ type=str,
184
+ default="test.jsonl",
185
+ help="path of the JSONL test list. Each line is a JSON object "
186
+ "with fields: id, text, ref_audio, ref_text, language_id, language_name.",
187
+ )
188
+ parser.add_argument(
189
+ "--lang",
190
+ type=str,
191
+ default=None,
192
+ help="""Language code to evaluate (e.g., 'en' for English, 'zh' for Chinese).
193
+ If not provided, the script will evaluate all languages found in the test list.
194
+ If specified, only samples of the given language will be evaluated.
195
+ """,
196
+ )
197
+ parser.add_argument(
198
+ "--batch-size",
199
+ type=int,
200
+ default=8,
201
+ help="Batch size for decoding with the Hugging Face pipeline.",
202
+ )
203
+ parser.add_argument(
204
+ "--nj-per-gpu", type=int, default=1, help="Number of workers per GPU."
205
+ )
206
+ parser.add_argument(
207
+ "--chunk-size",
208
+ type=int,
209
+ default=300,
210
+ help="Number of samples per task chunk sent to workers.",
211
+ )
212
+ return parser
213
+
214
+
215
+ def load_omni_model(model_card, device):
216
+ logging.info(f"Loading OmniASR model ({model_card}) on {device}...")
217
+ try:
218
+ pipeline = ASRInferencePipeline(model_card=model_card, device=str(device))
219
+ return pipeline
220
+ except Exception as e:
221
+ logging.error(f"Failed to load OmniASR pipeline: {e}")
222
+ return None
223
+
224
+
225
+ def process_init(rank_queue, model_card):
226
+ """
227
+ Initializer for each worker process.
228
+ """
229
+ global worker_pipe, worker_device
230
+
231
+ # Configure threads constraint
232
+ torch.set_num_threads(2)
233
+
234
+ try:
235
+ rank = rank_queue.get(timeout=10)
236
+ except Exception:
237
+ raise RuntimeError("Failed to get GPU rank from queue.")
238
+
239
+ assert torch.cuda.is_available(), "CUDA is required but not available."
240
+ worker_device = torch.device(f"cuda:{rank}")
241
+ torch.cuda.set_device(rank)
242
+
243
+ logging.info(f"Initializing worker on device: {worker_device}")
244
+
245
+ try:
246
+ # Using the model_card argument
247
+ worker_pipe = load_omni_model(model_card, worker_device)
248
+ if worker_pipe is None:
249
+ raise RuntimeError("Model loading failed.")
250
+ except Exception as e:
251
+ logging.critical(f"Failed to load model on {worker_device}: {e}")
252
+ raise e
253
+
254
+
255
+ def post_process(text: str, lang: str) -> str:
256
+ """
257
+ Cleans and normalizes text for WER calculation.
258
+ Args:
259
+ text (str): The input text to be processed.
260
+ lang (str): The language of the input text.
261
+
262
+ Returns:
263
+ str: The cleaned and normalized text.
264
+ """
265
+ lang_id = lang[:3] # Extract ISO 639-3 code (e.g., 'eng' from 'eng_Latn')
266
+ text = text_normalize(
267
+ text,
268
+ iso_code=lang_id,
269
+ lower_case=True,
270
+ remove_numbers=False,
271
+ remove_brackets=False,
272
+ )
273
+ text = clean_cjk_spaces(text)
274
+ text = text.replace(" ", "|")
275
+ text = " ".join([x for x in text])
276
+ return text
277
+
278
+
279
+ def run_eval_worker(data_chunk, language, batch_size):
280
+ """
281
+ Worker function to process a chunk of data.
282
+ Uses the global worker_pipe initialized by process_init.
283
+ """
284
+ global worker_pipe
285
+ if worker_pipe is None:
286
+ logging.error("Worker pipeline is not initialized!")
287
+ return []
288
+
289
+ metrics_buffer = []
290
+ try:
291
+ # Prepare batch lists for OmniASR
292
+ audio_paths = [item["wav_path"] for item in data_chunk]
293
+
294
+ # OmniASR expects explicit language codes for each file if not auto-detected.
295
+ # Using the language passed to the worker function, or item specific language
296
+ # Assuming item['lang_id'] is compatible (e.g., 'en', 'zh', 'arb_Arab')
297
+ # If the model needs full tokens like 'en_Latn', conversion might be needed here depending on input data.
298
+ lang_list = [item.get("lang_id", language) for item in data_chunk]
299
+
300
+ # Use the pipeline to infer batch
301
+ # OmniASR pipeline.transcribe returns a list of strings
302
+ transcriptions = worker_pipe.transcribe(
303
+ audio_paths, lang=lang_list, batch_size=batch_size
304
+ )
305
+
306
+ for i, hypo_text in enumerate(transcriptions):
307
+ ref_item = data_chunk[i]
308
+ truth = ref_item["truth_text"]
309
+ wav_path = ref_item["wav_path"]
310
+ lang_id = ref_item.get("lang_id")
311
+ lang_name = ref_item.get("lang_name")
312
+
313
+ m = process_one(hypo_text, truth, post_process, lang_id)
314
+ m["wav_path"] = wav_path
315
+ m["lang_name"] = lang_name
316
+ metrics_buffer.append(m)
317
+
318
+ except Exception:
319
+ logging.error(
320
+ f"Worker failed on chunk (Lang: {language}):\n{traceback.format_exc()}"
321
+ )
322
+ return []
323
+
324
+ return metrics_buffer
325
+
326
+
327
+ def main():
328
+ parser = get_parser()
329
+ args = parser.parse_args()
330
+
331
+ logging.basicConfig(
332
+ format="%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s",
333
+ level=logging.INFO,
334
+ force=True,
335
+ )
336
+
337
+ # 1. Prepare Data
338
+ logging.info("Reading test list...")
339
+ data_by_lang = defaultdict(list)
340
+ total_files = 0
341
+ wav_root = Path(args.wav_path)
342
+
343
+ samples = read_test_list(args.test_list)
344
+ for s in samples:
345
+ wav_path = str(wav_root / f"{s['id']}.{args.extension}")
346
+ if not os.path.exists(wav_path):
347
+ logging.warning(f"File missing: {wav_path}")
348
+ continue
349
+
350
+ lang_id = s.get("language_id") or "unknown"
351
+ if lang_id in rename:
352
+ lang_id = mixed_id_to_omnilingual_asr_lang[rename[lang_id]]
353
+ else:
354
+ lang_id = mixed_id_to_omnilingual_asr_lang[lang_id]
355
+ item = {
356
+ "wav_path": wav_path,
357
+ "truth_text": s["text"],
358
+ "lang_id": lang_id,
359
+ "lang_name": s.get("language_name") or "unknown",
360
+ }
361
+ if args.lang and s.get("language_id") != args.lang:
362
+ continue
363
+
364
+ data_by_lang[s.get("language_name") or "unknown"].append(item)
365
+
366
+ total_files += 1
367
+
368
+ logging.info(f"Total files: {total_files} in {len(data_by_lang)} languages.")
369
+
370
+ # 2. Worker config
371
+ num_gpus = torch.cuda.device_count()
372
+ assert num_gpus > 0, "No GPU found. GPU is required."
373
+ total_workers = num_gpus * args.nj_per_gpu
374
+
375
+ mp.set_start_method("spawn", force=True)
376
+ manager = mp.Manager()
377
+ rank_queue = manager.Queue()
378
+
379
+ for _ in range(args.nj_per_gpu):
380
+ for rank in range(num_gpus):
381
+ rank_queue.put(rank)
382
+
383
+ # 3. Scheduling: Split languages into chunks
384
+ # This prevents one huge language from blocking a worker for too long,
385
+ # allows better load balancing across the pool.
386
+ tasks = []
387
+ chunk_size = args.chunk_size
388
+
389
+ for lang_name, items in data_by_lang.items():
390
+ # Slicing the list into chunks
391
+ for i in range(0, len(items), chunk_size):
392
+ chunk = items[i : i + chunk_size]
393
+ tasks.append({"chunk": chunk, "lang": lang_name})
394
+
395
+ logging.info(
396
+ f"Split data into {len(tasks)} chunks (size ~{chunk_size}). Spawning {total_workers} workers."
397
+ )
398
+
399
+ # 4. Execution
400
+ results = []
401
+
402
+ with ProcessPoolExecutor(
403
+ max_workers=total_workers,
404
+ initializer=process_init,
405
+ initargs=(rank_queue, args.model_card),
406
+ ) as executor:
407
+
408
+ futures = []
409
+ for task in tasks:
410
+ futures.append(
411
+ executor.submit(
412
+ run_eval_worker, task["chunk"], task["lang"], args.batch_size
413
+ )
414
+ )
415
+
416
+ # Unified progress bar
417
+ with tqdm(total=total_files, desc="Eval Progress", dynamic_ncols=True) as pbar:
418
+ for future in as_completed(futures):
419
+ try:
420
+ chunk_metrics = future.result()
421
+ results.extend(chunk_metrics)
422
+ pbar.update(len(chunk_metrics))
423
+ except Exception as e:
424
+ logging.error(f"Task failed: {e}")
425
+
426
+ # 5. Metrics Aggregation
427
+ wers, inses, deles, subses = [], [], [], []
428
+ word_nums = 0
429
+
430
+ # Store metrics per language
431
+ lang_stats = {}
432
+
433
+ fout = None
434
+ if args.decode_path:
435
+ os.makedirs(os.path.dirname(args.decode_path), exist_ok=True)
436
+ logging.info(f"Saving detailed WER results to: {args.decode_path}")
437
+ fout = open(args.decode_path, "w", encoding="utf-8")
438
+
439
+ for res in results:
440
+ wers.append(float(res["wer"]))
441
+ inses.append(float(res["insertions"]))
442
+ deles.append(float(res["deletions"]))
443
+ subses.append(float(res["substitutions"]))
444
+ word_nums += res["word_num"]
445
+
446
+ if fout:
447
+ fout.write(
448
+ f"{res['wav_path']}\t{res['wer']}\t{res['truth']}\t"
449
+ f"{res['hypo']}\t{res['insertions']}\t{res['deletions']}\t"
450
+ f"{res['substitutions']}\n"
451
+ )
452
+ lang_name = res["lang_name"]
453
+
454
+ # Per language stats
455
+ if lang_name not in lang_stats:
456
+ lang_stats[lang_name] = {
457
+ "inses": [],
458
+ "deles": [],
459
+ "subses": [],
460
+ "word_nums": 0,
461
+ }
462
+ lang_stats[lang_name]["inses"].append(float(res["insertions"]))
463
+ lang_stats[lang_name]["deles"].append(float(res["deletions"]))
464
+ lang_stats[lang_name]["subses"].append(float(res["substitutions"]))
465
+ lang_stats[lang_name]["word_nums"] += res["word_num"]
466
+
467
+ print("-" * 50)
468
+ # Log per-language stats
469
+ per_lang_wers = []
470
+ for lang in sorted(lang_stats.keys()):
471
+ stats = lang_stats[lang]
472
+ if stats["word_nums"] > 0:
473
+ lang_wer = log_metrics(
474
+ fout,
475
+ f"[{lang}]",
476
+ stats["inses"],
477
+ stats["deles"],
478
+ stats["subses"],
479
+ stats["word_nums"],
480
+ )
481
+ per_lang_wers.append(lang_wer)
482
+ print("-" * 50)
483
+
484
+ # Log Macro-average WER
485
+ if len(per_lang_wers) > 1:
486
+ macro_wer = np.mean(per_lang_wers)
487
+ logging.info(
488
+ f"Macro-average WER over {len(per_lang_wers)} languages: {macro_wer:.2f}%"
489
+ )
490
+ if fout:
491
+ fout.write(
492
+ f"Macro-average WER over {len(per_lang_wers)} languages: {macro_wer:.2f}%\n"
493
+ )
494
+ count_le_5 = sum(1 for w in per_lang_wers if w <= 5.0)
495
+ count_le_10 = sum(1 for w in per_lang_wers if w <= 10.0)
496
+ count_le_20 = sum(1 for w in per_lang_wers if w <= 20.0)
497
+
498
+ stats_msg = (
499
+ f"Languages with WER/CER <= 5%: {count_le_5}/{len(per_lang_wers)}\n"
500
+ f"Languages with WER/CER <= 10%: {count_le_10}/{len(per_lang_wers)}\n"
501
+ f"Languages with WER/CER <= 20%: {count_le_20}/{len(per_lang_wers)}"
502
+ )
503
+
504
+ logging.info("\n" + stats_msg)
505
+ if fout:
506
+ fout.write(stats_msg + "\n")
507
+
508
+ # Log overall stats
509
+ if word_nums > 0:
510
+ log_metrics(fout, "Overall", inses, deles, subses, word_nums)
511
+
512
+ if fout:
513
+ fout.close()
514
+
515
+
516
+ if __name__ == "__main__":
517
+ main()
omnivoice/eval/wer/hubert.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """
19
+ Computes word error rate (WER) with Hubert models for LibriSpeech test sets.
20
+ """
21
+ import argparse
22
+ import logging
23
+ import multiprocessing as mp
24
+ import os
25
+ import re
26
+ import traceback
27
+ from concurrent.futures import ProcessPoolExecutor, as_completed
28
+ from pathlib import Path
29
+
30
+ import numpy as np
31
+ import torch
32
+ from tqdm import tqdm
33
+
34
+ from omnivoice.eval.utils import load_eval_waveform
35
+ from omnivoice.eval.wer.common import process_one
36
+ from omnivoice.utils.data_utils import read_test_list
37
+
38
+ # --- Global variables for worker processes ---
39
+ worker_pipe = None
40
+ worker_device = None
41
+
42
+
43
+ def get_parser():
44
+ parser = argparse.ArgumentParser(
45
+ description="Computes WER with Hubert-based ASR model.",
46
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
47
+ )
48
+ parser.add_argument(
49
+ "--wav-path",
50
+ type=str,
51
+ required=True,
52
+ help="Path to the directory containing speech files.",
53
+ )
54
+ parser.add_argument(
55
+ "--extension",
56
+ type=str,
57
+ default="wav",
58
+ help="Extension of the speech files. Default: wav",
59
+ )
60
+ parser.add_argument(
61
+ "--decode-path",
62
+ type=str,
63
+ default=None,
64
+ help="Path to the output file where WER information will be saved. "
65
+ "If not provided, results are only printed to console.",
66
+ )
67
+ parser.add_argument(
68
+ "--model-dir",
69
+ type=str,
70
+ required=True,
71
+ help="Local path of our evaluation model repository."
72
+ "Download from https://huggingface.co/k2-fsa/TTS_eval_models."
73
+ "Will use 'tts_eval_models/wer/hubert-large-ls960-ft/'"
74
+ " in this script",
75
+ )
76
+ parser.add_argument(
77
+ "--test-list",
78
+ type=str,
79
+ default="transcript.jsonl",
80
+ help="path of the JSONL test list. Each line is a JSON object "
81
+ "with fields: id, text, ref_audio, ref_text, language_id, language_name.",
82
+ )
83
+ parser.add_argument(
84
+ "--batch-size",
85
+ type=int,
86
+ default=16,
87
+ help="Batch size for decoding with the Hugging Face pipeline.",
88
+ )
89
+ parser.add_argument(
90
+ "--nj-per-gpu", type=int, default=1, help="Number of workers per GPU."
91
+ )
92
+ return parser
93
+
94
+
95
+ def process_init(rank_queue, model_dir):
96
+ global worker_pipe, worker_device
97
+
98
+ torch.set_num_threads(2)
99
+
100
+ try:
101
+ rank = rank_queue.get(timeout=10)
102
+ except Exception:
103
+ raise RuntimeError("Failed to get GPU rank from queue.")
104
+
105
+ assert torch.cuda.is_available(), "CUDA is required but not available."
106
+ worker_device = torch.device(f"cuda:{rank}")
107
+ torch.cuda.set_device(rank)
108
+
109
+ logging.info(f"Initializing worker on device: {worker_device}")
110
+
111
+ try:
112
+ worker_pipe = load_hubert_model(model_dir, worker_device)
113
+ if worker_pipe is None:
114
+ raise RuntimeError("Model loading failed.")
115
+ except Exception as e:
116
+ logging.critical(f"Failed to load model on {worker_device}: {e}")
117
+ raise e
118
+
119
+
120
+ def load_hubert_model(model_dir, device):
121
+ model_path = os.path.join(model_dir, "wer/hubert-large-ls960-ft/")
122
+ if not os.path.exists(model_path):
123
+ logging.error(
124
+ f"Hubert model not found at {model_path}. "
125
+ "Please download from https://huggingface.co/k2-fsa/TTS_eval_models"
126
+ )
127
+ return None
128
+
129
+ logging.debug(f"Loading Hubert-based ASR model on {device}...")
130
+ import transformers
131
+
132
+ # Suppress transformers logging
133
+ transformers.logging.set_verbosity_error()
134
+
135
+ pipe = transformers.pipeline(
136
+ "automatic-speech-recognition",
137
+ model=model_path,
138
+ device=device,
139
+ tokenizer=model_path,
140
+ )
141
+ return pipe
142
+
143
+
144
+ def post_process(text: str) -> str:
145
+ """
146
+ Cleans and normalizes text for WER calculation.
147
+ Args:
148
+ text (str): The input text to be processed.
149
+
150
+ Returns:
151
+ str: The cleaned and normalized text.
152
+ """
153
+ text = text.replace("‘", "'").replace("’", "'")
154
+ text = re.sub(r"[^a-zA-Z0-9']", " ", text.lower())
155
+ text = re.sub(r"\s+", " ", text).strip()
156
+ return text
157
+
158
+
159
+ def run_eval_worker(data_chunk, batch_size):
160
+ global worker_pipe
161
+ if worker_pipe is None:
162
+ logging.error("Worker pipeline is not initialized!")
163
+ return []
164
+
165
+ metrics_buffer = []
166
+ try:
167
+ dataset = [
168
+ {
169
+ "array": load_eval_waveform(
170
+ item["wav_path"], sample_rate=16000, return_numpy=True
171
+ ),
172
+ "sampling_rate": 16000,
173
+ }
174
+ for item in data_chunk
175
+ ]
176
+ generate_kwargs = {"language": "english", "task": "transcribe"}
177
+
178
+ iterator = worker_pipe(
179
+ dataset, generate_kwargs=generate_kwargs, batch_size=batch_size
180
+ )
181
+
182
+ for i, out in enumerate(iterator):
183
+ hypothesis = out["text"].strip()
184
+ ref_item = data_chunk[i]
185
+ truth = ref_item["truth_text"]
186
+ wav_path = ref_item["wav_path"]
187
+
188
+ m = process_one(hypothesis, truth, post_process)
189
+ m["wav_path"] = wav_path
190
+ metrics_buffer.append(m)
191
+
192
+ except Exception:
193
+ logging.error(f"Worker failed on chunk:\n{traceback.format_exc()}")
194
+ return []
195
+
196
+ return metrics_buffer
197
+
198
+
199
+ def main():
200
+ parser = get_parser()
201
+ args = parser.parse_args()
202
+
203
+ logging.basicConfig(
204
+ format="%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s",
205
+ level=logging.INFO,
206
+ force=True,
207
+ )
208
+
209
+ logging.info(f"Calculating WER for {args.wav_path}")
210
+
211
+ data_list = []
212
+ samples = read_test_list(args.test_list)
213
+ for s in samples:
214
+ wav_full_path = str(Path(args.wav_path) / (s["id"] + "." + args.extension))
215
+ if not os.path.exists(wav_full_path):
216
+ logging.warning(f"File missing: {wav_full_path}")
217
+ continue
218
+ data_list.append(
219
+ {
220
+ "wav_path": wav_full_path,
221
+ "truth_text": s["text"],
222
+ }
223
+ )
224
+ total_files = len(data_list)
225
+
226
+ num_gpus = torch.cuda.device_count()
227
+ assert num_gpus > 0, "No GPU found. GPU is required."
228
+ total_workers = num_gpus * args.nj_per_gpu
229
+
230
+ mp.set_start_method("spawn", force=True)
231
+ manager = mp.Manager()
232
+ rank_queue = manager.Queue()
233
+
234
+ for _ in range(args.nj_per_gpu):
235
+ for rank in range(num_gpus):
236
+ rank_queue.put(rank)
237
+
238
+ chunk_size = max(1, args.batch_size)
239
+ tasks = [data_list[i : i + chunk_size] for i in range(0, total_files, chunk_size)]
240
+
241
+ logging.info(
242
+ f"Split data into {len(tasks)} chunks (size ~{chunk_size}). "
243
+ f"Spawning {total_workers} workers."
244
+ )
245
+
246
+ results = []
247
+
248
+ with ProcessPoolExecutor(
249
+ max_workers=total_workers,
250
+ initializer=process_init,
251
+ initargs=(rank_queue, args.model_dir),
252
+ ) as executor:
253
+
254
+ futures = []
255
+ for chunk in tasks:
256
+ futures.append(executor.submit(run_eval_worker, chunk, args.batch_size))
257
+
258
+ with tqdm(total=total_files, desc="Eval Progress", dynamic_ncols=True) as pbar:
259
+ for future in as_completed(futures):
260
+ chunk_metrics = future.result()
261
+ results.extend(chunk_metrics)
262
+ pbar.update(len(chunk_metrics))
263
+
264
+ wers, inses, deles, subses = [], [], [], []
265
+ word_nums = 0
266
+
267
+ fout = None
268
+ if args.decode_path:
269
+ os.makedirs(os.path.dirname(args.decode_path), exist_ok=True)
270
+ fout = open(args.decode_path, "w", encoding="utf8")
271
+ logging.info(f"Saving detailed WER results to: {args.decode_path}")
272
+ fout.write(
273
+ "Name\tWER\tTruth\tHypothesis\tInsertions\tDeletions\tSubstitutions\n"
274
+ )
275
+
276
+ for res in results:
277
+ wers.append(float(res["wer"]))
278
+ inses.append(float(res["insertions"]))
279
+ deles.append(float(res["deletions"]))
280
+ subses.append(float(res["substitutions"]))
281
+ word_nums += res["word_num"]
282
+
283
+ if fout:
284
+ fout.write(
285
+ f"{res['wav_path']}\t{res['wer']}\t{res['truth']}\t"
286
+ f"{res['hypo']}\t{res['insertions']}\t{res['deletions']}\t"
287
+ f"{res['substitutions']}\n"
288
+ )
289
+
290
+ wer_weighted = (
291
+ round(
292
+ (np.sum(subses) + np.sum(deles) + np.sum(inses)) / word_nums * 100, 2
293
+ )
294
+ if word_nums > 0
295
+ else float("nan")
296
+ )
297
+
298
+ inse_sum = np.sum(inses)
299
+ dele_sum = np.sum(deles)
300
+ subs_sum = np.sum(subses)
301
+
302
+ print("-" * 50)
303
+ logging.info(f"Processed {len(results)}/{total_files} files.")
304
+ wer_info = f"WER: {wer_weighted}%"
305
+ detailed_info = (
306
+ f"Errors: {inse_sum} ins, {dele_sum} del, {subs_sum} sub / {word_nums} words"
307
+ )
308
+ logging.info(wer_info)
309
+ logging.info(detailed_info)
310
+ print("-" * 50)
311
+
312
+ if fout:
313
+ fout.write(wer_info + "\n" + detailed_info + "\n")
314
+ fout.close()
315
+
316
+
317
+ if __name__ == "__main__":
318
+ main()
omnivoice/eval/wer/minimax.py ADDED
@@ -0,0 +1,596 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """
19
+ Computes word error rate (WER) with Whisper-large-v3 for English and
20
+ Paraformer for Chinese. Intended to evaluate WERs on Seed-TTS test sets.
21
+ """
22
+ import argparse
23
+ import logging
24
+ import multiprocessing as mp
25
+ import os
26
+ import traceback
27
+ from collections import defaultdict
28
+ from concurrent.futures import ProcessPoolExecutor, as_completed
29
+ from pathlib import Path
30
+ from typing import List, Union
31
+
32
+ import numpy as np
33
+ import torch
34
+ import zhconv
35
+ from tqdm import tqdm
36
+
37
+ from omnivoice.eval.utils import load_eval_waveform
38
+ from omnivoice.eval.wer.common import log_metrics, process_one
39
+ from omnivoice.eval.wer.text_norm_omni import text_normalize
40
+ from omnivoice.utils.data_utils import read_test_list
41
+
42
+ # --- Global variables for worker processes ---
43
+ worker_pipe = None
44
+ worker_paraformer = None
45
+ worker_device = None
46
+
47
+
48
+ def read_language_mapping_from_tsv(
49
+ mapping_path: Path,
50
+ ) -> dict[str, Union[str, List[str]]]:
51
+ with open(mapping_path, "r", encoding="utf-8") as f:
52
+ _ = f.readline() # Skip header
53
+ language_mapping = {}
54
+ for line in f:
55
+ parts = line.strip().split("\t")
56
+ mixed_id, language_name, iso_639_3_id, duration = parts
57
+ language_mapping[mixed_id] = iso_639_3_id
58
+ return language_mapping
59
+
60
+
61
+ mixed_id_to_iso_639_3_id = read_language_mapping_from_tsv(
62
+ Path(f"{os.path.dirname(__file__)}/../../../docs/lang_id_name_map.tsv")
63
+ )
64
+
65
+
66
+ def get_parser():
67
+ parser = argparse.ArgumentParser(
68
+ description="Computes WER with Whisper.",
69
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
70
+ )
71
+
72
+ parser.add_argument(
73
+ "--wav-path",
74
+ type=str,
75
+ required=True,
76
+ help="Path to the directory containing speech files.",
77
+ )
78
+
79
+ parser.add_argument(
80
+ "--extension",
81
+ type=str,
82
+ default="wav",
83
+ help="Extension of the speech files. Default: wav",
84
+ )
85
+
86
+ parser.add_argument(
87
+ "--decode-path",
88
+ type=str,
89
+ default=None,
90
+ help="Path to the output file where WER information will be saved. "
91
+ "If not provided, results are only printed to console.",
92
+ )
93
+ parser.add_argument(
94
+ "--model-dir",
95
+ type=str,
96
+ required=True,
97
+ help="Local path of evaluation models repository. "
98
+ "Download from https://huggingface.co/k2-fsa/TTS_eval_models. ",
99
+ )
100
+ parser.add_argument(
101
+ "--test-list",
102
+ type=str,
103
+ default="test.jsonl",
104
+ help="path of the JSONL test list. Each line is a JSON object "
105
+ "with fields: id, text, ref_audio, ref_text, language_id, language_name.",
106
+ )
107
+ parser.add_argument(
108
+ "--lang",
109
+ type=str,
110
+ default=None,
111
+ help="""Language code to evaluate (e.g., 'en' for English, 'zh' for Chinese).
112
+ If not provided, the script will evaluate all languages found in the test list.
113
+ If specified, only samples of the given language will be evaluated.
114
+ """,
115
+ )
116
+ parser.add_argument(
117
+ "--batch-size",
118
+ type=int,
119
+ default=16,
120
+ help="Batch size for decoding with the Hugging Face pipeline.",
121
+ )
122
+ parser.add_argument(
123
+ "--nj-per-gpu", type=int, default=1, help="Number of workers per GPU."
124
+ )
125
+ parser.add_argument(
126
+ "--chunk-size",
127
+ type=int,
128
+ default=10,
129
+ help="Number of samples per task chunk sent to workers.",
130
+ )
131
+ return parser
132
+
133
+
134
+ def load_whisper_model(model_dir, device):
135
+ model_path = os.path.join(model_dir, "wer/whisper-large-v3/")
136
+ if not os.path.exists(model_path):
137
+ logging.error(f"Whisper model not found at {model_path}.")
138
+ return None
139
+
140
+ import transformers
141
+
142
+ # Suppress transformers logging
143
+ transformers.logging.set_verbosity_error()
144
+
145
+ logging.info(f"Loading Whisper model on {device}...")
146
+ pipe = transformers.pipeline(
147
+ "automatic-speech-recognition",
148
+ model=model_path,
149
+ chunk_length_s=30,
150
+ dtype=torch.float16 if "cuda" in str(device) else torch.float32,
151
+ device=device,
152
+ )
153
+ return pipe
154
+
155
+
156
+ def load_paraformer_model(model_dir, device):
157
+ model_path = os.path.join(model_dir, "wer/paraformer-zh/")
158
+ if not os.path.exists(model_path):
159
+ logging.error(f"Paraformer model not found at {model_path}.")
160
+ return None
161
+
162
+ logging.info(f"Loading Paraformer model on {device}...")
163
+
164
+ previous_level = logging.root.manager.disable
165
+ logging.disable(logging.CRITICAL)
166
+
167
+ try:
168
+ from funasr import AutoModel
169
+
170
+ model = AutoModel(
171
+ model=model_path,
172
+ device=str(device),
173
+ disable_update=True,
174
+ disable_pbar=True,
175
+ verbose=False,
176
+ )
177
+ finally:
178
+ logging.disable(previous_level)
179
+
180
+ return model
181
+
182
+
183
+ def _worker_setup(rank_queue):
184
+ """Common worker setup: get rank, configure device and threads."""
185
+ global worker_device
186
+
187
+ torch.set_num_threads(2)
188
+
189
+ try:
190
+ rank = rank_queue.get(timeout=10)
191
+ except Exception:
192
+ raise RuntimeError("Failed to get GPU rank from queue.")
193
+
194
+ assert torch.cuda.is_available(), "CUDA is required but not available."
195
+ worker_device = torch.device(f"cuda:{rank}")
196
+ torch.cuda.set_device(rank)
197
+
198
+ logging.info(f"Initializing worker on device: {worker_device}")
199
+
200
+
201
+ def process_init(rank_queue, model_dir):
202
+ """Initializer for Whisper worker processes."""
203
+ global worker_pipe
204
+
205
+ _worker_setup(rank_queue)
206
+
207
+ try:
208
+ worker_pipe = load_whisper_model(model_dir, worker_device)
209
+ if worker_pipe is None:
210
+ raise RuntimeError("Whisper model loading failed.")
211
+ except Exception as e:
212
+ logging.critical(f"Failed to load Whisper model on {worker_device}: {e}")
213
+ raise e
214
+
215
+
216
+ def process_init_paraformer(rank_queue, model_dir):
217
+ """Initializer for Paraformer worker processes (Chinese evaluation)."""
218
+ global worker_paraformer
219
+
220
+ _worker_setup(rank_queue)
221
+
222
+ try:
223
+ worker_paraformer = load_paraformer_model(model_dir, worker_device)
224
+ if worker_paraformer is None:
225
+ raise RuntimeError("Paraformer model loading failed.")
226
+ except Exception as e:
227
+ logging.critical(f"Failed to load Paraformer model on {worker_device}: {e}")
228
+ raise e
229
+
230
+
231
+ def post_process(text: str, lang: str) -> str:
232
+ """
233
+ Cleans and normalizes text for WER calculation.
234
+ Args:
235
+ text (str): The input text to be processed.
236
+ lang (str): The language of the input text.
237
+
238
+ Returns:
239
+ str: The cleaned and normalized text.
240
+ """
241
+ if lang != "unknown":
242
+
243
+ iso_639_3_code = mixed_id_to_iso_639_3_id[lang]
244
+ text = text_normalize(
245
+ text,
246
+ iso_code=iso_639_3_code,
247
+ lower_case=True,
248
+ remove_numbers=False,
249
+ remove_brackets=False,
250
+ )
251
+
252
+ if lang in ["zh", "yue"]:
253
+ text = zhconv.convert(text, "zh-cn")
254
+
255
+ # Processing spaces for languages using CER (consistent with the practice
256
+ # in paper Minimax-Speech), specifically: zh, yue, ja, ko, th, arb, vi, hi, el.
257
+ if lang in ("zh", "yue", "ja"):
258
+ # For languages where spaces are not semantically meaningful, remove spaces.
259
+ text = text.replace(" ", "")
260
+ text = " ".join([x for x in text])
261
+ elif lang in ("ko", "th", "arb", "vi", "hi", "el"):
262
+ # For languages where spaces are semantically meaningful, replace spaces with |.
263
+ text = text.replace(" ", "|")
264
+ text = " ".join([x for x in text])
265
+ text = text.lower()
266
+ return text.strip()
267
+
268
+
269
+ class SpeechEvalDataset(torch.utils.data.Dataset):
270
+ def __init__(self, data_list):
271
+ self.data_list = data_list
272
+
273
+ def __len__(self):
274
+ return len(self.data_list)
275
+
276
+ def __getitem__(self, index):
277
+ item = self.data_list[index]
278
+ waveform = load_eval_waveform(item["wav_path"], sample_rate=16000, return_numpy=True)
279
+ return {
280
+ "array": waveform,
281
+ "sampling_rate": 16000,
282
+ "truth_text": item["truth_text"],
283
+ }
284
+
285
+
286
+ def run_eval_worker(data_chunk, language, batch_size):
287
+ """
288
+ Worker function to process a chunk of data.
289
+ Uses the global worker_pipe initialized by process_init.
290
+ """
291
+ global worker_pipe
292
+ if worker_pipe is None:
293
+ logging.error("Worker pipeline is not initialized!")
294
+ return []
295
+
296
+ metrics_buffer = []
297
+ try:
298
+ dataset = SpeechEvalDataset(data_chunk)
299
+ if language != "unknown":
300
+ generate_kwargs = {"language": language, "task": "transcribe"}
301
+ else:
302
+ generate_kwargs = {"task": "transcribe"}
303
+
304
+ # Use the pipeline to infer batch
305
+ # Note: We iterate through the iterator returned by pipe
306
+ iterator = worker_pipe(
307
+ dataset, generate_kwargs=generate_kwargs, batch_size=batch_size
308
+ )
309
+
310
+ for i, out in enumerate(iterator):
311
+ hypothesis = out["text"].strip()
312
+
313
+ ref_item = data_chunk[i]
314
+ truth = ref_item["truth_text"]
315
+ wav_path = ref_item["wav_path"]
316
+ lang_id = ref_item.get("lang_id")
317
+ lang_name = ref_item.get("lang_name")
318
+
319
+ m = process_one(hypothesis, truth, post_process, lang_id)
320
+ m["wav_path"] = wav_path
321
+ m["lang_name"] = lang_name
322
+ metrics_buffer.append(m)
323
+
324
+ except Exception:
325
+ logging.error(
326
+ f"Worker failed on chunk (Lang: {language}):\n{traceback.format_exc()}"
327
+ )
328
+ return []
329
+
330
+ return metrics_buffer
331
+
332
+
333
+ def run_eval_worker_paraformer(data_chunk, batch_size):
334
+ """
335
+ Worker function for Chinese evaluation using Paraformer.
336
+ Uses the global worker_paraformer initialized by process_init_paraformer.
337
+ """
338
+ global worker_paraformer
339
+ if worker_paraformer is None:
340
+ logging.error("Paraformer worker pipeline is not initialized!")
341
+ return []
342
+
343
+ metrics_buffer = []
344
+ try:
345
+ wav_paths = [item["wav_path"] for item in data_chunk]
346
+
347
+ for i in range(0, len(wav_paths), batch_size):
348
+ batch_paths = wav_paths[i : i + batch_size]
349
+ res_batch = worker_paraformer.generate(
350
+ input=batch_paths, batch_size=batch_size, disable_pbar=True
351
+ )
352
+
353
+ for j, res in enumerate(res_batch):
354
+ hypothesis = res["text"]
355
+ ref_item = data_chunk[i + j]
356
+ truth = ref_item["truth_text"]
357
+ wav_path = ref_item["wav_path"]
358
+ lang_name = ref_item.get("lang_name")
359
+
360
+ m = process_one(hypothesis, truth, post_process, "zh")
361
+ m["wav_path"] = wav_path
362
+ m["lang_name"] = lang_name
363
+ metrics_buffer.append(m)
364
+
365
+ except Exception:
366
+ logging.error(f"Paraformer worker failed on chunk:\n{traceback.format_exc()}")
367
+ return []
368
+
369
+ return metrics_buffer
370
+
371
+
372
+ def main():
373
+ parser = get_parser()
374
+ args = parser.parse_args()
375
+
376
+ logging.basicConfig(
377
+ format="%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s",
378
+ level=logging.INFO,
379
+ force=True,
380
+ )
381
+
382
+ # 1. Prepare Data
383
+ logging.info("Reading test list...")
384
+ data_by_lang = defaultdict(list)
385
+ total_files = 0
386
+ wav_root = Path(args.wav_path)
387
+
388
+ samples = read_test_list(args.test_list)
389
+ for s in samples:
390
+ wav_path = str(wav_root / f"{s['id']}.{args.extension}")
391
+ if not os.path.exists(wav_path):
392
+ logging.warning(f"File missing: {wav_path}")
393
+ continue
394
+
395
+ lang_id = s.get("language_id") or "unknown"
396
+ lang_name = s.get("language_name") or "unknown"
397
+
398
+ item = {
399
+ "wav_path": wav_path,
400
+ "truth_text": s["text"],
401
+ "lang_id": lang_id,
402
+ "lang_name": lang_name,
403
+ }
404
+ if args.lang and s.get("language_id") != args.lang:
405
+ continue
406
+
407
+ data_by_lang[lang_name].append(item)
408
+ total_files += 1
409
+
410
+ logging.info(f"Total files: {total_files} in {len(data_by_lang)} languages.")
411
+
412
+ # 2. Worker config
413
+ num_gpus = torch.cuda.device_count()
414
+ assert num_gpus > 0, "No GPU found. GPU is required."
415
+ total_workers = num_gpus * args.nj_per_gpu
416
+
417
+ mp.set_start_method("spawn", force=True)
418
+ manager = mp.Manager()
419
+
420
+ # 3. Scheduling: Split data into Chinese (Paraformer) and non-Chinese (Whisper)
421
+ zh_items = []
422
+ non_zh_items = []
423
+ for lang_name, items in data_by_lang.items():
424
+ lang_id = items[0].get("lang_id", "") if items else ""
425
+ if lang_name == "Chinese" or (lang_id and lang_id.startswith("zh")):
426
+ zh_items.extend(items)
427
+ else:
428
+ non_zh_items.extend(items)
429
+
430
+ chunk_size = args.chunk_size
431
+
432
+ whisper_tasks = []
433
+ for i in range(0, len(non_zh_items), chunk_size):
434
+ chunk = non_zh_items[i : i + chunk_size]
435
+ lang_name = chunk[0].get("lang_name", "unknown")
436
+ whisper_tasks.append({"chunk": chunk, "lang": lang_name})
437
+
438
+ paraformer_tasks = []
439
+ for i in range(0, len(zh_items), chunk_size):
440
+ paraformer_tasks.append(zh_items[i : i + chunk_size])
441
+
442
+ logging.info(
443
+ f"Whisper tasks: {len(whisper_tasks)} chunks ({len(non_zh_items)} files). "
444
+ f"Paraformer tasks: {len(paraformer_tasks)} chunks ({len(zh_items)} files). "
445
+ f"Spawning {total_workers} workers per pool."
446
+ )
447
+
448
+ # 4. Execution — run Whisper and Paraformer pools sequentially
449
+ results = []
450
+
451
+ # 4a. Whisper pool for non-Chinese languages
452
+ if whisper_tasks:
453
+ whisper_rank_queue = manager.Queue()
454
+ for _ in range(args.nj_per_gpu):
455
+ for rank in range(num_gpus):
456
+ whisper_rank_queue.put(rank)
457
+
458
+ with ProcessPoolExecutor(
459
+ max_workers=total_workers,
460
+ initializer=process_init,
461
+ initargs=(whisper_rank_queue, args.model_dir),
462
+ ) as executor:
463
+
464
+ futures = []
465
+ for task in whisper_tasks:
466
+ futures.append(
467
+ executor.submit(
468
+ run_eval_worker, task["chunk"], task["lang"], args.batch_size
469
+ )
470
+ )
471
+
472
+ with tqdm(
473
+ total=len(non_zh_items),
474
+ desc="Whisper Eval",
475
+ dynamic_ncols=True,
476
+ ) as pbar:
477
+ for future in as_completed(futures):
478
+ try:
479
+ chunk_metrics = future.result()
480
+ results.extend(chunk_metrics)
481
+ pbar.update(len(chunk_metrics))
482
+ except Exception as e:
483
+ logging.error(f"Whisper task failed: {e}")
484
+
485
+ # 4b. Paraformer pool for Chinese
486
+ if paraformer_tasks:
487
+ para_rank_queue = manager.Queue()
488
+ for _ in range(args.nj_per_gpu):
489
+ for rank in range(num_gpus):
490
+ para_rank_queue.put(rank)
491
+
492
+ with ProcessPoolExecutor(
493
+ max_workers=total_workers,
494
+ initializer=process_init_paraformer,
495
+ initargs=(para_rank_queue, args.model_dir),
496
+ ) as executor:
497
+
498
+ futures = []
499
+ for chunk in paraformer_tasks:
500
+ futures.append(
501
+ executor.submit(run_eval_worker_paraformer, chunk, args.batch_size)
502
+ )
503
+
504
+ with tqdm(
505
+ total=len(zh_items),
506
+ desc="Paraformer Eval",
507
+ dynamic_ncols=True,
508
+ ) as pbar:
509
+ for future in as_completed(futures):
510
+ try:
511
+ chunk_metrics = future.result()
512
+ results.extend(chunk_metrics)
513
+ pbar.update(len(chunk_metrics))
514
+ except Exception as e:
515
+ logging.error(f"Paraformer task failed: {e}")
516
+
517
+ # 5. Metrics Aggregation
518
+ wers, inses, deles, subses = [], [], [], []
519
+ word_nums = 0
520
+
521
+ # Store metrics per language
522
+ lang_stats = {}
523
+
524
+ fout = None
525
+ if args.decode_path:
526
+ os.makedirs(os.path.dirname(args.decode_path), exist_ok=True)
527
+ logging.info(f"Saving detailed WER results to: {args.decode_path}")
528
+ fout = open(args.decode_path, "w", encoding="utf-8")
529
+
530
+ for res in results:
531
+ wers.append(float(res["wer"]))
532
+ inses.append(float(res["insertions"]))
533
+ deles.append(float(res["deletions"]))
534
+ subses.append(float(res["substitutions"]))
535
+ word_nums += res["word_num"]
536
+
537
+ if fout:
538
+ fout.write(
539
+ f"{res['wav_path']}\t{res['wer']}\t{res['truth']}\t"
540
+ f"{res['hypo']}\t{res['insertions']}\t{res['deletions']}\t"
541
+ f"{res['substitutions']}\n"
542
+ )
543
+ lang_name = res["lang_name"]
544
+
545
+ # Per language stats
546
+ if lang_name not in lang_stats:
547
+ lang_stats[lang_name] = {
548
+ "inses": [],
549
+ "deles": [],
550
+ "subses": [],
551
+ "word_nums": 0,
552
+ }
553
+ lang_stats[lang_name]["inses"].append(float(res["insertions"]))
554
+ lang_stats[lang_name]["deles"].append(float(res["deletions"]))
555
+ lang_stats[lang_name]["subses"].append(float(res["substitutions"]))
556
+ lang_stats[lang_name]["word_nums"] += res["word_num"]
557
+
558
+ print("-" * 50)
559
+ # Log per-language stats
560
+ per_lang_wers = []
561
+ for lang in sorted(lang_stats.keys()):
562
+ stats = lang_stats[lang]
563
+ if stats["word_nums"] > 0:
564
+ lang_wer = log_metrics(
565
+ fout,
566
+ f"[{lang}]",
567
+ stats["inses"],
568
+ stats["deles"],
569
+ stats["subses"],
570
+ stats["word_nums"],
571
+ ndigits=3,
572
+ )
573
+ per_lang_wers.append(lang_wer)
574
+ print("-" * 50)
575
+
576
+ # Log Macro-average WER
577
+ if len(per_lang_wers) > 1:
578
+ macro_wer = np.mean(per_lang_wers)
579
+ logging.info(
580
+ f"Macro-average WER over {len(per_lang_wers)} languages: {macro_wer:.2f}%"
581
+ )
582
+ if fout:
583
+ fout.write(
584
+ f"Macro-average WER over {len(per_lang_wers)} languages: {macro_wer:.2f}%\n"
585
+ )
586
+
587
+ # Log overall stats
588
+ if word_nums > 0:
589
+ log_metrics(fout, "Overall", inses, deles, subses, word_nums)
590
+
591
+ if fout:
592
+ fout.close()
593
+
594
+
595
+ if __name__ == "__main__":
596
+ main()
omnivoice/eval/wer/norm_config_module.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ """
9
+ This module defines the normalization configuration for WER evaluation.
10
+ Copied from https://github.com/facebookresearch/omnilingual-asr/blob/81f51e224ce9e74b02cc2a3eaf21b2d91d743455/workflows/dataprep/norm_config_module.py
11
+ """
12
+
13
+ # type: ignore
14
+ import os
15
+ import re
16
+
17
+ colon = ":"
18
+ comma = ","
19
+ exclamation_mark = "!"
20
+ period = re.escape(".")
21
+ question_mark = re.escape("?")
22
+ semicolon = ";"
23
+
24
+ left_curly_bracket = "{"
25
+ right_curly_bracket = "}"
26
+ quotation_mark = '"'
27
+
28
+ basic_punc = (
29
+ period
30
+ + question_mark
31
+ + comma
32
+ + colon
33
+ + exclamation_mark
34
+ + left_curly_bracket
35
+ + right_curly_bracket
36
+ )
37
+
38
+ # General punc unicode block (0x2000-0x206F)
39
+ zero_width_space = r"\u200B"
40
+ zero_width_nonjoiner = r"\u200C"
41
+ left_to_right_mark = r"\u200E"
42
+ right_to_left_mark = r"\u200F"
43
+ left_to_right_embedding = r"\u202A"
44
+ pop_directional_formatting = r"\u202C"
45
+
46
+ # Here are some commonly ill-typed versions of apostrophe
47
+ right_single_quotation_mark = r"\u2019"
48
+ left_single_quotation_mark = r"\u2018"
49
+
50
+ # Language specific definitions
51
+ # Spanish
52
+ inverted_exclamation_mark = r"\u00A1"
53
+ inverted_question_mark = r"\u00BF"
54
+
55
+
56
+ # Hindi
57
+ hindi_danda = "\u0964"
58
+
59
+ # Egyptian Arabic
60
+ # arabic_percent = r"\u066A"
61
+ arabic_comma = r"\u060C"
62
+ arabic_question_mark = r"\u061F"
63
+ arabic_semicolon = r"\u061B"
64
+ arabic_diacritics = r"\u064B-\u0652"
65
+
66
+
67
+ arabic_subscript_alef_and_inverted_damma = r"\u0656-\u0657"
68
+
69
+
70
+ # Chinese
71
+ full_stop = r"\u3002"
72
+ full_comma = r"\uFF0C"
73
+ full_exclamation_mark = r"\uFF01"
74
+ full_question_mark = r"\uFF1F"
75
+ full_semicolon = r"\uFF1B"
76
+ full_colon = r"\uFF1A"
77
+ full_parentheses = r"\uFF08\uFF09"
78
+ quotation_mark_horizontal = r"\u300C-\u300F"
79
+ quotation_mark_vertical = r"\uFF41-\uFF44"
80
+ title_marks = r"\u3008-\u300B"
81
+ wavy_low_line = r"\uFE4F"
82
+ ellipsis = r"\u22EF"
83
+ enumeration_comma = r"\u3001"
84
+ hyphenation_point = r"\u2027"
85
+ forward_slash = r"\uFF0F"
86
+ wavy_dash = r"\uFF5E"
87
+ box_drawings_light_horizontal = r"\u2500"
88
+ fullwidth_low_line = r"\uFF3F"
89
+ chinese_punc = (
90
+ full_stop
91
+ + full_comma
92
+ + full_exclamation_mark
93
+ + full_question_mark
94
+ + full_semicolon
95
+ + full_colon
96
+ + full_parentheses
97
+ + quotation_mark_horizontal
98
+ + quotation_mark_vertical
99
+ + title_marks
100
+ + wavy_low_line
101
+ + ellipsis
102
+ + enumeration_comma
103
+ + hyphenation_point
104
+ + forward_slash
105
+ + wavy_dash
106
+ + box_drawings_light_horizontal
107
+ + fullwidth_low_line
108
+ )
109
+
110
+ # Armenian
111
+ armenian_apostrophe = r"\u055A"
112
+ emphasis_mark = r"\u055B"
113
+ exclamation_mark = r"\u055C"
114
+ armenian_comma = r"\u055D"
115
+ armenian_question_mark = r"\u055E"
116
+ abbreviation_mark = r"\u055F"
117
+ armenian_full_stop = r"\u0589"
118
+ armenian_punc = (
119
+ armenian_apostrophe
120
+ + emphasis_mark
121
+ + exclamation_mark
122
+ + armenian_comma
123
+ + armenian_question_mark
124
+ + abbreviation_mark
125
+ + armenian_full_stop
126
+ )
127
+
128
+ lesser_than_symbol = r"&lt;"
129
+ greater_than_symbol = r"&gt;"
130
+
131
+ lesser_than_sign = r"\u003c"
132
+ greater_than_sign = r"\u003e"
133
+
134
+ nbsp_written_form = r"&nbsp"
135
+
136
+ # Quotation marks
137
+ left_double_quotes = r"\u201c"
138
+ right_double_quotes = r"\u201d"
139
+ left_double_angle = r"\u00ab"
140
+ right_double_angle = r"\u00bb"
141
+ left_single_angle = r"\u2039"
142
+ right_single_angle = r"\u203a"
143
+ low_double_quotes = r"\u201e"
144
+ low_single_quotes = r"\u201a"
145
+ high_double_quotes = r"\u201f"
146
+ high_single_quotes = r"\u201b"
147
+
148
+ all_punct_quotes = (
149
+ left_double_quotes
150
+ + right_double_quotes
151
+ + left_double_angle
152
+ + right_double_angle
153
+ + left_single_angle
154
+ + right_single_angle
155
+ + low_double_quotes
156
+ + low_single_quotes
157
+ + high_double_quotes
158
+ + high_single_quotes
159
+ + right_single_quotation_mark
160
+ + left_single_quotation_mark
161
+ )
162
+ mapping_quotes = (
163
+ "["
164
+ + high_single_quotes
165
+ + right_single_quotation_mark
166
+ + left_single_quotation_mark
167
+ + "]"
168
+ )
169
+
170
+
171
+ # Digits
172
+
173
+ english_digits = r"\u0030-\u0039"
174
+ bengali_digits = r"\u09e6-\u09ef"
175
+ khmer_digits = r"\u17e0-\u17e9"
176
+ devanagari_digits = r"\u0966-\u096f"
177
+ oriya_digits = r"\u0b66-\u0b6f"
178
+ extended_arabic_indic_digits = r"\u06f0-\u06f9"
179
+ kayah_li_digits = r"\ua900-\ua909"
180
+ fullwidth_digits = r"\uff10-\uff19"
181
+ malayam_digits = r"\u0d66-\u0d6f"
182
+ myanmar_digits = r"\u1040-\u1049"
183
+ roman_numeral = r"\u2170-\u2179"
184
+ nominal_digit_shapes = r"\u206f"
185
+
186
+ # Load punctuations
187
+ with open(f"{os.path.dirname(__file__)}/punctuations.lst", "r") as punc_f:
188
+ punc_list = [
189
+ line
190
+ for line in punc_f.readlines()
191
+ if line.strip() and not line.strip().startswith("#")
192
+ ]
193
+
194
+ punct_pattern = r""
195
+ for punc in punc_list:
196
+ # the first character in the tab separated line is the punc to be removed
197
+ punct_pattern += re.escape(punc.split("\t")[0])
198
+
199
+ shared_digits = (
200
+ english_digits
201
+ + bengali_digits
202
+ + khmer_digits
203
+ + devanagari_digits
204
+ + oriya_digits
205
+ + extended_arabic_indic_digits
206
+ + kayah_li_digits
207
+ + fullwidth_digits
208
+ + malayam_digits
209
+ + myanmar_digits
210
+ + roman_numeral
211
+ + nominal_digit_shapes
212
+ )
213
+
214
+ shared_punc_list = (
215
+ basic_punc
216
+ + all_punct_quotes
217
+ + greater_than_sign
218
+ + lesser_than_sign
219
+ + inverted_question_mark
220
+ + full_stop
221
+ + semicolon
222
+ + armenian_punc
223
+ + inverted_exclamation_mark
224
+ + arabic_comma
225
+ + enumeration_comma
226
+ + hindi_danda
227
+ + quotation_mark
228
+ + arabic_semicolon
229
+ + arabic_question_mark
230
+ + chinese_punc
231
+ + punct_pattern
232
+ )
233
+
234
+ shared_mappping = {
235
+ lesser_than_symbol: "",
236
+ greater_than_symbol: "",
237
+ nbsp_written_form: "",
238
+ r"(\S+)" + mapping_quotes + r"(\S+)": r"\1'\2",
239
+ }
240
+
241
+ shared_deletion_list = (
242
+ left_to_right_mark
243
+ + zero_width_nonjoiner
244
+ + arabic_subscript_alef_and_inverted_damma
245
+ + zero_width_space
246
+ + arabic_diacritics
247
+ + pop_directional_formatting
248
+ + right_to_left_mark
249
+ + left_to_right_embedding
250
+ )
251
+
252
+ norm_config = {
253
+ "*": {
254
+ "lower_case": True,
255
+ "punc_set": shared_punc_list,
256
+ "del_set": shared_deletion_list,
257
+ "mapping": shared_mappping,
258
+ "digit_set": shared_digits,
259
+ "unicode_norm": "NFKC",
260
+ "rm_diacritics": False,
261
+ }
262
+ }
263
+
264
+ # =============== Mongolian ===============#
265
+
266
+ norm_config["mon"] = norm_config["*"].copy()
267
+ # add soft hyphen to punc list to match with fleurs
268
+ norm_config["mon"]["del_set"] += r"\u00AD"
269
+
270
+ norm_config["khk"] = norm_config["mon"].copy()
271
+
272
+ # =============== Hebrew ===============#
273
+
274
+ norm_config["heb"] = norm_config["*"].copy()
275
+ # add "HEBREW POINT" symbols to match with fleurs
276
+ norm_config["heb"]["del_set"] += r"\u05B0-\u05BF\u05C0-\u05CF"
277
+
278
+ # =============== Thai ===============#
279
+
280
+ norm_config["tha"] = norm_config["*"].copy()
281
+ # add "Zero width joiner" symbols to match with fleurs
282
+ norm_config["tha"]["punc_set"] += r"\u200D"
283
+
284
+ # =============== Arabic ===============#
285
+ norm_config["ara"] = norm_config["*"].copy()
286
+ norm_config["ara"]["mapping"]["ٱ"] = "ا"
287
+ norm_config["arb"] = norm_config["ara"].copy()
288
+
289
+ # =============== Javanese ===============#
290
+ norm_config["jav"] = norm_config["*"].copy()
291
+ norm_config["jav"]["rm_diacritics"] = True
omnivoice/eval/wer/punctuations.lst ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+  7355 INVALID UNICODE 0x81
2
+  5265 INVALID UNICODE 0x90
3
+  75 INVALID UNICODE 0x8
4
+  31 INVALID UNICODE 0x8d
5
+ ” 3 INVALID UNICODE 0x94
6
+  2 INVALID UNICODE 0x8f
7
+  2 INVALID UNICODE 0x1a
8
+  1 INVALID UNICODE 0x9d
9
+ “ 1 INVALID UNICODE 0x93
10
+ ’ 1 INVALID UNICODE 0x92
11
+  8647 INVALID UNICODE 0xe295
12
+  6650 INVALID UNICODE 0xf21d
13
+  6234 INVALID UNICODE 0xf62d
14
+  4815 INVALID UNICODE 0xf173
15
+  4789 INVALID UNICODE 0xe514
16
+  4409 INVALID UNICODE 0xe293
17
+  3881 INVALID UNICODE 0xf523
18
+  3788 INVALID UNICODE 0xe233
19
+  2448 INVALID UNICODE 0xf50f
20
+  2177 INVALID UNICODE 0xe232
21
+  1955 INVALID UNICODE 0xea7b
22
+  1926 INVALID UNICODE 0xf172
23
+  973 INVALID UNICODE 0xe290
24
+  972 INVALID UNICODE 0xf519
25
+  661 INVALID UNICODE 0xe292
26
+  591 INVALID UNICODE 0xe328
27
+  509 INVALID UNICODE 0xe2fa
28
+  458 INVALID UNICODE 0xe234
29
+  446 INVALID UNICODE 0xe043
30
+  419 INVALID UNICODE 0xe040
31
+  399 INVALID UNICODE 0xe2fb
32
+  387 INVALID UNICODE 0xe32b
33
+  381 INVALID UNICODE 0xe236
34
+  374 INVALID UNICODE 0xf511
35
+  314 INVALID UNICODE 0xe517
36
+  296 INVALID UNICODE 0xe2fe
37
+  293 INVALID UNICODE 0xe492
38
+  291 INVALID UNICODE 0xf52d
39
+  289 INVALID UNICODE 0xe2fc
40
+  195 INVALID UNICODE 0xf521
41
+  190 INVALID UNICODE 0xe516
42
+  182 INVALID UNICODE 0xe041
43
+  178 INVALID UNICODE 0xf529
44
+  113 INVALID UNICODE 0xe2f9
45
+  87 INVALID UNICODE 0xe2d9
46
+  78 INVALID UNICODE 0xe32a
47
+  76 INVALID UNICODE 0xe291
48
+  74 INVALID UNICODE 0xe296
49
+  66 INVALID UNICODE 0xe518
50
+  52 INVALID UNICODE 0xe32c
51
+  46 INVALID UNICODE 0xe2db
52
+  41 INVALID UNICODE 0xe231
53
+  34 INVALID UNICODE 0xf522
54
+  33 INVALID UNICODE 0xf518
55
+  32 INVALID UNICODE 0xf513
56
+  27 INVALID UNICODE 0xe32d
57
+  25 INVALID UNICODE 0xe32e
58
+  23 INVALID UNICODE 0xe06b
59
+  15 INVALID UNICODE 0xea01
60
+  12 INVALID UNICODE 0xe294
61
+  11 INVALID UNICODE 0xe203
62
+  8 INVALID UNICODE 0xf218
63
+  7 INVALID UNICODE 0xe070
64
+  7 INVALID UNICODE 0xe013
65
+  5 INVALID UNICODE 0xe2de
66
+  4 INVALID UNICODE 0xe493
67
+  3 INVALID UNICODE 0xf7e8
68
+  3 INVALID UNICODE 0xf7d0
69
+  3 INVALID UNICODE 0xe313
70
+  2 INVALID UNICODE 0xe329
71
+  2 INVALID UNICODE 0xe06d
72
+  2 INVALID UNICODE 0xe003
73
+  1 INVALID UNICODE 0xf50e
74
+  1 INVALID UNICODE 0xf171
75
+  1 INVALID UNICODE 0xe01d
76
+  71 NOMINAL DIGIT SHAPES 0x206f
77
+ ⁠ 3 WORD JOINER 0x2060
78
+ ― 126545 HORIZONTAL BAR 0x2015
79
+ ־ 1028 HEBREW PUNCTUATION MAQAF 0x5be
80
+ ) 98429 RIGHT PARENTHESIS 0x29
81
+ ] 27108 RIGHT SQUARE BRACKET 0x5d
82
+ ⌋ 1567 RIGHT FLOOR 0x230b
83
+ 〕 97 RIGHT TORTOISE SHELL BRACKET 0x3015
84
+ 】 36 RIGHT BLACK LENTICULAR BRACKET 0x3011
85
+ ﴾ 14 ORNATE LEFT PARENTHESIS 0xfd3e
86
+ & 170517 AMPERSAND 0x26
87
+ ། 106330 TIBETAN MARK SHAD 0xf0d
88
+ ። 90203 ETHIOPIC FULL STOP 0x1362
89
+ ፥ 60484 ETHIOPIC COLON 0x1365
90
+ ༌ 60464 TIBETAN MARK DELIMITER TSHEG BSTAR 0xf0c
91
+ ။ 51567 MYANMAR SIGN SECTION 0x104b
92
+ / 46929 SOLIDUS 0x2f
93
+ ၊ 38042 MYANMAR SIGN LITTLE SECTION 0x104a
94
+ · 37985 MIDDLE DOT 0xb7
95
+ ‸ 36310 CARET 0x2038
96
+ * 34793 ASTERISK 0x2a
97
+ ۔ 32432 ARABIC FULL STOP 0x6d4
98
+ ፤ 31906 ETHIOPIC SEMICOLON 0x1364
99
+ ၏ 21519 MYANMAR SYMBOL GENITIVE 0x104f
100
+ ។ 20834 KHMER SIGN KHAN 0x17d4
101
+ ꓾ 15773 LISU PUNCTUATION COMMA 0xa4fe
102
+ ᙮ 13473 CANADIAN SYLLABICS FULL STOP 0x166e
103
+ ꤯ 12892 KAYAH LI SIGN SHYA 0xa92f
104
+ ⵰ 11478 TIFINAGH SEPARATOR MARK 0x2d70
105
+ ꓿ 11118 LISU PUNCTUATION FULL STOP 0xa4ff
106
+ ॥ 10763 DEVANAGARI DOUBLE DANDA 0x965
107
+ ؞ 10403 ARABIC TRIPLE DOT PUNCTUATION MARK 0x61e
108
+ ၍ 8936 MYANMAR SYMBOL COMPLETED 0x104d
109
+ · 8431 GREEK ANO TELEIA 0x387
110
+ † 7477 DAGGER 0x2020
111
+ ၌ 6632 MYANMAR SYMBOL LOCATIVE 0x104c
112
+ ፣ 5719 ETHIOPIC COMMA 0x1363
113
+ ៖ 5528 KHMER SIGN CAMNUC PII KUUH 0x17d6
114
+ ꤮ 4791 KAYAH LI SIGN CWI 0xa92e
115
+ ※ 3439 REFERENCE MARK 0x203b
116
+ ፦ 2727 ETHIOPIC PREFACE COLON 0x1366
117
+ • 1749 BULLET 0x2022
118
+ ¶ 1507 PILCROW SIGN 0xb6
119
+ ၎ 1386 MYANMAR SYMBOL AFOREMENTIONED 0x104e
120
+ ﹖ 1224 SMALL QUESTION MARK 0xfe56
121
+ ; 975 GREEK QUESTION MARK 0x37e
122
+ … 827 HORIZONTAL ELLIPSIS 0x2026
123
+ % 617 PERCENT SIGN 0x25
124
+ ・ 468 KATAKANA MIDDLE DOT 0x30fb
125
+ ༎ 306 TIBETAN MARK NYIS SHAD 0xf0e
126
+ ‡ 140 DOUBLE DAGGER 0x2021
127
+ # 137 NUMBER SIGN 0x23
128
+ @ 125 COMMERCIAL AT 0x40
129
+ ፡ 121 ETHIOPIC WORDSPACE 0x1361
130
+ ៚ 55 KHMER SIGN KOOMUUT 0x17da
131
+ ៕ 49 KHMER SIGN BARIYOOSAN 0x17d5
132
+ ﹐ 10 SMALL COMMA 0xfe50
133
+ ༅ 6 TIBETAN MARK CLOSING YIG MGO SGAB MA 0xf05
134
+ ༄ 6 TIBETAN MARK INITIAL YIG MGO MDUN MA 0xf04
135
+ . 2 FULLWIDTH FULL STOP 0xff0e
136
+ ﹗ 2 SMALL EXCLAMATION MARK 0xfe57
137
+ ﹕ 2 SMALL COLON 0xfe55
138
+ ‰ 2 PER MILLE SIGN 0x2030
139
+ ・ 1 HALFWIDTH KATAKANA MIDDLE DOT 0xff65
140
+ ( 98504 LEFT PARENTHESIS 0x28
141
+ [ 27245 LEFT SQUARE BRACKET 0x5b
142
+ ⌊ 1567 LEFT FLOOR 0x230a
143
+ 〔 95 LEFT TORTOISE SHELL BRACKET 0x3014
144
+ 【 36 LEFT BLACK LENTICULAR BRACKET 0x3010
145
+ ﴿ 14 ORNATE RIGHT PARENTHESIS 0xfd3f
146
+ _ 4851 LOW LINE 0x5f
147
+ $ 72 DOLLAR SIGN 0x24
148
+ € 14 EURO SIGN 0x20ac
149
+ £ 2 POUND SIGN 0xa3
150
+ ~ 27462 TILDE 0x7e
151
+ = 11450 EQUALS SIGN 0x3d
152
+ | 8430 VERTICAL LINE 0x7c
153
+ − 3971 MINUS SIGN 0x2212
154
+ ≫ 1904 MUCH GREATER-THAN 0x226b
155
+ ≪ 1903 MUCH LESS-THAN 0x226a
156
+ + 1450 PLUS SIGN 0x2b
157
+ < 345 FULLWIDTH LESS-THAN SIGN 0xff1c
158
+ > 344 FULLWIDTH GREATER-THAN SIGN 0xff1e
159
+ ¬ 5 NOT SIGN 0xac
160
+ × 4 MULTIPLICATION SIGN 0xd7
161
+ → 2 RIGHTWARDS ARROW 0x2192
162
+ ᙭ 537 CANADIAN SYLLABICS CHI SIGN 0x166d
163
+ ° 499 DEGREE SIGN 0xb0
164
+ ႟ 421 MYANMAR SYMBOL SHAN EXCLAMATION 0x109f
165
+ � 192 REPLACEMENT CHARACTER 0xfffd
166
+ ⌟ 54 BOTTOM RIGHT CORNER 0x231f
167
+ ⌞ 54 BOTTOM LEFT CORNER 0x231e
168
+ © 2 COPYRIGHT SIGN 0xa9
169
+   40 NARROW NO-BREAK SPACE 0x202f
170
+   1 SIX-PER-EM SPACE 0x2006
171
+ ˜ 40261 SMALL TILDE 0x2dc
172
+ ^ 6469 CIRCUMFLEX ACCENT 0x5e
173
+ ¯ 20 MACRON 0xaf
174
+ ˇ 191442 CARON 0x2c7
175
+ ⁿ 38144 SUPERSCRIPT LATIN SMALL LETTER N 0x207f
176
+ ـ 9440 ARABIC TATWEEL 0x640
177
+ ๆ 6766 THAI CHARACTER MAIYAMOK 0xe46
178
+ ៗ 3310 KHMER SIGN LEK TOO 0x17d7
179
+ 々 678 IDEOGRAPHIC ITERATION MARK 0x3005
180
+ ໆ 430 LAO KO LA 0xec6
181
+ ー 319 KATAKANA-HIRAGANA PROLONGED SOUND MARK 0x30fc
182
+ ⁱ 137 SUPERSCRIPT LATIN SMALL LETTER I 0x2071
183
+ ৷ 11056 BENGALI CURRENCY NUMERATOR FOUR 0x9f7
184
+ ⅓ 26 VULGAR FRACTION ONE THIRD 0x2153
185
+ ½ 26 VULGAR FRACTION ONE HALF 0xbd
186
+ ¼ 4 VULGAR FRACTION ONE QUARTER 0xbc
187
+ ⅟ 1 FRACTION NUMERATOR ONE 0x215f
188
+ ⁄ 57 FRACTION SLASH 0x2044
omnivoice/eval/wer/seedtts.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """
19
+ Computes word error rate (WER) with Whisper-large-v3 for English and
20
+ Paraformer for Chinese. Intended to evaluate WERs on Seed-TTS test sets.
21
+ """
22
+ import argparse
23
+ import logging
24
+ import multiprocessing as mp
25
+ import os
26
+ import string
27
+ import traceback
28
+ from concurrent.futures import ProcessPoolExecutor, as_completed
29
+ from pathlib import Path
30
+
31
+ import numpy as np
32
+ import torch
33
+ import zhconv
34
+ from tqdm import tqdm
35
+ from zhon.hanzi import punctuation
36
+
37
+ from omnivoice.eval.utils import load_eval_waveform
38
+ from omnivoice.eval.wer.common import process_one
39
+ from omnivoice.utils.data_utils import read_test_list
40
+
41
+ # --- Global variables for worker processes ---
42
+ worker_pipe = None
43
+ worker_device = None
44
+
45
+
46
+ def get_parser():
47
+ parser = argparse.ArgumentParser(
48
+ description="Computes WER with Whisper/Paraformer.",
49
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
50
+ )
51
+ parser.add_argument(
52
+ "--wav-path",
53
+ type=str,
54
+ required=True,
55
+ help="Path to the directory containing speech files.",
56
+ )
57
+ parser.add_argument(
58
+ "--extension",
59
+ type=str,
60
+ default="wav",
61
+ help="Extension of the speech files. Default: wav",
62
+ )
63
+ parser.add_argument(
64
+ "--decode-path",
65
+ type=str,
66
+ default=None,
67
+ help="Path to the output file where WER information will be saved. "
68
+ "If not provided, results are only printed to console.",
69
+ )
70
+ parser.add_argument(
71
+ "--model-dir",
72
+ type=str,
73
+ required=True,
74
+ help="Local path of evaluation models repository. "
75
+ "Download from https://huggingface.co/k2-fsa/TTS_eval_models. "
76
+ "This script expects 'tts_eval_models/wer/whisper-large-v3/' for English "
77
+ "and 'tts_eval_models/wer/paraformer-zh/' for Chinese within this directory.",
78
+ )
79
+ parser.add_argument(
80
+ "--test-list",
81
+ type=str,
82
+ default="test.jsonl",
83
+ help="path of the JSONL test list. Each line is a JSON object "
84
+ "with fields: id, text, ref_audio, ref_text, language_id, language_name.",
85
+ )
86
+ parser.add_argument(
87
+ "--lang",
88
+ type=str,
89
+ choices=["zh", "en"],
90
+ required=True,
91
+ help="Language of the audio and transcripts for "
92
+ "decoding ('zh' for Chinese or 'en' for English).",
93
+ )
94
+ parser.add_argument(
95
+ "--batch-size",
96
+ type=int,
97
+ default=16,
98
+ help="Batch size for decoding with the Hugging Face pipeline.",
99
+ )
100
+ parser.add_argument(
101
+ "--nj-per-gpu", type=int, default=1, help="Number of workers per GPU."
102
+ )
103
+ return parser
104
+
105
+
106
+ def load_whisper_model(model_dir, device):
107
+ model_path = os.path.join(model_dir, "wer/whisper-large-v3/")
108
+ if not os.path.exists(model_path):
109
+ logging.error(f"Whisper model not found at {model_path}.")
110
+ return None
111
+
112
+ logging.debug(f"Loading Whisper model on {device}...")
113
+
114
+ import transformers
115
+
116
+ # Suppress transformers logging
117
+ transformers.logging.set_verbosity_error()
118
+
119
+ pipe = transformers.pipeline(
120
+ "automatic-speech-recognition",
121
+ model=model_path,
122
+ dtype=torch.float16 if "cuda" in str(device) else torch.float32,
123
+ device=device,
124
+ )
125
+ return pipe
126
+
127
+
128
+ def load_paraformer_model(model_dir, device):
129
+ model_path = os.path.join(model_dir, "wer/paraformer-zh/")
130
+ if not os.path.exists(model_path):
131
+ logging.error(f"Paraformer model not found at {model_path}.")
132
+ return None
133
+
134
+ logging.debug(f"Loading Paraformer model on {device}...")
135
+
136
+ previous_level = logging.root.manager.disable
137
+ logging.disable(logging.CRITICAL)
138
+
139
+ try:
140
+ from funasr import AutoModel
141
+
142
+ # FunASR AutoModel accepts "cuda:0" string or torch.device
143
+ model = AutoModel(
144
+ model=model_path,
145
+ device=str(device),
146
+ disable_update=True,
147
+ disable_pbar=True,
148
+ verbose=False,
149
+ )
150
+ finally:
151
+ logging.disable(previous_level)
152
+
153
+ return model
154
+
155
+
156
+ def post_process(text: str, lang: str) -> str:
157
+ """
158
+ Cleans and normalizes text for WER calculation.
159
+ Args:
160
+ text (str): The input text to be processed.
161
+ lang (str): The language of the input text.
162
+
163
+ Returns:
164
+ str: The cleaned and normalized text.
165
+ """
166
+ punctuation_all = punctuation + string.punctuation
167
+ for x in punctuation_all:
168
+ if x == "'":
169
+ continue
170
+ text = text.replace(x, "")
171
+
172
+ text = text.replace(" ", " ")
173
+
174
+ if lang == "zh":
175
+ text = " ".join([x for x in text])
176
+ elif lang == "en":
177
+ text = text.lower()
178
+ else:
179
+ raise NotImplementedError
180
+ return text
181
+
182
+
183
+ def process_init(rank_queue, model_dir, lang):
184
+ """
185
+ Initializer for each worker process.
186
+ Loads model onto a specific GPU, once per process.
187
+ """
188
+ global worker_pipe, worker_device
189
+
190
+ torch.set_num_threads(2)
191
+
192
+ try:
193
+ rank = rank_queue.get(timeout=10)
194
+ except Exception:
195
+ raise RuntimeError("Failed to get GPU rank from queue.")
196
+
197
+ assert torch.cuda.is_available(), "CUDA is required but not available."
198
+ worker_device = torch.device(f"cuda:{rank}")
199
+ torch.cuda.set_device(rank)
200
+
201
+ logging.info(f"Initializing worker on device: {worker_device}")
202
+
203
+ try:
204
+ if lang == "en":
205
+ worker_pipe = load_whisper_model(model_dir, worker_device)
206
+ elif lang == "zh":
207
+ worker_pipe = load_paraformer_model(model_dir, worker_device)
208
+ if worker_pipe is None:
209
+ raise RuntimeError("Model loading failed.")
210
+ except Exception as e:
211
+ logging.critical(f"Failed to load model on {worker_device}: {e}")
212
+ raise e
213
+
214
+
215
+ def run_eval_worker(data_chunk, lang, batch_size):
216
+ """
217
+ Worker function to process a chunk of data.
218
+ Uses the global worker_pipe initialized by process_init.
219
+ """
220
+ global worker_pipe
221
+ if worker_pipe is None:
222
+ logging.error("Worker pipeline is not initialized!")
223
+ return []
224
+
225
+ metrics_buffer = []
226
+ try:
227
+ if lang == "en":
228
+ # Load waveforms as arrays, truncating to 30s
229
+ dataset = [
230
+ {
231
+ "array": load_eval_waveform(
232
+ item["wav_path"], sample_rate=16000, return_numpy=True
233
+ )[: 16000 * 30],
234
+ "sampling_rate": 16000,
235
+ }
236
+ for item in data_chunk
237
+ ]
238
+ generate_kwargs = {"language": "english", "task": "transcribe"}
239
+
240
+ iterator = worker_pipe(
241
+ dataset, generate_kwargs=generate_kwargs, batch_size=batch_size
242
+ )
243
+
244
+ for i, out in enumerate(iterator):
245
+ hypothesis = out["text"].strip()
246
+ ref_item = data_chunk[i]
247
+ truth = ref_item["truth_text"]
248
+ wav_path = ref_item["wav_path"]
249
+
250
+ m = process_one(hypothesis, truth, post_process, lang)
251
+ m["wav_path"] = wav_path
252
+ metrics_buffer.append(m)
253
+
254
+ elif lang == "zh":
255
+ wav_paths = [item["wav_path"] for item in data_chunk]
256
+
257
+ for i in range(0, len(wav_paths), batch_size):
258
+ batch_paths = wav_paths[i : i + batch_size]
259
+ res_batch = worker_pipe.generate(
260
+ input=batch_paths, batch_size=batch_size, disable_pbar=True
261
+ )
262
+
263
+ for j, res in enumerate(res_batch):
264
+ hypothesis = zhconv.convert(res["text"], "zh-cn")
265
+ ref_item = data_chunk[i + j]
266
+ truth = ref_item["truth_text"]
267
+ wav_path = ref_item["wav_path"]
268
+
269
+ m = process_one(hypothesis, truth, post_process, lang)
270
+ m["wav_path"] = wav_path
271
+ metrics_buffer.append(m)
272
+
273
+ except Exception:
274
+ logging.error(
275
+ f"Worker failed on chunk (Lang: {lang}):\n{traceback.format_exc()}"
276
+ )
277
+ return []
278
+
279
+ return metrics_buffer
280
+
281
+
282
+ def main():
283
+ parser = get_parser()
284
+ args = parser.parse_args()
285
+
286
+ logging.basicConfig(
287
+ format="%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s",
288
+ level=logging.INFO,
289
+ force=True,
290
+ )
291
+
292
+ logging.info(f"Calculating WER for {args.wav_path}")
293
+
294
+ # 1. Prepare Data
295
+ logging.info("Reading test list...")
296
+ data_list = []
297
+ samples = read_test_list(args.test_list)
298
+ for s in samples:
299
+ wav_path = str(Path(args.wav_path) / f"{s['id']}.{args.extension}")
300
+ if not os.path.exists(wav_path):
301
+ logging.warning(f"File missing: {wav_path}")
302
+ continue
303
+ data_list.append({"wav_path": wav_path, "truth_text": s["text"]})
304
+ total_files = len(data_list)
305
+ logging.info(f"Total files: {total_files}.")
306
+
307
+ # 2. Worker config
308
+ num_gpus = torch.cuda.device_count()
309
+ assert num_gpus > 0, "No GPU found. GPU is required."
310
+ total_workers = num_gpus * args.nj_per_gpu
311
+
312
+ mp.set_start_method("spawn", force=True)
313
+ manager = mp.Manager()
314
+ rank_queue = manager.Queue()
315
+
316
+ for _ in range(args.nj_per_gpu):
317
+ for rank in range(num_gpus):
318
+ rank_queue.put(rank)
319
+
320
+ # 3. Scheduling: Split data into chunks for better load balancing
321
+ chunk_size = max(1, args.batch_size)
322
+ tasks = []
323
+ for i in range(0, total_files, chunk_size):
324
+ tasks.append(data_list[i : i + chunk_size])
325
+
326
+ logging.info(
327
+ f"Split data into {len(tasks)} chunks (size ~{chunk_size}). "
328
+ f"Spawning {total_workers} workers."
329
+ )
330
+
331
+ # 4. Execution
332
+ results = []
333
+
334
+ with ProcessPoolExecutor(
335
+ max_workers=total_workers,
336
+ initializer=process_init,
337
+ initargs=(rank_queue, args.model_dir, args.lang),
338
+ ) as executor:
339
+
340
+ futures = []
341
+ for chunk in tasks:
342
+ futures.append(
343
+ executor.submit(run_eval_worker, chunk, args.lang, args.batch_size)
344
+ )
345
+
346
+ # Unified progress bar
347
+ with tqdm(total=total_files, desc="Eval Progress", dynamic_ncols=True) as pbar:
348
+ for future in as_completed(futures):
349
+ try:
350
+ chunk_metrics = future.result()
351
+ results.extend(chunk_metrics)
352
+ pbar.update(len(chunk_metrics))
353
+ except Exception as e:
354
+ logging.error(f"Task failed: {e}")
355
+
356
+ wers, inses, deles, subses = [], [], [], []
357
+ word_nums = 0
358
+
359
+ fout = None
360
+ if args.decode_path:
361
+ os.makedirs(os.path.dirname(args.decode_path), exist_ok=True)
362
+ fout = open(args.decode_path, "w", encoding="utf8")
363
+ logging.info(f"Saving detailed WER results to: {args.decode_path}")
364
+ fout.write(
365
+ "Name\tWER\tTruth\tHypothesis\tInsertions\tDeletions\tSubstitutions\n"
366
+ )
367
+
368
+ for res in results:
369
+ wers.append(float(res["wer"]))
370
+ inses.append(float(res["insertions"]))
371
+ deles.append(float(res["deletions"]))
372
+ subses.append(float(res["substitutions"]))
373
+ word_nums += res["word_num"]
374
+
375
+ if fout:
376
+ fout.write(
377
+ f"{res['wav_path']}\t{res['wer']}\t{res['truth']}\t"
378
+ f"{res['hypo']}\t{res['insertions']}\t{res['deletions']}\t"
379
+ f"{res['substitutions']}\n"
380
+ )
381
+
382
+ wer_avg = round(np.mean(wers) * 100, 2) if wers else float("nan")
383
+ wer_weighted = (
384
+ round(
385
+ (np.sum(subses) + np.sum(deles) + np.sum(inses)) / word_nums * 100, 2
386
+ )
387
+ if word_nums > 0
388
+ else float("nan")
389
+ )
390
+
391
+ inse_sum = np.sum(inses)
392
+ dele_sum = np.sum(deles)
393
+ subs_sum = np.sum(subses)
394
+
395
+ print("-" * 50)
396
+ logging.info(f"Processed {len(results)}/{total_files} files.")
397
+ seedtts_wer_info = f"Seed-TTS WER (Avg of WERs): {wer_avg}%"
398
+ wer_info = f"WER (Weighted): {wer_weighted}%"
399
+ detailed_info = (
400
+ f"Errors: {inse_sum} ins, {dele_sum} del, {subs_sum} sub / {word_nums} words"
401
+ )
402
+ logging.info(seedtts_wer_info)
403
+ logging.info(wer_info)
404
+ logging.info(detailed_info)
405
+ print("-" * 50)
406
+
407
+ if fout:
408
+ fout.write(seedtts_wer_info + "\n" + wer_info + "\n" + detailed_info + "\n")
409
+ fout.close()
410
+
411
+
412
+ if __name__ == "__main__":
413
+ main()
omnivoice/eval/wer/sensevoice.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """
19
+ Computes Character Error Rate (CER) for Cantonese (yue) using SenseVoiceSmall.
20
+ """
21
+
22
+ import argparse
23
+ import logging
24
+ import multiprocessing as mp
25
+ import os
26
+ import re
27
+ import traceback
28
+ from concurrent.futures import ProcessPoolExecutor, as_completed
29
+ from pathlib import Path
30
+
31
+ import cn2an
32
+ import torch
33
+ import zhconv
34
+ from tqdm import tqdm
35
+
36
+ from omnivoice.eval.wer.common import log_metrics, process_one
37
+ from omnivoice.eval.wer.text_norm_omni import text_normalize
38
+ from omnivoice.utils.data_utils import read_test_list
39
+
40
+ # --- Global variables for worker processes ---
41
+ worker_sensevoice = None
42
+ worker_device = None
43
+
44
+
45
+ def get_parser():
46
+ parser = argparse.ArgumentParser(
47
+ description="Computes CER for Cantonese using SenseVoiceSmall.",
48
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
49
+ )
50
+
51
+ parser.add_argument(
52
+ "--wav-path",
53
+ type=str,
54
+ required=True,
55
+ help="Path to the directory containing speech files.",
56
+ )
57
+
58
+ parser.add_argument(
59
+ "--extension",
60
+ type=str,
61
+ default="wav",
62
+ help="Extension of the speech files. Default: wav",
63
+ )
64
+
65
+ parser.add_argument(
66
+ "--decode-path",
67
+ type=str,
68
+ default=None,
69
+ help="Path to the output file where CER information will be saved. ",
70
+ )
71
+ parser.add_argument(
72
+ "--model-dir",
73
+ type=str,
74
+ required=True,
75
+ help="Local path of evaluation models repository. ",
76
+ )
77
+ parser.add_argument(
78
+ "--test-list",
79
+ type=str,
80
+ default="test.jsonl",
81
+ help="path of the JSONL test list.",
82
+ )
83
+ parser.add_argument(
84
+ "--batch-size",
85
+ type=int,
86
+ default=16,
87
+ help="Batch size for decoding.",
88
+ )
89
+ parser.add_argument(
90
+ "--nj-per-gpu", type=int, default=1, help="Number of workers per GPU."
91
+ )
92
+ parser.add_argument(
93
+ "--chunk-size",
94
+ type=int,
95
+ default=10,
96
+ help="Number of samples per task chunk sent to workers.",
97
+ )
98
+ return parser
99
+
100
+
101
+ def load_sensevoice_model(model_dir, device):
102
+ model_path = os.path.join(model_dir, "wer/SenseVoiceSmall")
103
+ if not os.path.exists(model_path):
104
+ # Fallback if specific sensevoice spelling isn't found
105
+ logging.warning(
106
+ f"SenseVoiceSmall not found at {model_path}. "
107
+ f"Please ensure it is present in eval models."
108
+ )
109
+
110
+ logging.info(f"Loading SenseVoice model on {device}...")
111
+
112
+ previous_level = logging.root.manager.disable
113
+ logging.disable(logging.CRITICAL)
114
+
115
+ try:
116
+ from funasr import AutoModel
117
+
118
+ model = AutoModel(
119
+ model="iic/SenseVoiceSmall",
120
+ device=str(device),
121
+ disable_update=True,
122
+ disable_pbar=True,
123
+ verbose=False,
124
+ )
125
+ finally:
126
+ logging.disable(previous_level)
127
+
128
+ return model
129
+
130
+
131
+ def _worker_setup(rank_queue):
132
+ global worker_device
133
+
134
+ torch.set_num_threads(2)
135
+
136
+ try:
137
+ rank = rank_queue.get(timeout=10)
138
+ except Exception:
139
+ raise RuntimeError("Failed to get GPU rank from queue.")
140
+
141
+ assert torch.cuda.is_available(), "CUDA is required but not available."
142
+ worker_device = torch.device(f"cuda:{rank}")
143
+ torch.cuda.set_device(rank)
144
+
145
+ logging.info(f"Initializing worker on device: {worker_device}")
146
+
147
+
148
+ def process_init_sensevoice(rank_queue, model_dir):
149
+ global worker_sensevoice
150
+
151
+ _worker_setup(rank_queue)
152
+
153
+ try:
154
+ worker_sensevoice = load_sensevoice_model(model_dir, worker_device)
155
+ if worker_sensevoice is None:
156
+ raise RuntimeError("SenseVoice model loading failed.")
157
+ except Exception as e:
158
+ logging.critical(f"Failed to load SenseVoice model on {worker_device}: {e}")
159
+ raise e
160
+
161
+
162
+ def post_process(text: str, lang: str) -> str:
163
+ """
164
+ Cleans and normalizes text for calculation.
165
+ """
166
+ assert lang == "yue", "this script is designed for Cantonese (yue) evaluation only."
167
+ text = text_normalize(
168
+ text,
169
+ iso_code="yue",
170
+ lower_case=True,
171
+ remove_numbers=False,
172
+ remove_brackets=False,
173
+ )
174
+
175
+ text = zhconv.convert(text, "zh-cn")
176
+
177
+ text = cn2an.transform(text, "an2cn")
178
+
179
+ text = text.replace(" ", "")
180
+ text = " ".join([x for x in text])
181
+ text = text.lower()
182
+ return text.strip()
183
+
184
+
185
+ def run_eval_worker_sensevoice(data_chunk, batch_size):
186
+ global worker_sensevoice
187
+ if worker_sensevoice is None:
188
+ logging.error("SenseVoice worker pipeline is not initialized!")
189
+ return []
190
+
191
+ metrics_buffer = []
192
+ try:
193
+ wav_paths = [item["wav_path"] for item in data_chunk]
194
+
195
+ for i in range(0, len(wav_paths), batch_size):
196
+ batch_paths = wav_paths[i : i + batch_size]
197
+
198
+ # SenseVoice generate call, target lang mapped to yue
199
+ res_batch = worker_sensevoice.generate(
200
+ input=batch_paths,
201
+ batch_size=batch_size,
202
+ language="yue",
203
+ use_itn=False,
204
+ disable_pbar=True,
205
+ )
206
+
207
+ for j, res in enumerate(res_batch):
208
+ hypothesis = res["text"]
209
+ # SenseVoice may format output with language tags,
210
+ # cleaning basic tags if any
211
+ hypothesis = re.sub(r"<\|[^|]*\|>", "", hypothesis).strip()
212
+
213
+ ref_item = data_chunk[i + j]
214
+ truth = ref_item["truth_text"]
215
+ wav_path = ref_item["wav_path"]
216
+ lang_name = ref_item.get("lang_name")
217
+
218
+ m = process_one(hypothesis, truth, post_process, "yue")
219
+ m["wav_path"] = wav_path
220
+ m["lang_name"] = lang_name
221
+ metrics_buffer.append(m)
222
+
223
+ except Exception:
224
+ logging.error(f"SenseVoice worker failed on chunk:\n{traceback.format_exc()}")
225
+ return []
226
+
227
+ return metrics_buffer
228
+
229
+
230
+ def main():
231
+ parser = get_parser()
232
+ args = parser.parse_args()
233
+
234
+ logging.basicConfig(
235
+ format="%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s",
236
+ level=logging.INFO,
237
+ force=True,
238
+ )
239
+
240
+ logging.info("Reading test list and filtering for Cantonese (yue)...")
241
+ yue_items = []
242
+ wav_root = Path(args.wav_path)
243
+
244
+ samples = read_test_list(args.test_list)
245
+ for s in samples:
246
+ lang_id = s.get("language_id", "")
247
+ if lang_id != "yue":
248
+ continue
249
+
250
+ wav_path = str(wav_root / f"{s['id']}.{args.extension}")
251
+ if not os.path.exists(wav_path):
252
+ logging.warning(f"File missing: {wav_path}")
253
+ continue
254
+
255
+ yue_items.append(
256
+ {
257
+ "wav_path": wav_path,
258
+ "truth_text": s["text"],
259
+ "lang_id": "yue",
260
+ "lang_name": s.get("language_name", "Cantonese"),
261
+ }
262
+ )
263
+
264
+ logging.info(f"Total Cantonese files found: {len(yue_items)}.")
265
+ if len(yue_items) == 0:
266
+ logging.warning("No files to evaluate. Exiting.")
267
+ return
268
+
269
+ num_gpus = torch.cuda.device_count()
270
+ assert num_gpus > 0, "No GPU found. GPU is required."
271
+ total_workers = num_gpus * args.nj_per_gpu
272
+
273
+ mp.set_start_method("spawn", force=True)
274
+ manager = mp.Manager()
275
+
276
+ chunk_size = args.chunk_size
277
+ tasks = []
278
+ for i in range(0, len(yue_items), chunk_size):
279
+ tasks.append(yue_items[i : i + chunk_size])
280
+
281
+ results = []
282
+ rank_queue = manager.Queue()
283
+ for _ in range(args.nj_per_gpu):
284
+ for rank in range(num_gpus):
285
+ rank_queue.put(rank)
286
+
287
+ with ProcessPoolExecutor(
288
+ max_workers=total_workers,
289
+ initializer=process_init_sensevoice,
290
+ initargs=(rank_queue, args.model_dir),
291
+ ) as executor:
292
+
293
+ futures = []
294
+ for chunk in tasks:
295
+ futures.append(
296
+ executor.submit(run_eval_worker_sensevoice, chunk, args.batch_size)
297
+ )
298
+
299
+ with tqdm(
300
+ total=len(yue_items),
301
+ desc="SenseVoice Eval (Cantonese)",
302
+ dynamic_ncols=True,
303
+ ) as pbar:
304
+ for future in as_completed(futures):
305
+ try:
306
+ chunk_metrics = future.result()
307
+ results.extend(chunk_metrics)
308
+ pbar.update(len(chunk_metrics))
309
+ except Exception as e:
310
+ logging.error(f"Task failed: {e}")
311
+
312
+ # Metrics Aggregation
313
+ inses, deles, subses = [], [], []
314
+ word_nums = 0
315
+
316
+ fout = None
317
+ if args.decode_path:
318
+ os.makedirs(os.path.dirname(args.decode_path), exist_ok=True)
319
+ logging.info(f"Saving detailed CER results to: {args.decode_path}")
320
+ fout = open(args.decode_path, "w", encoding="utf-8")
321
+
322
+ for res in results:
323
+ inses.append(float(res["insertions"]))
324
+ deles.append(float(res["deletions"]))
325
+ subses.append(float(res["substitutions"]))
326
+ word_nums += res["word_num"]
327
+
328
+ if fout:
329
+ fout.write(
330
+ f"{res['wav_path']}\t{res['wer']}\t{res['truth']}\t"
331
+ f"{res['hypo']}\t{res['insertions']}\t{res['deletions']}\t"
332
+ f"{res['substitutions']}\n"
333
+ )
334
+
335
+ print("-" * 50)
336
+ if word_nums > 0:
337
+ log_metrics(fout, "[yue] Cantonese", inses, deles, subses, word_nums)
338
+
339
+ if fout:
340
+ fout.close()
341
+
342
+
343
+ if __name__ == "__main__":
344
+ main()
omnivoice/eval/wer/text_norm_omni.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the BSD-style license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+
8
+ """
9
+ This module contains the text normalization function for WER evaluation.
10
+ Copied from https://github.com/facebookresearch/omnilingual-asr/blob/81f51e224ce9e74b02cc2a3eaf21b2d91d743455/workflows/dataprep/text_tools.py
11
+ """
12
+
13
+ import re
14
+ import unicodedata
15
+
16
+ from unidecode import unidecode
17
+
18
+ import omnivoice.eval.wer.norm_config_module as norm_config_module
19
+
20
+ norm_config = norm_config_module.norm_config # type: ignore
21
+
22
+
23
+ def text_normalize(
24
+ text, iso_code, lower_case=True, remove_numbers=True, remove_brackets=False
25
+ ):
26
+ """Given a text, normalize it by changing to lower case, removing punctuations, removing words that only contain digits and removing extra spaces
27
+
28
+ Args:
29
+ text : The string to be normalized
30
+ iso_code :
31
+ remove_numbers : Boolean flag to specify if words containing only digits should be removed
32
+
33
+ Returns:
34
+ normalized_text : the string after all normalization
35
+
36
+ """
37
+
38
+ config = norm_config.get(iso_code, norm_config["*"])
39
+
40
+ for field in [
41
+ "lower_case",
42
+ "punc_set",
43
+ "del_set",
44
+ "mapping",
45
+ "digit_set",
46
+ "unicode_norm",
47
+ ]:
48
+ if field not in config:
49
+ config[field] = norm_config["*"][field]
50
+
51
+ text = unicodedata.normalize(config["unicode_norm"], text)
52
+
53
+ # Convert to lower case
54
+
55
+ if config["lower_case"] and lower_case:
56
+ text = text.lower()
57
+
58
+ # brackets
59
+
60
+ # always text inside brackets with numbers in them. Usually corresponds to "(Sam 23:17)"
61
+ text = re.sub(r"\([^\)]*\d[^\)]*\)", " ", text)
62
+ if remove_brackets:
63
+ text = re.sub(r"\([^\)]*\)", " ", text)
64
+
65
+ # Apply mappings
66
+
67
+ for old, new in config["mapping"].items():
68
+ text = re.sub(old, new, text)
69
+
70
+ # Replace punctutations with space
71
+
72
+ punct_pattern = r"[" + config["punc_set"]
73
+
74
+ punct_pattern += "]"
75
+
76
+ normalized_text = re.sub(punct_pattern, " ", text)
77
+
78
+ # remove characters in delete list
79
+
80
+ delete_patten = r"[" + config["del_set"] + "]"
81
+
82
+ normalized_text = re.sub(delete_patten, "", normalized_text)
83
+
84
+ # Remove words containing only digits
85
+ # We check for 3 cases a)text starts with a number b) a number is present somewhere in the middle of the text c) the text ends with a number
86
+ # For each case we use lookaround regex pattern to see if the digit pattern in preceded and followed by whitespaces, only then we replace the numbers with space
87
+ # The lookaround enables overlapping pattern matches to be replaced
88
+
89
+ if remove_numbers:
90
+
91
+ digits_pattern = "[" + config["digit_set"]
92
+
93
+ digits_pattern += "]+"
94
+
95
+ complete_digit_pattern = (
96
+ r"^"
97
+ + digits_pattern
98
+ + r"(?=\s)|(?<=\s)"
99
+ + digits_pattern
100
+ + r"(?=\s)|(?<=\s)"
101
+ + digits_pattern
102
+ + "$"
103
+ )
104
+
105
+ normalized_text = re.sub(complete_digit_pattern, " ", normalized_text)
106
+
107
+ if config["rm_diacritics"]:
108
+ normalized_text = unidecode(normalized_text)
109
+
110
+ # Remove extra spaces
111
+ normalized_text = re.sub(r"\s+", " ", normalized_text).strip()
112
+
113
+ return normalized_text
omnivoice/models/__init__.py ADDED
File without changes
omnivoice/models/omnivoice.py ADDED
@@ -0,0 +1,1598 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Core OmniVoice model implementation.
19
+
20
+ Defines the ``OmniVoice`` model class, generation config, and inference pipeline.
21
+ This is the main entry point for both inference and training:
22
+
23
+ - **Inference**: ``OmniVoice.from_pretrained()`` loads the model, then
24
+ ``model.generate()`` supports voice cloning, voice design, and auto voice.
25
+ - **Training**: ``model.forward()`` computes the training loss; the model is
26
+ built and used by ``omnivoice.training.builder`` and ``omnivoice.training.trainer``.
27
+
28
+ """
29
+
30
+ import difflib
31
+ import logging
32
+ import math
33
+ import os
34
+ import re
35
+ from dataclasses import dataclass, fields
36
+ from functools import partial
37
+ from typing import Any, List, Optional, Union
38
+
39
+ import numpy as np
40
+ import torch
41
+ import torch.nn as nn
42
+ import torch.nn.functional as F
43
+ import torchaudio
44
+
45
+ try:
46
+ from torch.nn.attention.flex_attention import create_block_mask
47
+
48
+ _flex_attention_available = True
49
+ except ImportError:
50
+ _flex_attention_available = False
51
+ from transformers import (
52
+ AutoFeatureExtractor,
53
+ AutoModel,
54
+ AutoTokenizer,
55
+ HiggsAudioV2TokenizerModel,
56
+ PretrainedConfig,
57
+ PreTrainedModel,
58
+ )
59
+ from transformers.modeling_outputs import ModelOutput
60
+ from transformers.models.auto import CONFIG_MAPPING, AutoConfig
61
+
62
+ from omnivoice.utils.audio import (
63
+ cross_fade_chunks,
64
+ fade_and_pad_audio,
65
+ load_audio,
66
+ remove_silence,
67
+ trim_long_audio,
68
+ )
69
+ from omnivoice.utils.duration import RuleDurationEstimator
70
+ from omnivoice.utils.lang_map import LANG_IDS, LANG_NAMES
71
+ from omnivoice.utils.text import add_punctuation, chunk_text_punctuation
72
+ from omnivoice.utils.voice_design import (
73
+ _INSTRUCT_ALL_VALID,
74
+ _INSTRUCT_EN_TO_ZH,
75
+ _INSTRUCT_MUTUALLY_EXCLUSIVE,
76
+ _INSTRUCT_VALID_EN,
77
+ _INSTRUCT_VALID_ZH,
78
+ _INSTRUCT_ZH_TO_EN,
79
+ _ZH_RE,
80
+ )
81
+
82
+ logger = logging.getLogger(__name__)
83
+
84
+
85
+ # ---------------------------------------------------------------------------
86
+ # Dataclasses
87
+ # ---------------------------------------------------------------------------
88
+
89
+
90
+ @dataclass
91
+ class VoiceClonePrompt:
92
+ ref_audio_tokens: torch.Tensor # (C, T)
93
+ ref_text: str
94
+ ref_rms: float
95
+
96
+
97
+ @dataclass
98
+ class OmniVoiceGenerationConfig:
99
+ num_step: int = 32
100
+ guidance_scale: float = 2.0
101
+ t_shift: float = 0.1
102
+ layer_penalty_factor: float = 5.0
103
+ position_temperature: float = 5.0
104
+ class_temperature: float = 0.0
105
+ denoise: bool = True
106
+ preprocess_prompt: bool = True
107
+ postprocess_output: bool = True
108
+ audio_chunk_duration: float = 15.0
109
+ audio_chunk_threshold: float = 30.0
110
+
111
+ @classmethod
112
+ def from_dict(cls, kwargs_dict):
113
+ valid_keys = {f.name for f in fields(cls)}
114
+ filtered = {k: v for k, v in kwargs_dict.items() if k in valid_keys}
115
+ return cls(**filtered)
116
+
117
+
118
+ @dataclass
119
+ class GenerationTask:
120
+ batch_size: int
121
+ texts: List[str]
122
+ target_lens: List[int]
123
+ langs: List[Optional[str]]
124
+ instructs: List[Optional[str]]
125
+ ref_texts: List[Optional[str]]
126
+ ref_audio_tokens: List[Optional[torch.Tensor]]
127
+ ref_rms: List[Optional[float]]
128
+ speed: Optional[List[float]] = None
129
+
130
+ def get_indices(self, config: OmniVoiceGenerationConfig, frame_rate: int):
131
+ threshold = int(config.audio_chunk_threshold * frame_rate)
132
+ short_idx = [i for i, l in enumerate(self.target_lens) if l <= threshold]
133
+ long_idx = [i for i, l in enumerate(self.target_lens) if l > threshold]
134
+ return short_idx, long_idx
135
+
136
+ def slice_task(self, indices: List[int]):
137
+ if not indices:
138
+ return None
139
+ return GenerationTask(
140
+ batch_size=len(indices),
141
+ texts=[self.texts[i] for i in indices],
142
+ target_lens=[self.target_lens[i] for i in indices],
143
+ langs=[self.langs[i] for i in indices],
144
+ instructs=[self.instructs[i] for i in indices],
145
+ ref_texts=[self.ref_texts[i] for i in indices],
146
+ ref_audio_tokens=[self.ref_audio_tokens[i] for i in indices],
147
+ ref_rms=[self.ref_rms[i] for i in indices],
148
+ speed=[self.speed[i] for i in indices] if self.speed else None,
149
+ )
150
+
151
+
152
+ @dataclass
153
+ class OmniVoiceModelOutput(ModelOutput):
154
+ loss: Optional[torch.Tensor] = None
155
+ logits: Optional[torch.Tensor] = None
156
+
157
+
158
+ # ---------------------------------------------------------------------------
159
+ # Config & Model
160
+ # ---------------------------------------------------------------------------
161
+
162
+
163
+ class OmniVoiceConfig(PretrainedConfig):
164
+ model_type = "omnivoice"
165
+ sub_configs = {"llm_config": AutoConfig}
166
+
167
+ def __init__(
168
+ self,
169
+ audio_vocab_size: int = 1025,
170
+ audio_mask_id: int = 1024,
171
+ num_audio_codebook: int = 8,
172
+ audio_codebook_weights: Optional[list[float]] = None,
173
+ llm_config: Optional[Union[dict, PretrainedConfig]] = None,
174
+ **kwargs,
175
+ ):
176
+
177
+ if isinstance(llm_config, dict):
178
+ llm_config = CONFIG_MAPPING[llm_config["model_type"]](**llm_config)
179
+
180
+ self.llm_config = llm_config
181
+
182
+ super().__init__(**kwargs)
183
+ self.audio_vocab_size = audio_vocab_size
184
+ self.audio_mask_id = audio_mask_id
185
+ self.num_audio_codebook = num_audio_codebook
186
+ if audio_codebook_weights is None:
187
+ audio_codebook_weights = [8, 8, 6, 6, 4, 4, 2, 2]
188
+ self.audio_codebook_weights = audio_codebook_weights
189
+
190
+
191
+ def _resolve_model_path(name_or_path: str) -> str:
192
+ if os.path.isdir(name_or_path):
193
+ return name_or_path
194
+ from huggingface_hub import snapshot_download
195
+
196
+ return snapshot_download(name_or_path)
197
+
198
+
199
+ class OmniVoice(PreTrainedModel):
200
+ _supports_flex_attn = True
201
+ _supports_flash_attn_2 = True
202
+ _supports_sdpa = True
203
+ config_class = OmniVoiceConfig
204
+
205
+ def __init__(self, config: OmniVoiceConfig, llm: Optional[PreTrainedModel] = None):
206
+ super().__init__(config)
207
+
208
+ if llm is not None:
209
+ # If an LLM instance is provided, use it directly
210
+ # (skipping config-based init).
211
+ self.llm = llm
212
+ else:
213
+ # Otherwise, initialize the LLM from the config.
214
+ self.llm = AutoModel.from_config(self.config.llm_config)
215
+
216
+ self.audio_embeddings = nn.Embedding(
217
+ config.num_audio_codebook * config.audio_vocab_size,
218
+ self.config.llm_config.hidden_size,
219
+ )
220
+ self.register_buffer(
221
+ "codebook_layer_offsets",
222
+ torch.arange(config.num_audio_codebook) * config.audio_vocab_size,
223
+ )
224
+
225
+ self.audio_heads = nn.Linear(
226
+ self.config.llm_config.hidden_size,
227
+ config.num_audio_codebook * config.audio_vocab_size,
228
+ bias=False,
229
+ )
230
+
231
+ self.normalized_audio_codebook_weights = [
232
+ w / sum(config.audio_codebook_weights)
233
+ for w in config.audio_codebook_weights
234
+ ]
235
+
236
+ self.post_init()
237
+
238
+ # Inference-only attributes (set by from_pretrained when not in train mode)
239
+ self.text_tokenizer = None
240
+ self.audio_tokenizer = None
241
+ self.duration_estimator = None
242
+ self.sampling_rate = None
243
+ self._asr_pipe = None
244
+
245
+ @classmethod
246
+ def from_pretrained(cls, pretrained_model_name_or_path, *args, **kwargs):
247
+ train_mode = kwargs.pop("train", False)
248
+ load_asr = kwargs.pop("load_asr", False)
249
+ asr_model_name = kwargs.pop("asr_model_name", "openai/whisper-large-v3-turbo")
250
+
251
+ # Suppress noisy INFO logs from transformers/huggingface_hub during loading
252
+ _prev_disable = logging.root.manager.disable
253
+ logging.disable(logging.INFO)
254
+
255
+ try:
256
+ # Resolve to local path first; download only if not already cached
257
+ resolved_path = _resolve_model_path(pretrained_model_name_or_path)
258
+
259
+ model = super().from_pretrained(resolved_path, *args, **kwargs)
260
+
261
+ if not train_mode:
262
+ model.text_tokenizer = AutoTokenizer.from_pretrained(resolved_path)
263
+
264
+ audio_tokenizer_path = os.path.join(resolved_path, "audio_tokenizer")
265
+
266
+ if not os.path.isdir(audio_tokenizer_path):
267
+ audio_tokenizer_path = _resolve_model_path(
268
+ "eustlb/higgs-audio-v2-tokenizer"
269
+ )
270
+
271
+ # higgs-audio-v2-tokenizer does not support MPS
272
+ # (output channels > 65536)
273
+ tokenizer_device = (
274
+ "cpu" if str(model.device).startswith("mps") else model.device
275
+ )
276
+ model.audio_tokenizer = HiggsAudioV2TokenizerModel.from_pretrained(
277
+ audio_tokenizer_path, device_map=tokenizer_device
278
+ )
279
+ model.feature_extractor = AutoFeatureExtractor.from_pretrained(
280
+ audio_tokenizer_path
281
+ )
282
+
283
+ model.sampling_rate = model.feature_extractor.sampling_rate
284
+
285
+ model.duration_estimator = RuleDurationEstimator()
286
+
287
+ if load_asr:
288
+ model.load_asr_model(model_name=asr_model_name)
289
+ finally:
290
+ logging.disable(_prev_disable)
291
+
292
+ return model
293
+
294
+ # -------------------------------------------------------------------
295
+ # ASR support (optional, for auto-transcription)
296
+ # -------------------------------------------------------------------
297
+
298
+ def load_asr_model(self, model_name: str = "openai/whisper-large-v3-turbo"):
299
+ """Load a Whisper ASR model for reference audio transcription.
300
+
301
+ Args:
302
+ model_name: HuggingFace model name or local path for the Whisper model.
303
+ """
304
+ from transformers import pipeline as hf_pipeline
305
+
306
+ logger.info("Loading ASR model %s ...", model_name)
307
+ asr_dtype = (
308
+ torch.float16 if str(self.device).startswith("cuda") else torch.float32
309
+ )
310
+
311
+ model_name = _resolve_model_path(model_name)
312
+
313
+ self._asr_pipe = hf_pipeline(
314
+ "automatic-speech-recognition",
315
+ model=model_name,
316
+ dtype=asr_dtype,
317
+ device_map=self.device,
318
+ )
319
+ logger.info("ASR model loaded on %s.", self.device)
320
+
321
+ @torch.inference_mode()
322
+ def transcribe(
323
+ self,
324
+ audio: Union[str, tuple],
325
+ ) -> str:
326
+ """Transcribe audio using the loaded Whisper ASR model.
327
+
328
+ Args:
329
+ audio: File path or ``(waveform, sample_rate)`` tuple.
330
+ Waveform can be a numpy array or torch.Tensor of shape
331
+ ``(1, T)`` or ``(T,)``.
332
+
333
+ Returns:
334
+ Transcribed text.
335
+ """
336
+ if self._asr_pipe is None:
337
+ raise RuntimeError(
338
+ "ASR model is not loaded. Call model.load_asr_model() first."
339
+ )
340
+
341
+ if isinstance(audio, str):
342
+ return self._asr_pipe(audio)["text"].strip()
343
+ else:
344
+ waveform, sr = audio
345
+ if isinstance(waveform, torch.Tensor):
346
+ waveform = waveform.cpu().numpy()
347
+ waveform = np.squeeze(waveform) # (1, T) or (T,) → (T,)
348
+ audio_input = {
349
+ "array": waveform,
350
+ "sampling_rate": sr,
351
+ }
352
+ return self._asr_pipe(audio_input)["text"].strip()
353
+
354
+ def get_input_embeddings(self):
355
+ return self.llm.get_input_embeddings()
356
+
357
+ def set_input_embeddings(self, value):
358
+ self.llm.set_input_embeddings(value)
359
+
360
+ def _prepare_embed_inputs(
361
+ self, input_ids: torch.Tensor, audio_mask: torch.Tensor
362
+ ) -> torch.Tensor:
363
+ """
364
+ Prepares embeddings from input_ids of shape (batch_size, layers, seq_length).
365
+ Embedding shape is (batch_size, seq_length, hidden_size).
366
+ """
367
+ text_embeds = self.get_input_embeddings()(input_ids[:, 0, :])
368
+
369
+ # Apply shift to audio IDs based on codebook layer
370
+ # audio_ids: [Batch, 8, Seq]
371
+ # codebook_layer_offsets: [1, 8, 1]
372
+ # Result: Layer 0 ID Layer 1 ID + Layer 2 ID + 2050...
373
+ shifted_ids = (
374
+ input_ids * audio_mask.unsqueeze(1)
375
+ ) + self.codebook_layer_offsets.view(1, -1, 1)
376
+
377
+ # input: [Batch, 8, Seq] -> output: [Batch, Seq, Hidden]
378
+ audio_embeds = self.audio_embeddings(shifted_ids).sum(dim=1)
379
+
380
+ return torch.where(audio_mask.unsqueeze(-1), audio_embeds, text_embeds)
381
+
382
+ def forward(
383
+ self,
384
+ input_ids: torch.LongTensor,
385
+ audio_mask: torch.Tensor,
386
+ labels: Optional[torch.LongTensor] = None,
387
+ attention_mask: Optional[torch.Tensor] = None,
388
+ document_ids: Optional[torch.Tensor] = None,
389
+ position_ids: Optional[torch.LongTensor] = None,
390
+ ):
391
+
392
+ inputs_embeds = self._prepare_embed_inputs(input_ids, audio_mask)
393
+
394
+ if attention_mask is None and document_ids is not None:
395
+ if not _flex_attention_available:
396
+ raise RuntimeError(
397
+ "flex_attention is not available in the current environment. "
398
+ "If you do not need flex_attention, set "
399
+ '"attn_implementation": "sdpa" in your training config.'
400
+ )
401
+ attention_mask = create_block_mask(
402
+ _get_packed_mask(
403
+ document_ids[0].to(inputs_embeds.device),
404
+ ),
405
+ B=None,
406
+ H=None,
407
+ Q_LEN=input_ids.size(-1),
408
+ KV_LEN=input_ids.size(-1),
409
+ _compile=True,
410
+ device=inputs_embeds.device,
411
+ )
412
+
413
+ llm_outputs = self.llm(
414
+ inputs_embeds=inputs_embeds,
415
+ attention_mask=attention_mask,
416
+ return_dict=True,
417
+ position_ids=position_ids,
418
+ )
419
+ hidden_states = llm_outputs[0]
420
+
421
+ loss = None
422
+
423
+ # Shape: [B, S, C * Vocab]
424
+ batch_size, seq_len, _ = hidden_states.shape
425
+ logits_flat = self.audio_heads(hidden_states)
426
+ # Shape: [B, S, C, Vocab] -> [B, C, S, Vocab]
427
+ audio_logits = logits_flat.view(
428
+ batch_size,
429
+ seq_len,
430
+ self.config.num_audio_codebook,
431
+ self.config.audio_vocab_size,
432
+ ).permute(0, 2, 1, 3)
433
+
434
+ if labels is not None:
435
+
436
+ # audio_logits.permute(0, 3, 1, 2):
437
+ # [Batch, Layer, Seq, Vocab] -> [Batch, Vocab, Layer, Seq]
438
+ # per_token_loss shape: [Batch, Layer, Seq],ignore -100
439
+ per_token_loss = torch.nn.functional.cross_entropy(
440
+ audio_logits.permute(0, 3, 1, 2),
441
+ labels,
442
+ reduction="none",
443
+ ignore_index=-100,
444
+ )
445
+ # valid_mask shape: [Batch, Layer, Seq]
446
+ valid_mask = (labels != -100).float()
447
+
448
+ # layer_means shape: [num_layers]
449
+ layer_means = (per_token_loss * valid_mask).sum(
450
+ dim=(0, 2)
451
+ ) / valid_mask.sum(dim=(0, 2)).clamp(min=1.0)
452
+
453
+ weights = torch.tensor(
454
+ self.normalized_audio_codebook_weights, device=audio_logits.device
455
+ )
456
+ loss = (layer_means * weights).sum()
457
+
458
+ return OmniVoiceModelOutput(
459
+ loss=loss,
460
+ logits=audio_logits,
461
+ )
462
+
463
+ def supported_language_ids(self) -> set[str]:
464
+ """Return a list of supported language IDs."""
465
+ return LANG_IDS
466
+
467
+ def supported_language_names(self) -> set[str]:
468
+ """Return a list of supported language names."""
469
+ return LANG_NAMES
470
+
471
+ # -------------------------------------------------------------------
472
+ # Inference API
473
+ # -------------------------------------------------------------------
474
+
475
+ @torch.inference_mode()
476
+ def generate(
477
+ self,
478
+ text: Union[str, list[str]],
479
+ language: Union[str, list[str], None] = None,
480
+ ref_text: Union[str, list[str], None] = None,
481
+ ref_audio: Union[
482
+ str,
483
+ list[str],
484
+ tuple[torch.Tensor, int],
485
+ list[tuple[torch.Tensor, int]],
486
+ None,
487
+ ] = None,
488
+ voice_clone_prompt: Union[
489
+ VoiceClonePrompt, list[VoiceClonePrompt], None
490
+ ] = None,
491
+ instruct: Union[str, list[str], None] = None,
492
+ duration: Union[float, list[Optional[float]], None] = None,
493
+ speed: Union[float, list[Optional[float]], None] = None,
494
+ generation_config: Optional[OmniVoiceGenerationConfig] = None,
495
+ **kwargs,
496
+ ) -> list[np.ndarray]:
497
+ """Generate speech audio given text in various modes.
498
+
499
+ Supports three modes:
500
+
501
+ 1. **Voice clone** — clone the voice style from the reference audio.
502
+ Should provide ``voice_clone_prompt`` (from
503
+ :meth:`create_voice_clone_prompt`) or ``ref_text`` + ``ref_audio``.
504
+ 2. **Voice design** — provide ``instruct`` text describing
505
+ the desired voice style; no reference audio needed.
506
+ 3. **Auto** — provide neither; the model picks a voice itself.
507
+
508
+ Args:
509
+ text: Target text (single string or list for batch).
510
+ language: Language name (e.g. ``"English"``) or code
511
+ (e.g. ``"en"``). ``None`` for language-agnostic mode.
512
+ Performance is slightly better if you specify the language.
513
+ ref_text: Optional reference text for voice cloning mode.
514
+ ref_audio: Optional reference audio for voice cloning mode.
515
+ Can be a file path or a (waveform, sample_rate) tuple.
516
+ voice_clone_prompt: Reusable prompt from :meth:`create_voice_clone_prompt`.
517
+ If provided, it overrides ``ref_text`` and ``ref_audio``.
518
+ instruct: Style instruction for voice design mode.
519
+ duration: Fixed output duration in seconds. If a single float,
520
+ applies to all items; if a list, one value per item.
521
+ ``None`` (default) lets the model estimate duration from text.
522
+ Overrides ``speed`` when both are provided.
523
+ speed: Speaking speed factor. ``> 1.0`` for faster, ``< 1.0`` for
524
+ slower. If a list, one value per item. ``None`` (default) uses
525
+ the model's default estimation.
526
+ generation_config: Explicit config object. If provided, takes
527
+ precedence over ``**kwargs``.
528
+ **kwargs: Generation config or its fields:
529
+ denoise: Whether to prepend the ``<|denoise|>`` token.
530
+ num_step: Number of iterative decoding steps.
531
+ guidance_scale: Classifier-free guidance scale.
532
+ t_shift: Time-step shift (smaller → emphasise low-SNR).
533
+ postprocess_output: Post-process output (remove silence, fade-in/out, pad edges).
534
+ layer_penalty_factor: Penalty encouraging earlier codebook
535
+ layers to unmask first.
536
+ position_temperature: Temperature for position selection.
537
+ class_temperature: Temperature for token sampling (0 = greedy).
538
+ audio_chunk_duration: If > 0, split long text into chunks of
539
+ this duration (seconds) and generate chunk by chunk.
540
+ audio_chunk_threshold: Only apply chunking if estimated audio
541
+ duration exceeds this threshold (seconds).
542
+ Returns:
543
+ ``audios`` a list of 1-D ``np.ndarray`` with shape ``(T,)`` and
544
+ sampling rate consistent with the model's audio tokenizer
545
+ (usually 24 000 Hz). Can be saved directly with
546
+ ``soundfile.write("out.wav", audios[0], model.sampling_rate)``.
547
+ """
548
+
549
+ if self.audio_tokenizer is None or self.text_tokenizer is None:
550
+ raise RuntimeError(
551
+ "Model is not loaded with audio/text tokenizers. Make sure you "
552
+ "loaded the model with OmniVoice.from_pretrained()."
553
+ )
554
+ gen_config = (
555
+ generation_config
556
+ if generation_config is not None
557
+ else OmniVoiceGenerationConfig.from_dict(kwargs)
558
+ )
559
+
560
+ self.eval()
561
+
562
+ full_task = self._preprocess_all(
563
+ text=text,
564
+ language=language,
565
+ ref_text=ref_text,
566
+ ref_audio=ref_audio,
567
+ voice_clone_prompt=voice_clone_prompt,
568
+ instruct=instruct,
569
+ preprocess_prompt=gen_config.preprocess_prompt,
570
+ speed=speed,
571
+ duration=duration,
572
+ )
573
+
574
+ short_idx, long_idx = full_task.get_indices(
575
+ gen_config, self.audio_tokenizer.config.frame_rate
576
+ )
577
+
578
+ results = [None] * full_task.batch_size
579
+
580
+ if short_idx:
581
+ short_task = full_task.slice_task(short_idx)
582
+ short_results = self._generate_iterative(short_task, gen_config)
583
+ for idx, res in zip(short_idx, short_results):
584
+ results[idx] = res
585
+
586
+ if long_idx:
587
+ long_task = full_task.slice_task(long_idx)
588
+ long_results = self._generate_chunked(long_task, gen_config)
589
+ for idx, res in zip(long_idx, long_results):
590
+ results[idx] = res
591
+
592
+ generated_audios = []
593
+ for i in range(full_task.batch_size):
594
+ assert results[i] is not None, f"Result {i} was not generated"
595
+ generated_audios.append(
596
+ self._decode_and_post_process(
597
+ results[i], full_task.ref_rms[i], gen_config # type: ignore[arg-type]
598
+ )
599
+ )
600
+
601
+ return generated_audios
602
+
603
+ def create_voice_clone_prompt(
604
+ self,
605
+ ref_audio: Union[str, tuple[torch.Tensor, int]],
606
+ ref_text: Optional[str] = None,
607
+ preprocess_prompt: bool = True,
608
+ ) -> VoiceClonePrompt:
609
+ """Create a reusable voice clone prompt from reference audio.
610
+
611
+ Args:
612
+ ref_audio: File path (str) or ``(waveform, sample_rate)`` tuple.
613
+ waveform should be a 1-D or 2-D torch.Tensor (channels x samples).
614
+ ref_text: Transcript of the reference audio. If ``None``, the
615
+ ASR model will be used to auto-transcribe (must call
616
+ :meth:`load_asr_model` first).
617
+ preprocess_prompt: If ``True`` (default), apply silence removal and
618
+ trimming to the reference audio, add punctuation in the end
619
+ of reference text (if not already)
620
+
621
+ Returns:
622
+ A :class:`VoiceClonePrompt` that can be passed to :meth:`generate`.
623
+ """
624
+ if self.audio_tokenizer is None:
625
+ raise RuntimeError(
626
+ "Audio tokenizer is not loaded. Make sure you loaded the model "
627
+ "with OmniVoice.from_pretrained()."
628
+ )
629
+
630
+ if isinstance(ref_audio, str):
631
+ ref_wav = load_audio(ref_audio, self.sampling_rate)
632
+ else:
633
+ waveform, sr = ref_audio
634
+ if isinstance(waveform, torch.Tensor):
635
+ waveform = waveform.cpu().numpy()
636
+ if waveform.ndim == 1:
637
+ waveform = waveform[np.newaxis, :]
638
+ if waveform.shape[0] > 1:
639
+ waveform = np.mean(waveform, axis=0, keepdims=True)
640
+ if sr != self.sampling_rate:
641
+ waveform = torchaudio.functional.resample(
642
+ torch.from_numpy(waveform),
643
+ orig_freq=sr,
644
+ new_freq=self.sampling_rate,
645
+ ).numpy()
646
+ ref_wav = waveform
647
+
648
+ ref_rms = float(np.sqrt(np.mean(ref_wav**2)))
649
+ if 0 < ref_rms < 0.1:
650
+ ref_wav = ref_wav * 0.1 / ref_rms
651
+
652
+ if preprocess_prompt:
653
+ # Trim long reference audio (>20s) by splitting at the largest silence gap.
654
+ # Skip trimming when ref_text is user-provided, otherwise the
655
+ # trimmed audio will no longer match the full transcript.
656
+ if ref_text is None:
657
+ ref_wav = trim_long_audio(
658
+ ref_wav, self.sampling_rate, trim_threshold=20.0
659
+ )
660
+ ref_wav = remove_silence(
661
+ ref_wav,
662
+ self.sampling_rate,
663
+ mid_sil=200,
664
+ lead_sil=100,
665
+ trail_sil=200,
666
+ )
667
+ if ref_wav.shape[-1] == 0:
668
+ raise ValueError(
669
+ "Reference audio is empty after silence removal. "
670
+ "Try setting preprocess_prompt=False."
671
+ )
672
+
673
+ ref_duration = ref_wav.shape[-1] / self.sampling_rate
674
+ if ref_duration > 20.0:
675
+ logger.warning(
676
+ "Reference audio is %.1fs long (>20s). This may cause slower "
677
+ "generation, higher memory usage, and degraded voice cloning "
678
+ "quality. We recommend trimming it to 3-10s.",
679
+ ref_duration,
680
+ )
681
+
682
+ # Auto-transcribe if ref_text not provided
683
+ if ref_text is None:
684
+ if self._asr_pipe is None:
685
+ logger.info("ASR model not loaded yet, loading on-the-fly ...")
686
+ self.load_asr_model()
687
+ ref_text = self.transcribe((ref_wav, self.sampling_rate))
688
+ logger.debug("Auto-transcribed ref_text: %s", ref_text)
689
+
690
+ chunk_size = self.audio_tokenizer.config.hop_length
691
+ clip_size = int(ref_wav.shape[-1] % chunk_size)
692
+ ref_wav = ref_wav[:, :-clip_size] if clip_size > 0 else ref_wav
693
+ # numpy → torch at tokenizer boundary
694
+ ref_wav_tensor = torch.from_numpy(ref_wav).to(self.audio_tokenizer.device)
695
+ ref_audio_tokens = self.audio_tokenizer.encode(
696
+ ref_wav_tensor.unsqueeze(0),
697
+ ).audio_codes.squeeze(
698
+ 0
699
+ ) # (C, T)
700
+
701
+ if preprocess_prompt:
702
+ ref_text = add_punctuation(ref_text)
703
+
704
+ return VoiceClonePrompt(
705
+ ref_audio_tokens=ref_audio_tokens,
706
+ ref_text=ref_text,
707
+ ref_rms=ref_rms,
708
+ )
709
+
710
+ def _decode_and_post_process(
711
+ self,
712
+ tokens: Union[torch.Tensor, List[torch.Tensor]],
713
+ rms: Union[float, None],
714
+ gen_config: OmniVoiceGenerationConfig,
715
+ ) -> np.ndarray:
716
+ """
717
+ Args:
718
+ tokens: Audio tokens — either a single tensor of shape
719
+ (num_codebooks, seq_len) or a list of chunk tensors.
720
+ rms: RMS of the reference audio for volume adjustment.
721
+ gen_config: Generation config for post-processing options.
722
+ Returns:
723
+ Decoded and post-processed audio array of shape (T,).
724
+ """
725
+ tokenizer_device = self.audio_tokenizer.device
726
+ if isinstance(tokens, list):
727
+ chunk_audios = [
728
+ self.audio_tokenizer.decode(t.to(tokenizer_device).unsqueeze(0))
729
+ .audio_values[0]
730
+ .cpu()
731
+ .numpy()
732
+ for t in tokens
733
+ ]
734
+ audio_waveform = cross_fade_chunks(chunk_audios, self.sampling_rate)
735
+ else:
736
+ audio_waveform = (
737
+ self.audio_tokenizer.decode(tokens.to(tokenizer_device).unsqueeze(0))
738
+ .audio_values[0]
739
+ .cpu()
740
+ .numpy()
741
+ )
742
+
743
+ audio_waveform = self._post_process_audio(
744
+ audio_waveform,
745
+ postprocess_output=gen_config.postprocess_output,
746
+ ref_rms=rms,
747
+ )
748
+ return audio_waveform.squeeze(0)
749
+
750
+ def _post_process_audio(
751
+ self,
752
+ generated_audio: np.ndarray,
753
+ postprocess_output: bool,
754
+ ref_rms: Union[float, None],
755
+ ) -> np.ndarray:
756
+ """Optionally remove long silences, adjust volume, and add edge padding.
757
+
758
+ Args:
759
+ generated_audio: Numpy array of shape (1, T).
760
+ postprocess_output: If True, remove long silences and apply fade/pad.
761
+ ref_rms: RMS of the reference audio for volume normalisation.
762
+ Returns:
763
+ Processed numpy array of shape (1, T).
764
+ """
765
+ if postprocess_output:
766
+ generated_audio = remove_silence(
767
+ generated_audio,
768
+ self.sampling_rate,
769
+ mid_sil=500,
770
+ lead_sil=100,
771
+ trail_sil=100,
772
+ )
773
+
774
+ if ref_rms is not None and ref_rms < 0.1:
775
+ generated_audio = generated_audio * ref_rms / 0.1
776
+ elif ref_rms is None:
777
+ peak = np.abs(generated_audio).max()
778
+ if peak > 1e-6:
779
+ generated_audio = generated_audio / peak * 0.5
780
+
781
+ generated_audio = fade_and_pad_audio(
782
+ generated_audio,
783
+ sample_rate=self.sampling_rate,
784
+ )
785
+ return generated_audio
786
+
787
+ def _generate_chunked(
788
+ self, task: GenerationTask, gen_config: OmniVoiceGenerationConfig
789
+ ) -> List[List[torch.Tensor]]:
790
+ """Generate long audio by splitting text into chunks and batching.
791
+
792
+ Each item in the returned list corresponds to one input and contains
793
+ a list of audio token tensors — one per text chunk.
794
+
795
+ Args:
796
+ task: A :class:`GenerationTask` with one or more items whose
797
+ estimated audio exceeds ``audio_chunk_threshold``.
798
+ gen_config: Generation config (``audio_chunk_duration`` controls
799
+ chunk size).
800
+ Returns:
801
+ Per-item list of chunk token-tensor lists.
802
+ """
803
+ # Chunk each item's text
804
+ all_chunks = []
805
+ for i in range(task.batch_size):
806
+ avg_tokens_per_char = task.target_lens[i] / len(task.texts[i])
807
+ text_chunk_len = int(
808
+ gen_config.audio_chunk_duration
809
+ * self.audio_tokenizer.config.frame_rate
810
+ / avg_tokens_per_char
811
+ )
812
+ chunks = chunk_text_punctuation(
813
+ text=task.texts[i],
814
+ chunk_len=text_chunk_len,
815
+ min_chunk_len=3,
816
+ )
817
+ logger.debug(f"Item {i} chunked into {len(chunks)} pieces: {chunks}")
818
+ all_chunks.append(chunks)
819
+
820
+ has_ref = [t is not None for t in task.ref_audio_tokens]
821
+ assert all(has_ref) or not any(has_ref), (
822
+ "Chunked inference requires all items to either have or not have "
823
+ "ref_audio. Mixed ref/non-ref is not supported."
824
+ )
825
+
826
+ max_num_chunks = max(len(c) for c in all_chunks)
827
+
828
+ # chunk_results[item_idx] = list of generated token tensors per chunk
829
+ chunk_results = [[] for _ in range(task.batch_size)]
830
+
831
+ def _run_batch(indices, texts, ref_audios, ref_texts):
832
+ speed_list = task.speed
833
+ target_lens = [
834
+ self._estimate_target_tokens(
835
+ texts[j],
836
+ ref_texts[j],
837
+ ref_audios[j].size(-1) if ref_audios[j] is not None else None,
838
+ speed=speed_list[i] if speed_list else 1.0,
839
+ )
840
+ for j, i in enumerate(indices)
841
+ ]
842
+ sub_task = GenerationTask(
843
+ batch_size=len(indices),
844
+ texts=texts,
845
+ target_lens=target_lens,
846
+ langs=[task.langs[i] for i in indices],
847
+ instructs=[task.instructs[i] for i in indices],
848
+ ref_texts=ref_texts,
849
+ ref_audio_tokens=ref_audios,
850
+ ref_rms=[task.ref_rms[i] for i in indices],
851
+ speed=[task.speed[i] for i in indices] if task.speed else None,
852
+ )
853
+ gen_tokens = self._generate_iterative(sub_task, gen_config)
854
+ for j, idx in enumerate(indices):
855
+ chunk_results[idx].append(gen_tokens[j])
856
+
857
+ if all(has_ref):
858
+ # All items have reference audio.
859
+ # We still sequentially generate chunks within each item, but we
860
+ # batch across items for the same chunk index. This allows to keep
861
+ # the VRAM usage manageable while still benefiting from batching.
862
+ for ci in range(max_num_chunks):
863
+ indices = [i for i in range(task.batch_size) if ci < len(all_chunks[i])]
864
+ if not indices:
865
+ continue
866
+ _run_batch(
867
+ indices,
868
+ texts=[all_chunks[i][ci] for i in indices],
869
+ ref_audios=[task.ref_audio_tokens[i] for i in indices],
870
+ ref_texts=[task.ref_texts[i] for i in indices],
871
+ )
872
+ else:
873
+ # No reference audio — generate chunk 0 for all items first,
874
+ # then use chunk 0 output as reference for all subsequent chunks.
875
+ indices_0 = [i for i in range(task.batch_size) if len(all_chunks[i]) > 0]
876
+ _run_batch(
877
+ indices_0,
878
+ texts=[all_chunks[i][0] for i in indices_0],
879
+ ref_audios=[None] * len(indices_0),
880
+ ref_texts=[None] * len(indices_0),
881
+ )
882
+ first_chunk_map = {idx: chunk_results[idx][0] for idx in indices_0}
883
+
884
+ # Batch all remaining chunks, using chunk 0 as fixed reference
885
+ for ci in range(1, max_num_chunks):
886
+ indices = [i for i in range(task.batch_size) if ci < len(all_chunks[i])]
887
+ if not indices:
888
+ continue
889
+ _run_batch(
890
+ indices,
891
+ texts=[all_chunks[i][ci] for i in indices],
892
+ ref_audios=[first_chunk_map[i] for i in indices],
893
+ ref_texts=[all_chunks[i][0] for i in indices],
894
+ )
895
+
896
+ return chunk_results
897
+
898
+ def _preprocess_all(
899
+ self,
900
+ text: Union[str, list[str]],
901
+ language: Union[str, list[str], None] = None,
902
+ ref_text: Union[str, list[str], None] = None,
903
+ ref_audio: Union[
904
+ str,
905
+ list[str],
906
+ tuple[torch.Tensor, int],
907
+ list[tuple[torch.Tensor, int]],
908
+ None,
909
+ ] = None,
910
+ voice_clone_prompt: Union[
911
+ VoiceClonePrompt, list[VoiceClonePrompt], None
912
+ ] = None,
913
+ instruct: Union[str, list[str], None] = None,
914
+ preprocess_prompt: bool = True,
915
+ speed: Union[float, list[Optional[float]], None] = None,
916
+ duration: Union[float, list[Optional[float]], None] = None,
917
+ ) -> GenerationTask:
918
+
919
+ if isinstance(text, str):
920
+ text_list = [text]
921
+ else:
922
+ assert isinstance(
923
+ text, list
924
+ ), "text should be a string or a list of strings"
925
+ text_list = text
926
+ batch_size = len(text_list)
927
+
928
+ language_list = self._ensure_list(language, batch_size)
929
+ language_list = [_resolve_language(lang) for lang in language_list]
930
+ instruct_list = self._ensure_list(instruct, batch_size)
931
+ for i, s in enumerate(instruct_list):
932
+ if s is None:
933
+ continue
934
+ use_zh = bool(text_list[i] and _ZH_RE.search(text_list[i]))
935
+ instruct_list[i] = _resolve_instruct(s, use_zh=use_zh)
936
+
937
+ if voice_clone_prompt is not None and (
938
+ ref_text is not None or ref_audio is not None
939
+ ):
940
+ logger.warning(
941
+ "Both voice_clone_prompt and ref_text/ref_audio are provided. "
942
+ "ref_text/ref_audio will be ignored."
943
+ )
944
+ if voice_clone_prompt is None and ref_audio is not None:
945
+ # If voice_clone_prompt is not provided, create it from
946
+ # ref_audio (ref_text will be auto-transcribed if not given).
947
+ ref_text_list = self._ensure_list(ref_text, batch_size, auto_repeat=False)
948
+ ref_audio_list = self._ensure_list(ref_audio, batch_size, auto_repeat=False)
949
+
950
+ voice_clone_prompt = []
951
+ for i in range(len(ref_text_list)):
952
+ voice_clone_prompt.append(
953
+ self.create_voice_clone_prompt(
954
+ ref_audio=ref_audio_list[i],
955
+ ref_text=ref_text_list[i],
956
+ preprocess_prompt=preprocess_prompt,
957
+ )
958
+ )
959
+
960
+ voice_clone_prompt_list = self._ensure_list(voice_clone_prompt, batch_size)
961
+ if voice_clone_prompt_list[0] is not None:
962
+ ref_text_list = [vc.ref_text for vc in voice_clone_prompt_list]
963
+ ref_audio_tokens_list = [
964
+ vc.ref_audio_tokens for vc in voice_clone_prompt_list
965
+ ]
966
+ ref_rms_list = [vc.ref_rms for vc in voice_clone_prompt_list]
967
+ else:
968
+ ref_text_list = [None] * batch_size
969
+ ref_audio_tokens_list = [None] * batch_size
970
+ ref_rms_list = [None] * batch_size
971
+
972
+ # Normalize speed/duration to per-item lists (may contain None).
973
+ if speed is not None:
974
+ if isinstance(speed, (int, float)):
975
+ user_speed = [float(speed)] * batch_size
976
+ else:
977
+ user_speed = list(speed)
978
+ else:
979
+ user_speed = None
980
+
981
+ if duration is not None:
982
+ if isinstance(duration, (int, float)):
983
+ durations = [float(duration)] * batch_size
984
+ else:
985
+ durations = list(duration)
986
+ else:
987
+ durations = None
988
+
989
+ num_target_tokens_list = []
990
+ for i in range(batch_size):
991
+ # duration[i] overrides speed for estimation: use speed=1.0
992
+ # to get the raw estimate, then override target_lens below.
993
+ has_dur = durations is not None and durations[i] is not None
994
+ item_speed = 1.0 if has_dur else (user_speed[i] if user_speed else 1.0)
995
+ est = self._estimate_target_tokens(
996
+ text_list[i],
997
+ ref_text_list[i],
998
+ ref_audio_tokens_list[i].size(-1)
999
+ if ref_audio_tokens_list[i] is not None
1000
+ else None,
1001
+ speed=item_speed,
1002
+ )
1003
+ num_target_tokens_list.append(est)
1004
+
1005
+ # Per-item duration overrides: set target_lens to exact frame count
1006
+ # and compute speed ratio so chunked generation scales proportionally.
1007
+ speed_list: Optional[List[float]] = None
1008
+ if durations is not None:
1009
+ frame_rate = self.audio_tokenizer.config.frame_rate
1010
+ speed_list = []
1011
+ for i in range(batch_size):
1012
+ if durations[i] is not None:
1013
+ target_tokens = max(1, int(durations[i] * frame_rate))
1014
+ est = num_target_tokens_list[i]
1015
+ speed_list.append(est / target_tokens if target_tokens > 0 else 1.0)
1016
+ num_target_tokens_list[i] = target_tokens
1017
+ else:
1018
+ s = user_speed[i] if user_speed else None
1019
+ speed_list.append(s if s is not None else 1.0)
1020
+ elif user_speed is not None:
1021
+ speed_list = [s if s is not None else 1.0 for s in user_speed]
1022
+
1023
+ return GenerationTask(
1024
+ batch_size=batch_size,
1025
+ texts=text_list,
1026
+ target_lens=num_target_tokens_list,
1027
+ langs=language_list,
1028
+ instructs=instruct_list,
1029
+ ref_texts=ref_text_list,
1030
+ ref_audio_tokens=ref_audio_tokens_list,
1031
+ ref_rms=ref_rms_list,
1032
+ speed=speed_list,
1033
+ )
1034
+
1035
+ def _estimate_target_tokens(self, text, ref_text, num_ref_audio_tokens, speed=1.0):
1036
+ """Estimate number of target audio tokens."""
1037
+ if num_ref_audio_tokens is None or ref_text is None or len(ref_text) == 0:
1038
+ # Fall back to a simple heuristic
1039
+ ref_text = "Nice to meet you."
1040
+ num_ref_audio_tokens = 25
1041
+
1042
+ est = self.duration_estimator.estimate_duration(
1043
+ text, ref_text, num_ref_audio_tokens
1044
+ )
1045
+ if speed > 0 and speed != 1.0:
1046
+ est = est / speed
1047
+ return max(1, int(est))
1048
+
1049
+ def _ensure_list(
1050
+ self, x: Union[Any, List[Any]], batch_size: int, auto_repeat: bool = True
1051
+ ) -> List[Any]:
1052
+ x_list = x if isinstance(x, list) else [x]
1053
+ if len(x_list) not in (
1054
+ 1,
1055
+ batch_size,
1056
+ ):
1057
+ raise ValueError(
1058
+ f"should be either the number of the text or 1, but got {len(x_list)}"
1059
+ )
1060
+ if auto_repeat and len(x_list) == 1 and batch_size is not None:
1061
+ x_list = x_list * batch_size
1062
+ return x_list
1063
+
1064
+ def _prepare_inference_inputs(
1065
+ self,
1066
+ text: str,
1067
+ num_target_tokens: int,
1068
+ ref_text: Optional[str] = None,
1069
+ ref_audio_tokens: Optional[torch.Tensor] = None,
1070
+ lang: Optional[str] = None,
1071
+ instruct: Optional[str] = None,
1072
+ denoise: bool = True,
1073
+ ):
1074
+ """Prepare input_ids and audio masks for inference.
1075
+ Args:
1076
+ text: Target text to generate.
1077
+ num_target_tokens: Number of audio tokens to generate.
1078
+ ref_text: Optional reference text for voice cloning.
1079
+ ref_audio_tokens: Optional reference audio tokens for voice cloning.
1080
+ with shape (C, T).
1081
+ lang: Optional language ID.
1082
+ instruct: Optional style instruction for voice design.
1083
+ denoise: Whether to include the <|denoise|> token.
1084
+ """
1085
+
1086
+ # Build style tokens: <|denoise|> + <|lang_start|>...<|lang_end|>
1087
+ # + <|instruct_start|>...<|instruct_end|>
1088
+ style_text = ""
1089
+ if denoise and ref_audio_tokens is not None:
1090
+ style_text += "<|denoise|>"
1091
+ lang_str = lang if lang else "None"
1092
+ instruct_str = instruct if instruct else "None"
1093
+ style_text += f"<|lang_start|>{lang_str}<|lang_end|>"
1094
+ style_text += f"<|instruct_start|>{instruct_str}<|instruct_end|>"
1095
+
1096
+ style_tokens = (
1097
+ self.text_tokenizer(style_text, return_tensors="pt")
1098
+ .input_ids.repeat(self.config.num_audio_codebook, 1)
1099
+ .unsqueeze(0)
1100
+ ).to(
1101
+ self.device
1102
+ ) # [1, C, N1]
1103
+
1104
+ # Build text tokens
1105
+ full_text = _combine_text(ref_text=ref_text, text=text)
1106
+ wrapped_text = f"<|text_start|>{full_text}<|text_end|>"
1107
+ text_tokens = (
1108
+ _tokenize_with_nonverbal_tags(wrapped_text, self.text_tokenizer)
1109
+ .repeat(self.config.num_audio_codebook, 1)
1110
+ .unsqueeze(0)
1111
+ ).to(
1112
+ self.device
1113
+ ) # [1, C, N2]
1114
+
1115
+ # Target: all MASK
1116
+ target_audio_tokens = torch.full(
1117
+ (1, self.config.num_audio_codebook, num_target_tokens),
1118
+ self.config.audio_mask_id,
1119
+ dtype=torch.long,
1120
+ device=self.device,
1121
+ )
1122
+
1123
+ # Conditional input
1124
+ parts = [style_tokens, text_tokens]
1125
+ if ref_audio_tokens is not None:
1126
+ parts.append(ref_audio_tokens.unsqueeze(0).to(self.device))
1127
+ parts.append(target_audio_tokens)
1128
+ cond_input_ids = torch.cat(parts, dim=2)
1129
+
1130
+ cond_total_length = cond_input_ids.shape[2]
1131
+ cond_audio_start_idx = cond_total_length - num_target_tokens
1132
+ if ref_audio_tokens is not None:
1133
+ cond_audio_start_idx -= ref_audio_tokens.size(-1)
1134
+
1135
+ cond_audio_mask = torch.zeros(
1136
+ 1, cond_total_length, dtype=torch.bool, device=self.device
1137
+ )
1138
+ cond_audio_mask[0, cond_audio_start_idx:] = True
1139
+
1140
+ return {
1141
+ "input_ids": cond_input_ids,
1142
+ "audio_mask": cond_audio_mask,
1143
+ }
1144
+
1145
+ def _generate_iterative(
1146
+ self, task: GenerationTask, gen_config: OmniVoiceGenerationConfig
1147
+ ) -> List[torch.Tensor]:
1148
+ """N-step iterative unmasked decoding.
1149
+
1150
+ Args:
1151
+ task: A :class:`GenerationTask` containing batch texts, target
1152
+ lengths, languages, instructions, and optional reference data.
1153
+ gen_config: A :class:`OmniVoiceGenerationConfig` controlling
1154
+ decoding steps, guidance, temperatures, etc.
1155
+ Returns:
1156
+ List of generated audio token tensors of shape (C, T) (one per
1157
+ input text).
1158
+ """
1159
+
1160
+ B = task.batch_size
1161
+
1162
+ for i in range(B):
1163
+ logger.debug(
1164
+ "Item %d — text: %s | ref_text: %s | instruct: %s | lang: %s | target_tokens: %d",
1165
+ i,
1166
+ task.texts[i],
1167
+ task.ref_texts[i],
1168
+ task.instructs[i],
1169
+ task.langs[i],
1170
+ task.target_lens[i],
1171
+ )
1172
+
1173
+ inputs_list = [
1174
+ self._prepare_inference_inputs(
1175
+ task.texts[i],
1176
+ task.target_lens[i],
1177
+ task.ref_texts[i],
1178
+ task.ref_audio_tokens[i],
1179
+ task.langs[i],
1180
+ task.instructs[i],
1181
+ gen_config.denoise,
1182
+ )
1183
+ for i in range(B)
1184
+ ]
1185
+
1186
+ c_lens = [inp["input_ids"].size(2) for inp in inputs_list]
1187
+ max_c_len = max(c_lens)
1188
+ pad_id = self.config.audio_mask_id # Or any other tokens
1189
+
1190
+ batch_input_ids = torch.full(
1191
+ (2 * B, self.config.num_audio_codebook, max_c_len),
1192
+ pad_id,
1193
+ dtype=torch.long,
1194
+ device=self.device,
1195
+ )
1196
+ batch_audio_mask = torch.zeros(
1197
+ (2 * B, max_c_len), dtype=torch.bool, device=self.device
1198
+ )
1199
+ batch_attention_mask = torch.zeros(
1200
+ (2 * B, 1, max_c_len, max_c_len), dtype=torch.bool, device=self.device
1201
+ )
1202
+
1203
+ for i, inp in enumerate(inputs_list):
1204
+ c_len, u_len = c_lens[i], task.target_lens[i]
1205
+
1206
+ # Cond (0 ~ B-1)
1207
+ batch_input_ids[i, :, :c_len] = inp["input_ids"]
1208
+ batch_audio_mask[i, :c_len] = inp["audio_mask"]
1209
+ batch_attention_mask[i, :, :c_len, :c_len] = True
1210
+
1211
+ # Uncond (B ~ 2B-1)
1212
+ batch_input_ids[B + i, :, :u_len] = inp["input_ids"][..., -u_len:]
1213
+ batch_audio_mask[B + i, :u_len] = inp["audio_mask"][..., -u_len:]
1214
+ batch_attention_mask[B + i, :, :u_len, :u_len] = True
1215
+ if max_c_len > u_len:
1216
+ pad_diag = torch.arange(u_len, max_c_len, device=self.device)
1217
+ batch_attention_mask[B + i, :, pad_diag, pad_diag] = True
1218
+
1219
+ tokens = torch.full(
1220
+ (B, self.config.num_audio_codebook, max(task.target_lens)),
1221
+ self.config.audio_mask_id,
1222
+ dtype=torch.long,
1223
+ device=self.device,
1224
+ )
1225
+
1226
+ timesteps = _get_time_steps(
1227
+ t_start=0.0,
1228
+ t_end=1.0,
1229
+ num_step=gen_config.num_step,
1230
+ t_shift=gen_config.t_shift,
1231
+ ).tolist()
1232
+ schedules = []
1233
+ for t_len in task.target_lens:
1234
+ total_mask = t_len * self.config.num_audio_codebook
1235
+ rem = total_mask
1236
+ sched = []
1237
+ for step in range(gen_config.num_step):
1238
+ num = (
1239
+ rem
1240
+ if step == gen_config.num_step - 1
1241
+ else min(
1242
+ math.ceil(total_mask * (timesteps[step + 1] - timesteps[step])),
1243
+ rem,
1244
+ )
1245
+ )
1246
+ sched.append(int(num))
1247
+ rem -= int(num)
1248
+ schedules.append(sched)
1249
+
1250
+ layer_ids = torch.arange(
1251
+ self.config.num_audio_codebook, device=self.device
1252
+ ).view(1, -1, 1)
1253
+
1254
+ for step in range(gen_config.num_step):
1255
+ batch_logits = self(
1256
+ input_ids=batch_input_ids,
1257
+ audio_mask=batch_audio_mask,
1258
+ attention_mask=batch_attention_mask,
1259
+ ).logits.to(torch.float32)
1260
+
1261
+ for i in range(B):
1262
+ k = schedules[i][step]
1263
+ if k <= 0:
1264
+ continue
1265
+
1266
+ c_len, t_len = c_lens[i], task.target_lens[i]
1267
+
1268
+ # Extract real target Logits
1269
+ # [1, C, T, V]
1270
+ c_logits = batch_logits[i : i + 1, :, c_len - t_len : c_len, :]
1271
+ u_logits = batch_logits[B + i : B + i + 1, :, :t_len, :]
1272
+
1273
+ pred_tokens, scores = self._predict_tokens_with_scoring(
1274
+ c_logits, u_logits, gen_config
1275
+ )
1276
+
1277
+ scores = scores - (layer_ids * gen_config.layer_penalty_factor)
1278
+
1279
+ if gen_config.position_temperature > 0.0:
1280
+ scores = _gumbel_sample(scores, gen_config.position_temperature)
1281
+
1282
+ sample_tokens = tokens[i : i + 1, :, :t_len]
1283
+ scores.masked_fill_(
1284
+ sample_tokens != self.config.audio_mask_id, -float("inf")
1285
+ )
1286
+
1287
+ _, topk_idx = torch.topk(scores.flatten(), k)
1288
+ flat_tokens = sample_tokens.flatten()
1289
+ flat_tokens[topk_idx] = pred_tokens.flatten()[topk_idx]
1290
+ sample_tokens.copy_(flat_tokens.view_as(sample_tokens))
1291
+
1292
+ # Update individual slices into batched structure
1293
+ tokens[i : i + 1, :, :t_len] = sample_tokens
1294
+ batch_input_ids[i : i + 1, :, c_len - t_len : c_len] = sample_tokens
1295
+ batch_input_ids[B + i : B + i + 1, :, :t_len] = sample_tokens
1296
+
1297
+ return [tokens[i, :, : task.target_lens[i]] for i in range(B)]
1298
+
1299
+ def _predict_tokens_with_scoring(self, c_logits, u_logits, gen_config):
1300
+ if gen_config.guidance_scale != 0:
1301
+ c_log_probs = F.log_softmax(c_logits, dim=-1)
1302
+ u_log_probs = F.log_softmax(u_logits, dim=-1)
1303
+ log_probs = torch.log_softmax(
1304
+ c_log_probs + gen_config.guidance_scale * (c_log_probs - u_log_probs),
1305
+ dim=-1,
1306
+ )
1307
+ else:
1308
+ log_probs = F.log_softmax(c_logits, dim=-1)
1309
+
1310
+ log_probs[..., self.config.audio_mask_id] = -float("inf")
1311
+
1312
+ if gen_config.class_temperature > 0.0:
1313
+ filtered_probs = _filter_top_k(log_probs, ratio=0.1)
1314
+ pred_tokens = _gumbel_sample(
1315
+ filtered_probs, gen_config.class_temperature
1316
+ ).argmax(dim=-1)
1317
+ else:
1318
+ pred_tokens = log_probs.argmax(dim=-1)
1319
+
1320
+ confidence_scores = log_probs.max(dim=-1)[0]
1321
+
1322
+ return pred_tokens, confidence_scores
1323
+
1324
+
1325
+ # ---------------------------------------------------------------------------
1326
+ # Standalone helpers
1327
+ # ---------------------------------------------------------------------------
1328
+
1329
+
1330
+ def _get_packed_mask(document_ids):
1331
+ return partial(_mask_mod_packed, document_ids)
1332
+
1333
+
1334
+ def _mask_mod_packed(document_ids, b, h, q_idx, kv_idx):
1335
+ # 1. Sequence Packing Logic: Tokens must belong to the same document.
1336
+ # Note: The doc_id for padding tokens is -1, which will automatically not match
1337
+ # (if handled correctly) or be ignored.
1338
+ same_doc = document_ids[q_idx] == document_ids[kv_idx]
1339
+ return same_doc
1340
+
1341
+
1342
+ def _resolve_language(language: Optional[str]) -> Union[str, None]:
1343
+ from omnivoice.utils.lang_map import LANG_IDS, LANG_NAME_TO_ID
1344
+
1345
+ if language is None or language.lower() == "none":
1346
+ return None
1347
+ if language in LANG_IDS:
1348
+ return language
1349
+ key = language.lower()
1350
+ if key in LANG_NAME_TO_ID:
1351
+ return LANG_NAME_TO_ID[key]
1352
+ logger.warning(
1353
+ f"Language '{language}' is not recognized. "
1354
+ f"Please use a valid language ID (e.g., 'en', 'zh', 'ja', 'de') "
1355
+ f"or a full language name (e.g., 'English', 'Chinese', 'Japanese'). "
1356
+ f"See supported_language_ids() or supported_language_names() for details. "
1357
+ f"Falling back to None (language-agnostic mode)."
1358
+ )
1359
+ return None
1360
+
1361
+
1362
+ def _resolve_instruct(
1363
+ instruct: Optional[str], use_zh: bool = False
1364
+ ) -> Union[str, None]:
1365
+ """Validate and normalise a voice-design instruct string.
1366
+
1367
+ Supported instruct items (case-insensitive for English):
1368
+
1369
+ English (comma + space separated):
1370
+ gender: male, female
1371
+ age: child, teenager, young adult, middle-aged, elderly
1372
+ pitch: very low pitch, low pitch, moderate pitch,
1373
+ high pitch, very high pitch
1374
+ style: whisper
1375
+ accent: american accent, british accent, australian accent, ...
1376
+
1377
+ Chinese (full-width comma separated):
1378
+ gender: 男, 女
1379
+ age: 儿童, 少年, 青年, 中年, 老年
1380
+ pitch: 极低音调, 低音调, 中音调, 高音调, 极高音调
1381
+ style: 耳语
1382
+ dialect: 河南话, 陕西话, 四川话, 贵州话, 云南话,
1383
+ 桂林话, 济南话, 石家庄话, 甘肃话, 宁夏话,
1384
+ 青岛话, 东北话
1385
+
1386
+ Minor issues (auto-fixed):
1387
+ - Wrong separator (half-width comma in Chinese instruct or
1388
+ full-width comma in English instruct)
1389
+ - Leading / trailing commas
1390
+
1391
+ Major issues (raise ``ValueError``):
1392
+ - Unsupported or misspelled instruct items
1393
+ - Suggestions are offered for close matches
1394
+
1395
+ Args:
1396
+ instruct: Raw instruct string, or ``None``.
1397
+ use_zh: If True, normalise all items to Chinese (used when the
1398
+ synthesis text contains Chinese and no accent is specified).
1399
+
1400
+ Returns:
1401
+ Normalised instruct string, or ``None``.
1402
+
1403
+ Raises:
1404
+ ValueError: if any instruct item is unsupported or misspelled.
1405
+ """
1406
+ if instruct is None:
1407
+ return None
1408
+
1409
+ instruct_str = instruct.strip()
1410
+ if not instruct_str:
1411
+ return None
1412
+
1413
+ # Split on both half-width and full-width commas
1414
+ raw_items = re.split(r"\s*[,,]\s*", instruct_str)
1415
+ raw_items = [x for x in raw_items if x]
1416
+
1417
+ # Validate each item
1418
+ unknown = []
1419
+ normalised = []
1420
+ for raw in raw_items:
1421
+ n = raw.strip().lower()
1422
+ if n in _INSTRUCT_ALL_VALID:
1423
+ normalised.append(n)
1424
+ else:
1425
+ sug = difflib.get_close_matches(n, _INSTRUCT_ALL_VALID, n=1, cutoff=0.6)
1426
+ unknown.append((raw, n, sug[0] if sug else None))
1427
+
1428
+ if unknown:
1429
+ lines = []
1430
+ for raw, n, sug in unknown:
1431
+ if sug:
1432
+ lines.append(f" '{raw}' -> '{n}' (unsupported; did you mean '{sug}'?)")
1433
+ else:
1434
+ lines.append(f" '{raw}' -> '{n}' (unsupported)")
1435
+ err = (
1436
+ f"Unsupported instruct items found in {instruct_str}:\n"
1437
+ + "\n".join(lines)
1438
+ + "\n\nValid English items: "
1439
+ + ", ".join(sorted(_INSTRUCT_VALID_EN))
1440
+ + "\nValid Chinese items: "
1441
+ + ",".join(sorted(_INSTRUCT_VALID_ZH))
1442
+ + "\n\nTip: Use only English or only Chinese instructs. "
1443
+ "English instructs should use comma + space (e.g. "
1444
+ "'male, indian accent'),\nChinese instructs should use full-width "
1445
+ "comma (e.g. '男,河南话')."
1446
+ )
1447
+ raise ValueError(err)
1448
+
1449
+ # --- Language consistency: dialect forces Chinese, accent forces English ---
1450
+ has_dialect = any(n.endswith("话") for n in normalised)
1451
+ has_accent = any(" accent" in n for n in normalised)
1452
+
1453
+ if has_dialect and has_accent:
1454
+ raise ValueError(
1455
+ "Cannot mix Chinese dialect and English accent in a single instruct. "
1456
+ "Dialects are for Chinese speech, accents for English speech."
1457
+ )
1458
+
1459
+ if has_dialect:
1460
+ use_zh = True
1461
+ elif has_accent:
1462
+ use_zh = False
1463
+
1464
+ # --- Unify to single language ---
1465
+ if use_zh:
1466
+ normalised = [_INSTRUCT_EN_TO_ZH.get(n, n) for n in normalised]
1467
+ else:
1468
+ normalised = [_INSTRUCT_ZH_TO_EN.get(n, n) for n in normalised]
1469
+
1470
+ # --- Category conflict check ---
1471
+ conflicts = []
1472
+ for cat in _INSTRUCT_MUTUALLY_EXCLUSIVE:
1473
+ hits = [n for n in normalised if n in cat]
1474
+ if len(hits) > 1:
1475
+ conflicts.append(hits)
1476
+ if conflicts:
1477
+ parts = []
1478
+ for group in conflicts:
1479
+ parts.append(" vs ".join(f"'{x}'" for x in group))
1480
+ raise ValueError(
1481
+ "Conflicting instruct items within the same category: "
1482
+ + "; ".join(parts)
1483
+ + ". Each category (gender, age, pitch, style, accent, dialect) "
1484
+ "allows at most one item."
1485
+ )
1486
+
1487
+ # Determine separator based on language
1488
+ has_zh = any(any("\u4e00" <= c <= "\u9fff" for c in n) for n in normalised)
1489
+ separator = "," if has_zh else ", "
1490
+
1491
+ return separator.join(normalised)
1492
+
1493
+
1494
+ def _filter_top_k(logits: torch.Tensor, ratio: float = 0.1) -> torch.Tensor:
1495
+ k = math.ceil(ratio * logits.shape[-1])
1496
+ val, ind = logits.topk(k, dim=-1)
1497
+ probs = torch.full_like(logits, float("-inf"))
1498
+ probs.scatter_(-1, ind, val)
1499
+ return probs
1500
+
1501
+
1502
+ def _gumbel_sample(logits: torch.Tensor, temperature: float) -> torch.Tensor:
1503
+ scaled_logits = logits / temperature
1504
+ u = torch.rand_like(scaled_logits)
1505
+ gumbel_noise = -torch.log(-torch.log(u + 1e-10) + 1e-10)
1506
+ return scaled_logits + gumbel_noise
1507
+
1508
+
1509
+ def _get_time_steps(
1510
+ t_start: float = 0.0,
1511
+ t_end: float = 1.0,
1512
+ num_step: int = 10,
1513
+ t_shift: float = 1.0,
1514
+ device: torch.device = torch.device("cpu"),
1515
+ ) -> torch.Tensor:
1516
+ timesteps = torch.linspace(t_start, t_end, num_step + 1).to(device)
1517
+ timesteps = t_shift * timesteps / (1 + (t_shift - 1) * timesteps)
1518
+ return timesteps
1519
+
1520
+
1521
+ _NONVERBAL_PATTERN = re.compile(
1522
+ r"\[(laughter|sigh|confirmation-en|question-en|question-ah|question-oh|"
1523
+ r"question-ei|question-yi|surprise-ah|surprise-oh|surprise-wa|"
1524
+ r"surprise-yo|dissatisfaction-hnn)\]"
1525
+ )
1526
+
1527
+
1528
+ def _tokenize_with_nonverbal_tags(text: str, tokenizer) -> torch.Tensor:
1529
+ """Tokenize text containing non-verbal tags, handling each tag independently.
1530
+
1531
+ Non-verbal tags are tokenized standalone to guarantee consistent token
1532
+ IDs regardless of surrounding language context (Chinese, English, etc.).
1533
+
1534
+ Args:
1535
+ text: Full text string potentially containing non-verbal tags.
1536
+ tokenizer: HuggingFace text tokenizer instance.
1537
+ Returns:
1538
+ Token IDs tensor of shape (1, seq_len).
1539
+ """
1540
+ parts = []
1541
+ last_end = 0
1542
+ for m in _NONVERBAL_PATTERN.finditer(text):
1543
+ if m.start() > last_end:
1544
+ segment = text[last_end : m.start()]
1545
+ ids = tokenizer(segment, add_special_tokens=False).input_ids
1546
+ if ids:
1547
+ parts.append(ids)
1548
+ tag_ids = tokenizer(m.group(), add_special_tokens=False).input_ids
1549
+ if tag_ids:
1550
+ parts.append(tag_ids)
1551
+ last_end = m.end()
1552
+ if last_end < len(text):
1553
+ segment = text[last_end:]
1554
+ ids = tokenizer(segment, add_special_tokens=False).input_ids
1555
+ if ids:
1556
+ parts.append(ids)
1557
+
1558
+ if not parts:
1559
+ result = tokenizer(text, return_tensors="pt").input_ids
1560
+ else:
1561
+ combined = []
1562
+ for p in parts:
1563
+ combined.extend(p)
1564
+ result = torch.tensor([combined], dtype=torch.long)
1565
+ return result
1566
+
1567
+
1568
+ def _combine_text(text, ref_text: Optional[str] = None) -> str:
1569
+
1570
+ # combine with reference text if not None
1571
+ if ref_text:
1572
+ full_text = ref_text.strip() + " " + text.strip()
1573
+ else:
1574
+ full_text = text.strip()
1575
+
1576
+ # filter out newline / carriage-return characters
1577
+ full_text = re.sub(r"[\r\n]+", "", full_text)
1578
+
1579
+ # replace Chinese parentheses with English ones
1580
+ full_text = full_text.replace("\uff08", "(").replace("\uff09", ")")
1581
+
1582
+ # collapse consecutive spaces / tabs into a single space
1583
+ full_text = re.sub(r"[ \t]+", " ", full_text)
1584
+
1585
+ # remove spaces around chinese characters
1586
+ chinese_range = r"[\u4e00-\u9fff]"
1587
+ pattern = rf"(?<={chinese_range})\s+|\s+(?={chinese_range})"
1588
+ full_text = re.sub(pattern, "", full_text)
1589
+
1590
+ return full_text
1591
+
1592
+
1593
+ # ---------------------------------------------------------------------------
1594
+ # Register with HuggingFace Auto classes
1595
+ # ---------------------------------------------------------------------------
1596
+
1597
+ AutoConfig.register("omnivoice", OmniVoiceConfig)
1598
+ AutoModel.register(OmniVoiceConfig, OmniVoice)
omnivoice/scripts/__init__.py ADDED
File without changes
omnivoice/scripts/denoise_audio.py ADDED
@@ -0,0 +1,1049 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Denoise audio with Sidon and pack results into WebDataset shards.
19
+
20
+ Supports two input modes:
21
+
22
+ 1. WebDataset manifest (data.lst):
23
+ python denoise_audio.py \
24
+ --input_manifest data.lst \
25
+ --tar_output_pattern output/audios/shard-%06d.tar \
26
+ --jsonl_output_pattern output/txts/shard-%06d.jsonl \
27
+ --feature_extractor_path sidon-v0.1/feature_extractor_cuda.pt \
28
+ --decoder_path sidon-v0.1/decoder_cuda.pt
29
+
30
+ 2. Raw JSONL (each line: {"id": "...", "audio_path": "...", ...}):
31
+ python denoise_audio.py \
32
+ --input_jsonl data.jsonl \
33
+ --tar_output_pattern output/audios/shard-%06d.tar \
34
+ --jsonl_output_pattern output/txts/shard-%06d.jsonl \
35
+ --feature_extractor_path sidon-v0.1/feature_extractor_cuda.pt \
36
+ --decoder_path sidon-v0.1/decoder_cuda.pt
37
+
38
+ Output structure:
39
+ output_dir/
40
+ ├── audios/ # WebDataset tar shards (.flac audio + .json metadata)
41
+ │ ├── shard_000000.tar
42
+ │ └── ...
43
+ ├── txts/ # Per-shard JSONL metadata
44
+ │ ├── shard_000000.jsonl
45
+ │ └── ...
46
+ ├── data.lst # Manifest: <tar_path> <jsonl_path> <sample_count> <total_duration>
47
+ └── errors.jsonl # Failed samples with error details
48
+ """
49
+
50
+ from __future__ import annotations
51
+
52
+ import argparse
53
+ import io
54
+ import json
55
+ import logging
56
+ import os
57
+ import pickle
58
+ import struct
59
+ import subprocess
60
+ import sys
61
+ import threading
62
+ from concurrent.futures import FIRST_COMPLETED, Future, wait
63
+ from dataclasses import dataclass
64
+ from pathlib import Path
65
+ from typing import Any, Dict, List, Optional, Sequence, Union
66
+
67
+ import numpy as np
68
+ import torch
69
+ import torchaudio
70
+ import webdataset as wds
71
+ from torch.utils.data import DataLoader
72
+ from tqdm.auto import tqdm
73
+
74
+ from omnivoice.data.batching import StreamLengthGroupDataset
75
+ from omnivoice.data.dataset import JsonlDatasetReader, WebDatasetReader
76
+ import soundfile as sf
77
+ from omnivoice.utils.common import str2bool
78
+
79
+ SIDON_INPUT_SAMPLE_RATE = 16_000
80
+ SIDON_OUTPUT_SAMPLE_RATE = 48_000
81
+
82
+
83
+ def build_parser() -> argparse.ArgumentParser:
84
+ parser = argparse.ArgumentParser(description=__doc__)
85
+
86
+ # ── Input (mutually exclusive) ──
87
+ parser.add_argument(
88
+ "--input_manifest",
89
+ default=None,
90
+ help="WebDataset manifest (data.lst). Each line: "
91
+ "<tar_path> <jsonl_path> <num_items> <duration>",
92
+ )
93
+ parser.add_argument(
94
+ "--input_jsonl",
95
+ default=None,
96
+ help="Raw JSONL file. Each line: " '{"id": "...", "audio_path": "...", ...}',
97
+ )
98
+
99
+ # ── Output ──
100
+ parser.add_argument(
101
+ "--tar_output_pattern",
102
+ default=None,
103
+ help="Tar shard pattern, e.g. output/audios/shard_%%06d.tar",
104
+ )
105
+ parser.add_argument(
106
+ "--jsonl_output_pattern",
107
+ default=None,
108
+ help="JSONL shard pattern, e.g. output/txts/shard_%%06d.jsonl",
109
+ )
110
+ parser.add_argument(
111
+ "--samples_per_shard",
112
+ type=int,
113
+ default=1_000,
114
+ help="Maximum records per output shard",
115
+ )
116
+
117
+ # ── Model ──
118
+ parser.add_argument(
119
+ "--feature_extractor_path",
120
+ default=None,
121
+ help="Path to feature_extractor_cuda.pt",
122
+ )
123
+ parser.add_argument(
124
+ "--decoder_path",
125
+ default=None,
126
+ help="Path to decoder_cuda.pt",
127
+ )
128
+ parser.add_argument(
129
+ "--target_sample_rate",
130
+ type=int,
131
+ default=24_000,
132
+ help="Sample rate of the denoised output audio",
133
+ )
134
+
135
+ # ── Filtering ──
136
+ parser.add_argument(
137
+ "--min_length",
138
+ type=float,
139
+ default=0.0,
140
+ help="Minimum audio duration in seconds",
141
+ )
142
+ parser.add_argument(
143
+ "--max_length",
144
+ type=float,
145
+ default=80.0,
146
+ help="Maximum audio duration in seconds",
147
+ )
148
+
149
+ # ── Batching ──
150
+ parser.add_argument(
151
+ "--batch_duration",
152
+ type=float,
153
+ default=200.0,
154
+ help="Target batch duration in seconds for dynamic batching",
155
+ )
156
+ parser.add_argument(
157
+ "--max_sample",
158
+ type=int,
159
+ default=32,
160
+ help="Maximum samples per batch for dynamic batching",
161
+ )
162
+
163
+ # ── Distributed ──
164
+ parser.add_argument(
165
+ "--num_machines",
166
+ type=int,
167
+ default=1,
168
+ help="Total number of machines for distributed runs",
169
+ )
170
+ parser.add_argument(
171
+ "--machine_index",
172
+ type=int,
173
+ default=0,
174
+ help="Zero-based machine index when distributing across multiple "
175
+ "machines (e.g. 0, 1, ... num_machines-1)",
176
+ )
177
+
178
+ # ── Parallelism ──
179
+ parser.add_argument(
180
+ "--nj_per_gpu",
181
+ type=int,
182
+ default=1,
183
+ help="Worker processes per GPU (default 1)",
184
+ )
185
+ parser.add_argument(
186
+ "--loader_workers",
187
+ type=int,
188
+ default=16,
189
+ help="PyTorch DataLoader worker threads",
190
+ )
191
+
192
+ # ── Data order (JSONL mode) ──
193
+ parser.add_argument(
194
+ "--shuffle",
195
+ type=str2bool,
196
+ default=True,
197
+ help="Shuffle JSONL entries",
198
+ )
199
+ parser.add_argument(
200
+ "--shuffle_seed",
201
+ type=int,
202
+ default=42,
203
+ help="Seed for JSONL shuffle",
204
+ )
205
+
206
+ # ── Error handling ──
207
+ parser.add_argument(
208
+ "--skip_errors",
209
+ action="store_true",
210
+ help="Skip items that fail to denoise instead of aborting",
211
+ )
212
+ parser.add_argument(
213
+ "--_subprocess_worker",
214
+ action="store_true",
215
+ help=argparse.SUPPRESS,
216
+ )
217
+ return parser
218
+
219
+
220
+ # ---------------------------------------------------------------------------
221
+ # Utilities
222
+ # ---------------------------------------------------------------------------
223
+
224
+
225
+ def count_lines(path: str) -> int:
226
+ """Count newlines efficiently by reading binary chunks."""
227
+ count = 0
228
+ with open(path, "rb") as f:
229
+ for chunk in iter(lambda: f.read(1 << 20), b""):
230
+ count += chunk.count(b"\n")
231
+ return count
232
+
233
+
234
+ PaddingStrategy = Union[bool, str]
235
+ ReturnType = Union[torch.Tensor, np.ndarray]
236
+
237
+
238
+ def extract_seamless_m4t_features(
239
+ raw_speech: Union[torch.Tensor, List[float], List[torch.Tensor], List[List[float]]],
240
+ sampling_rate: int = 16000,
241
+ num_mel_bins: int = 80,
242
+ frame_length: int = 25,
243
+ frame_shift: int = 10,
244
+ preemphasis_coefficient: float = 0.97,
245
+ dither: float = 0.0,
246
+ window_type: str = "povey",
247
+ do_normalize_per_mel_bins: bool = True,
248
+ stride: int = 2,
249
+ padding: PaddingStrategy = "longest",
250
+ max_length: Optional[int] = None,
251
+ pad_to_multiple_of: Optional[int] = 2,
252
+ return_tensors: Optional[str] = "pt",
253
+ return_attention_mask: bool = True,
254
+ padding_value: float = 0.0,
255
+ device: torch.device = torch.device("cpu"),
256
+ ) -> Dict[str, ReturnType]:
257
+ """Extract SeamlessM4T features using Torch-only operators."""
258
+ if not isinstance(raw_speech, list):
259
+ raw_speech = [raw_speech]
260
+
261
+ processed_speech = [
262
+ torch.as_tensor(sample, dtype=torch.float32, device=device)
263
+ for sample in raw_speech
264
+ ]
265
+
266
+ features: List[torch.Tensor] = []
267
+ for waveform in processed_speech:
268
+ if waveform.ndim > 1:
269
+ waveform = waveform[0]
270
+ waveform_tensor = waveform.unsqueeze(0)
271
+ feature = torchaudio.compliance.kaldi.fbank(
272
+ waveform=waveform_tensor,
273
+ sample_frequency=sampling_rate,
274
+ num_mel_bins=num_mel_bins,
275
+ frame_length=frame_length,
276
+ frame_shift=frame_shift,
277
+ dither=dither,
278
+ preemphasis_coefficient=preemphasis_coefficient,
279
+ remove_dc_offset=True,
280
+ window_type=window_type,
281
+ use_energy=False,
282
+ energy_floor=1.192092955078125e-07,
283
+ )
284
+ features.append(feature.squeeze(0))
285
+
286
+ if do_normalize_per_mel_bins:
287
+ normalised: List[torch.Tensor] = []
288
+ for feature in features:
289
+ mean = feature.mean(0, keepdim=True)
290
+ var = feature.var(0, keepdim=True)
291
+ normalised.append((feature - mean) / torch.sqrt(var + 1e-5))
292
+ features = normalised
293
+
294
+ def _pad_batch(
295
+ features: List[torch.Tensor],
296
+ padding_strategy: PaddingStrategy = "longest",
297
+ max_length: Optional[int] = None,
298
+ pad_to_multiple_of: Optional[int] = None,
299
+ padding_value: float = 0.0,
300
+ ) -> tuple[torch.Tensor, torch.Tensor]:
301
+ if padding_strategy == "longest":
302
+ target_length = max(f.shape[0] for f in features)
303
+ elif max_length is not None:
304
+ target_length = max_length
305
+ else:
306
+ raise ValueError(
307
+ "max_length must be provided when padding_strategy is not 'longest'"
308
+ )
309
+
310
+ if pad_to_multiple_of is not None:
311
+ target_length = (
312
+ (target_length + pad_to_multiple_of - 1)
313
+ // pad_to_multiple_of
314
+ * pad_to_multiple_of
315
+ )
316
+
317
+ batch_size = len(features)
318
+ feature_dim = features[0].shape[1]
319
+ device = features[0].device
320
+
321
+ padded_features = torch.full(
322
+ (batch_size, target_length, feature_dim),
323
+ padding_value,
324
+ dtype=torch.float32,
325
+ device=device,
326
+ )
327
+ attention_mask = torch.zeros(
328
+ (batch_size, target_length),
329
+ dtype=torch.int64,
330
+ device=device,
331
+ )
332
+
333
+ for index, feature_tensor in enumerate(features):
334
+ seq_len = feature_tensor.shape[0]
335
+ padded_features[index, :seq_len] = feature_tensor
336
+ attention_mask[index, :seq_len] = 1
337
+
338
+ return padded_features, attention_mask
339
+
340
+ input_features, attention_mask = _pad_batch(
341
+ features,
342
+ padding_strategy=padding,
343
+ max_length=max_length,
344
+ pad_to_multiple_of=pad_to_multiple_of,
345
+ padding_value=padding_value,
346
+ )
347
+
348
+ batch_size, num_frames, num_channels = input_features.shape
349
+ new_num_frames = (num_frames // stride) * stride
350
+ input_features = input_features[:, :new_num_frames, :]
351
+ if return_attention_mask:
352
+ attention_mask = attention_mask[:, :new_num_frames]
353
+
354
+ input_features = input_features.reshape(
355
+ batch_size, new_num_frames // stride, num_channels * stride
356
+ )
357
+
358
+ output: Dict[str, ReturnType] = {"input_features": input_features}
359
+ if return_attention_mask:
360
+ output["attention_mask"] = attention_mask[:, 1::stride]
361
+
362
+ if return_tensors == "np":
363
+ for key, value in output.items():
364
+ output[key] = value.cpu().numpy() # type: ignore[assignment]
365
+
366
+ return output
367
+
368
+
369
+ def serialise_flac(key: str, waveform: torch.Tensor, sample_rate: int) -> dict:
370
+ buffer = io.BytesIO()
371
+ audio = waveform.to(dtype=torch.float32).cpu().numpy()
372
+ if audio.ndim == 2:
373
+ audio = audio.T # (C, T) → (T, C) for soundfile
374
+ sf.write(buffer, audio, sample_rate, format="FLAC")
375
+ return {"__key__": key, "flac": buffer.getvalue()}
376
+
377
+
378
+ def _normalise_value(value: Any) -> Any:
379
+ """Convert tensors and NumPy scalars to serialisable Python objects."""
380
+ if isinstance(value, torch.Tensor):
381
+ if value.ndim == 0:
382
+ return value.item()
383
+ return value.cpu().tolist()
384
+ if isinstance(value, np.generic):
385
+ return value.item()
386
+ if isinstance(value, np.ndarray):
387
+ return value.tolist()
388
+ return value
389
+
390
+
391
+ def _encode_metadata(metadata: dict[str, Any]) -> bytes:
392
+ cleaned: dict[str, Any] = {}
393
+ for key, value in metadata.items():
394
+ if value is None:
395
+ continue
396
+ cleaned[key] = _normalise_value(value)
397
+ return json.dumps(cleaned, ensure_ascii=False).encode("utf-8")
398
+
399
+
400
+ # ---------------------------------------------------------------------------
401
+ # Denoising model
402
+ # ---------------------------------------------------------------------------
403
+
404
+
405
+ class SpeechDenoisingProcessor:
406
+ """Run the TorchScripted feature extractor and decoder."""
407
+
408
+ def __init__(
409
+ self,
410
+ feature_extractor_path: str,
411
+ decoder_path: str,
412
+ device: str,
413
+ ) -> None:
414
+ self.device = torch.device(device)
415
+ self.feature_extractor = torch.jit.load(
416
+ feature_extractor_path, map_location=self.device
417
+ )
418
+ self.decoder = torch.jit.load(decoder_path, map_location=self.device)
419
+ self.feature_extractor.eval()
420
+ self.decoder.eval()
421
+
422
+ @torch.inference_mode()
423
+ def process(self, waveform: torch.Tensor, sample_rate: int) -> torch.Tensor:
424
+ return self.process_batch([waveform], [sample_rate])[0]
425
+
426
+ @torch.inference_mode()
427
+ def process_batch(
428
+ self,
429
+ waveforms: Sequence[torch.Tensor] | torch.Tensor,
430
+ sample_rates: Optional[Sequence[int]] = None,
431
+ expected_lengths: Optional[Sequence[int]] = None,
432
+ ) -> List[torch.Tensor]:
433
+ if expected_lengths is None:
434
+ expected_lengths: list[int] = []
435
+ for waveform, sample_rate in zip(waveforms, sample_rates):
436
+ duration_seconds = waveform.shape[-1] / float(sample_rate)
437
+ expected_lengths.append(
438
+ int(round(duration_seconds * SIDON_OUTPUT_SAMPLE_RATE))
439
+ )
440
+ waveforms = torch.nn.functional.pad(waveforms, (0, 24000))
441
+
442
+ features = extract_seamless_m4t_features(
443
+ [x for x in waveforms],
444
+ return_tensors="pt",
445
+ padding_value=1.0,
446
+ device=self.device,
447
+ )
448
+ feature_tensor = self.feature_extractor(
449
+ features["input_features"].to(self.device)
450
+ )["last_hidden_state"]
451
+ restored_waveforms = self.decoder(feature_tensor.transpose(1, 2)).cpu()
452
+
453
+ results: List[torch.Tensor] = []
454
+ for sample_idx, sample in enumerate(restored_waveforms):
455
+ restored_waveform = sample.view(-1)
456
+ target_length = expected_lengths[sample_idx]
457
+ current_length = restored_waveform.shape[-1]
458
+ if target_length > 0 and current_length != target_length:
459
+ diff = target_length - current_length
460
+ if diff > 0:
461
+ restored_waveform = torch.nn.functional.pad(
462
+ restored_waveform, (0, diff)
463
+ )
464
+ elif diff < 0:
465
+ restored_waveform = restored_waveform[:target_length]
466
+ results.append(restored_waveform.contiguous())
467
+
468
+ return results
469
+
470
+
471
+ # ---------------------------------------------------------------------------
472
+ # Batch collation
473
+ # ---------------------------------------------------------------------------
474
+
475
+
476
+ class CollateFunction:
477
+ """Collate a list of samples into a padded batch."""
478
+
479
+ def __init__(
480
+ self,
481
+ sample_rate: int,
482
+ skip_errors: bool,
483
+ ) -> None:
484
+ self.sample_rate = sample_rate
485
+ self.skip_errors = skip_errors
486
+
487
+ def __call__(self, samples: Sequence[dict[str, Any]]) -> CollatedBatch:
488
+ keys: list[str] = []
489
+ waveforms: list[torch.Tensor] = []
490
+ durations: list[float] = []
491
+ metadata: list[dict[str, Any]] = []
492
+
493
+ for sample in samples:
494
+ keys.append(sample["label"]["id"])
495
+ waveforms.append(sample["audio"].squeeze(0))
496
+ durations.append(sample["audio"].size(-1) / self.sample_rate)
497
+ metadata.append(sample["label"])
498
+ waveforms = torch.nn.utils.rnn.pad_sequence(waveforms, batch_first=True)
499
+
500
+ return CollatedBatch(
501
+ keys=keys, waveforms=waveforms, durations=durations, metadata=metadata
502
+ )
503
+
504
+
505
+ @dataclass
506
+ class CollatedBatch:
507
+ """Batch payload returned by the DataLoader collate function."""
508
+
509
+ keys: list[str]
510
+ waveforms: list[torch.Tensor]
511
+ durations: list[float]
512
+ metadata: list[dict[str, Any]]
513
+
514
+ @property
515
+ def size(self) -> int:
516
+ return len(self.keys)
517
+
518
+
519
+ # ---------------------------------------------------------------------------
520
+ # Subprocess-based GPU worker pool
521
+ # ---------------------------------------------------------------------------
522
+ #
523
+ # Problem: PyTorch ≥2.8 caches CUDA device state at import time. Neither
524
+ # forkserver nor spawn lets us change CUDA_VISIBLE_DEVICES *before* the CUDA
525
+ # runtime captures the device list. The only reliable approach is to launch
526
+ # each worker as a **subprocess** with CUDA_VISIBLE_DEVICES set in the
527
+ # subprocess environment, guaranteeing it takes effect before `import torch`.
528
+ #
529
+ # Protocol (parent ↔ child, length-prefixed pickle over stdin/stdout):
530
+ # Parent → child: 4-byte LE uint32 length + pickle(CollatedBatch)
531
+ # Child → parent: 4-byte LE uint32 length + pickle(result dict)
532
+ # Shutdown signal: 4 zero bytes (length == 0)
533
+
534
+
535
+ def _subprocess_recv():
536
+ """Read a length-prefixed pickled object from stdin. Returns None on shutdown."""
537
+ raw = sys.stdin.buffer.read(4)
538
+ if len(raw) < 4:
539
+ return None
540
+ (length,) = struct.unpack("<I", raw)
541
+ if length == 0:
542
+ return None
543
+ data = sys.stdin.buffer.read(length)
544
+ return pickle.loads(data)
545
+
546
+
547
+ def _subprocess_send(obj):
548
+ """Send a pickled object with a 4-byte length prefix to stdout."""
549
+ data = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
550
+ sys.stdout.buffer.write(struct.pack("<I", len(data)))
551
+ sys.stdout.buffer.write(data)
552
+ sys.stdout.buffer.flush()
553
+
554
+
555
+ def subprocess_worker_main():
556
+ """Entry point for a GPU worker subprocess.
557
+
558
+ Expected environment: CUDA_VISIBLE_DEVICES already set by the parent.
559
+ Receives initargs via stdin, then processes batches in a loop.
560
+ """
561
+ formatter = "%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] [Worker PID %(process)d] %(message)s"
562
+ logging.basicConfig(format=formatter, level=logging.INFO, force=True)
563
+
564
+ initargs = _subprocess_recv()
565
+ feature_extractor_path, decoder_path = initargs
566
+
567
+ device = "cpu"
568
+ if torch.cuda.is_available():
569
+ torch.cuda.set_device(0)
570
+ device = "cuda:0"
571
+ else:
572
+ logging.warning("CUDA not available in worker subprocess.")
573
+
574
+ logging.info(
575
+ f"Worker PID={os.getpid()}, "
576
+ f"CUDA_VISIBLE_DEVICES={os.environ.get('CUDA_VISIBLE_DEVICES')}, device={device}"
577
+ )
578
+
579
+ processor = SpeechDenoisingProcessor(
580
+ feature_extractor_path=feature_extractor_path,
581
+ decoder_path=decoder_path,
582
+ device=device,
583
+ )
584
+
585
+ # Process batches until shutdown signal
586
+ while True:
587
+ msg = _subprocess_recv()
588
+ if msg is None:
589
+ break
590
+ req_id = msg["_req_id"]
591
+ batch = msg["_batch"]
592
+ try:
593
+ cleaned_waveforms = processor.process_batch(
594
+ batch.waveforms,
595
+ expected_lengths=[
596
+ round(d * SIDON_OUTPUT_SAMPLE_RATE) for d in batch.durations
597
+ ],
598
+ )
599
+ cleaned_cpu = [w.cpu() for w in cleaned_waveforms]
600
+ result = {
601
+ "_req_id": req_id,
602
+ "status": "success",
603
+ "keys": batch.keys,
604
+ "results": cleaned_cpu,
605
+ "metadata": batch.metadata,
606
+ "size": batch.size,
607
+ }
608
+ except Exception as e:
609
+ result = {
610
+ "_req_id": req_id,
611
+ "status": "error",
612
+ "keys": batch.keys,
613
+ "error": str(e),
614
+ "size": batch.size,
615
+ }
616
+ _subprocess_send(result)
617
+
618
+
619
+ class _GPUWorker:
620
+ """Handle to a single GPU worker subprocess."""
621
+
622
+ def __init__(self, physical_gpu_id, feature_extractor_path, decoder_path):
623
+ env = os.environ.copy()
624
+ if physical_gpu_id is not None:
625
+ env["CUDA_VISIBLE_DEVICES"] = str(physical_gpu_id)
626
+ self.proc = subprocess.Popen(
627
+ [
628
+ sys.executable,
629
+ "-m",
630
+ "omnivoice.scripts.denoise_audio",
631
+ "--_subprocess_worker",
632
+ ],
633
+ stdin=subprocess.PIPE,
634
+ stdout=subprocess.PIPE,
635
+ env=env,
636
+ )
637
+ # Send init args
638
+ init_data = pickle.dumps(
639
+ (feature_extractor_path, decoder_path), protocol=pickle.HIGHEST_PROTOCOL
640
+ )
641
+ self.proc.stdin.write(struct.pack("<I", len(init_data)))
642
+ self.proc.stdin.write(init_data)
643
+ self.proc.stdin.flush()
644
+ self._lock = threading.Lock()
645
+
646
+ def submit(self, batch_with_id):
647
+ """Send a batch dict (containing _req_id + _batch) for processing."""
648
+ with self._lock:
649
+ data = pickle.dumps(batch_with_id, protocol=pickle.HIGHEST_PROTOCOL)
650
+ self.proc.stdin.write(struct.pack("<I", len(data)))
651
+ self.proc.stdin.write(data)
652
+ self.proc.stdin.flush()
653
+
654
+ def read_result(self):
655
+ """Blocking read for one result."""
656
+ raw = self.proc.stdout.read(4)
657
+ if len(raw) < 4:
658
+ return None
659
+ (length,) = struct.unpack("<I", raw)
660
+ if length == 0:
661
+ return None
662
+ data = self.proc.stdout.read(length)
663
+ return pickle.loads(data)
664
+
665
+ def shutdown(self):
666
+ """Send shutdown signal and wait for process."""
667
+ try:
668
+ with self._lock:
669
+ self.proc.stdin.write(struct.pack("<I", 0))
670
+ self.proc.stdin.flush()
671
+ except Exception:
672
+ pass
673
+ self.proc.wait(timeout=30)
674
+
675
+
676
+ class GPUWorkerPool:
677
+ """Pool of GPU worker subprocesses with round-robin task submission."""
678
+
679
+ def __init__(self, pool_specs, feature_extractor_path, decoder_path):
680
+ """
681
+ Args:
682
+ pool_specs: list of (physical_gpu_id, num_workers) tuples.
683
+ feature_extractor_path: path to JIT feature extractor.
684
+ decoder_path: path to JIT decoder.
685
+ """
686
+ self.workers: list[_GPUWorker] = []
687
+ for physical_gpu_id, num_workers in pool_specs:
688
+ for _ in range(num_workers):
689
+ self.workers.append(
690
+ _GPUWorker(physical_gpu_id, feature_extractor_path, decoder_path)
691
+ )
692
+ self._rr = 0
693
+ self._futures: dict[int, Future] = {}
694
+ self._futures_lock = threading.Lock()
695
+ self._next_id = 0
696
+ # Start reader threads for each worker
697
+ self._reader_threads = []
698
+ for worker in self.workers:
699
+ t = threading.Thread(target=self._reader_loop, args=(worker,), daemon=True)
700
+ t.start()
701
+ self._reader_threads.append(t)
702
+
703
+ def _reader_loop(self, worker):
704
+ while True:
705
+ result = worker.read_result()
706
+ if result is None:
707
+ break
708
+ req_id = result.pop("_req_id", None)
709
+ with self._futures_lock:
710
+ fut = self._futures.pop(req_id, None)
711
+ if fut is not None:
712
+ fut.set_result(result)
713
+
714
+ def submit(self, batch) -> Future:
715
+ worker = self.workers[self._rr % len(self.workers)]
716
+ self._rr += 1
717
+ with self._futures_lock:
718
+ req_id = self._next_id
719
+ self._next_id += 1
720
+ fut = Future()
721
+ self._futures[req_id] = fut
722
+ batch_dict = {
723
+ "_req_id": req_id,
724
+ "_batch": batch,
725
+ }
726
+ worker.submit(batch_dict)
727
+ return fut
728
+
729
+ def shutdown(self):
730
+ for worker in self.workers:
731
+ worker.shutdown()
732
+ for t in self._reader_threads:
733
+ t.join(timeout=5)
734
+
735
+
736
+ # ---------------------------------------------------------------------------
737
+ # Main
738
+ # ---------------------------------------------------------------------------
739
+
740
+
741
+ def main() -> None:
742
+ formatter = "%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s"
743
+ logging.basicConfig(format=formatter, level=logging.INFO, force=True)
744
+ parser = build_parser()
745
+ args = parser.parse_args()
746
+
747
+ # ── Subprocess worker mode ──
748
+ if args._subprocess_worker:
749
+ subprocess_worker_main()
750
+ return
751
+
752
+ # Validate input arguments
753
+ assert args.tar_output_pattern is not None, "--tar_output_pattern is required."
754
+ assert args.jsonl_output_pattern is not None, "--jsonl_output_pattern is required."
755
+ assert bool(args.input_manifest) != bool(
756
+ args.input_jsonl
757
+ ), "Exactly one of --input_manifest or --input_jsonl must be provided."
758
+
759
+ if args.num_machines > 1:
760
+ assert (
761
+ 0 <= args.machine_index < args.num_machines
762
+ ), f"machine_index {args.machine_index} must be in [0, {args.num_machines})"
763
+
764
+ # ── Build base dataset and count total samples ──
765
+ if args.input_jsonl:
766
+ logging.info(f"Input mode: raw JSONL ({args.input_jsonl})")
767
+ total_samples = count_lines(args.input_jsonl)
768
+ base_dataset = JsonlDatasetReader(
769
+ args.input_jsonl,
770
+ sample_rate=SIDON_INPUT_SAMPLE_RATE,
771
+ shuffle=args.shuffle,
772
+ shuffle_seed=args.shuffle_seed,
773
+ )
774
+ loader_workers = args.loader_workers
775
+ else:
776
+ logging.info(f"Input mode: WebDataset manifest ({args.input_manifest})")
777
+ manifest_num_lines = count_lines(args.input_manifest)
778
+ loader_workers = min(args.loader_workers, manifest_num_lines)
779
+ total_samples = 0
780
+ manifests = []
781
+ with open(args.input_manifest, "r", encoding="utf-8") as f:
782
+ for line_id, line in tqdm(
783
+ enumerate(f),
784
+ total=manifest_num_lines,
785
+ desc="Calculating dataset length",
786
+ ):
787
+ items = line.strip().split(" ")
788
+ tar_path, jsonl_path, num_items, duration = (
789
+ items[0],
790
+ items[1],
791
+ int(items[2]),
792
+ float(items[3]),
793
+ )
794
+ assert os.path.exists(tar_path), f"File {tar_path} does not exist."
795
+ assert os.path.exists(jsonl_path), f"File {jsonl_path} does not exist."
796
+ assert jsonl_path.endswith(
797
+ ".jsonl"
798
+ ), f"File {jsonl_path} is not a .jsonl file."
799
+ if (
800
+ args.num_machines > 1
801
+ and line_id % args.num_machines != args.machine_index
802
+ ):
803
+ continue
804
+ total_samples += num_items
805
+ manifests.append((tar_path, jsonl_path, num_items, duration))
806
+ logging.info(
807
+ f"Total shards: {manifest_num_lines}, "
808
+ f"Shards for current index: {len(manifests)}"
809
+ )
810
+ base_dataset = WebDatasetReader(
811
+ manifests=manifests,
812
+ sample_rate=SIDON_INPUT_SAMPLE_RATE,
813
+ evaluation=True,
814
+ )
815
+
816
+ # ── Dynamic batching + DataLoader ──
817
+ batched_dataset = StreamLengthGroupDataset(
818
+ dataset=base_dataset,
819
+ batch_duration=args.batch_duration,
820
+ max_sample=args.max_sample,
821
+ min_length=args.min_length,
822
+ max_length=args.max_length,
823
+ )
824
+
825
+ collate_fn = CollateFunction(
826
+ skip_errors=args.skip_errors,
827
+ sample_rate=SIDON_INPUT_SAMPLE_RATE,
828
+ )
829
+
830
+ dataloader = DataLoader(
831
+ dataset=batched_dataset,
832
+ batch_size=None,
833
+ collate_fn=collate_fn,
834
+ num_workers=loader_workers,
835
+ prefetch_factor=10 if loader_workers > 0 else None,
836
+ pin_memory=True,
837
+ persistent_workers=loader_workers > 0,
838
+ )
839
+
840
+ # ── Multi-GPU process pool ──
841
+ num_devices = torch.cuda.device_count()
842
+ if num_devices == 0:
843
+ logging.warning("No GPUs detected - using CPU for processing")
844
+ num_processes = args.nj_per_gpu
845
+ else:
846
+ num_processes = num_devices * args.nj_per_gpu
847
+ logging.info(
848
+ f"GPU count: {num_devices}, Processes per GPU: {args.nj_per_gpu}, "
849
+ f"Total processes: {num_processes}"
850
+ )
851
+
852
+ # Build a list of (physical_gpu_id, num_workers) for each pool.
853
+ # When num_devices == 0 we use a single CPU pool.
854
+ if num_devices == 0:
855
+ pool_specs = [(None, num_processes)]
856
+ else:
857
+ pool_specs = [(gpu_id, args.nj_per_gpu) for gpu_id in range(num_devices)]
858
+
859
+ # ── Output paths ──
860
+ tar_output_pattern = str(Path(args.tar_output_pattern).expanduser())
861
+ jsonl_output_pattern = str(Path(args.jsonl_output_pattern).expanduser())
862
+ Path(tar_output_pattern).parent.mkdir(parents=True, exist_ok=True)
863
+ Path(jsonl_output_pattern).parent.mkdir(parents=True, exist_ok=True)
864
+
865
+ output_dir = Path(tar_output_pattern).parent.parent
866
+ error_log_path = str(output_dir / "errors.jsonl")
867
+ manifest_path = str(output_dir / "data.lst")
868
+
869
+ error_logger = logging.getLogger("error_log")
870
+ error_logger.setLevel(logging.ERROR)
871
+ error_logger.handlers.clear()
872
+ error_fh = logging.FileHandler(error_log_path, mode="w", encoding="utf-8")
873
+ error_fh.setFormatter(logging.Formatter("%(message)s"))
874
+ error_logger.addHandler(error_fh)
875
+
876
+ # ── Progress and shard tracking ──
877
+ processed_count = 0
878
+ error_count = 0
879
+ write_error_count = 0
880
+ failed_ids = []
881
+ shard_idx = 0
882
+ shard_sample_count = 0
883
+ shard_duration = 0.0
884
+ samples_per_shard = args.samples_per_shard
885
+ shard_manifest = {}
886
+ target_sample_rate = args.target_sample_rate
887
+
888
+ tar_writer = None
889
+ jsonl_file = None
890
+
891
+ def open_new_shard():
892
+ nonlocal tar_writer, jsonl_file, shard_idx, shard_sample_count, shard_duration
893
+ if tar_writer is not None:
894
+ tar_writer.close()
895
+ if jsonl_file is not None:
896
+ jsonl_file.close()
897
+ if shard_idx > 0 and shard_sample_count > 0:
898
+ prev_idx = shard_idx - 1
899
+ shard_manifest[prev_idx] = (
900
+ os.path.abspath(tar_output_pattern % prev_idx),
901
+ os.path.abspath(jsonl_output_pattern % prev_idx),
902
+ shard_sample_count,
903
+ shard_duration,
904
+ )
905
+ tar_fname = tar_output_pattern % shard_idx
906
+ jsonl_fname = jsonl_output_pattern % shard_idx
907
+ tar_writer = wds.TarWriter(tar_fname)
908
+ jsonl_file = open(jsonl_fname, "w", encoding="utf-8")
909
+ shard_idx += 1
910
+ shard_sample_count = 0
911
+ shard_duration = 0.0
912
+
913
+ def write_sample(key, waveform, metadata):
914
+ nonlocal shard_sample_count, write_error_count, shard_duration
915
+ assert tar_writer is not None and jsonl_file is not None
916
+ try:
917
+ if target_sample_rate != SIDON_OUTPUT_SAMPLE_RATE:
918
+ waveform = torchaudio.functional.resample(
919
+ waveform,
920
+ orig_freq=SIDON_OUTPUT_SAMPLE_RATE,
921
+ new_freq=target_sample_rate,
922
+ )
923
+ waveform = (waveform / (waveform.abs().max() + 1e-7)) * 0.6
924
+
925
+ record = serialise_flac(key, waveform, target_sample_rate)
926
+ jsonl_record = _encode_metadata(metadata)
927
+ tar_writer.write(record)
928
+ jsonl_file.write(jsonl_record.decode("utf-8") + "\n")
929
+ shard_sample_count += 1
930
+ shard_duration += metadata.get("audio_duration", 0.0)
931
+ except Exception as exc:
932
+ write_error_count += 1
933
+ failed_ids.append(key)
934
+ error_logger.error(
935
+ json.dumps({"id": key, "reason": str(exc)}, ensure_ascii=False)
936
+ )
937
+ logging.error(f"Write failed for sample {key}: {exc}")
938
+
939
+ def handle_result(result):
940
+ nonlocal processed_count, error_count
941
+ if result["status"] == "success":
942
+ for key, cleaned, metadata in zip(
943
+ result["keys"], result["results"], result["metadata"]
944
+ ):
945
+ if tar_writer is None or shard_sample_count >= samples_per_shard:
946
+ open_new_shard()
947
+ write_sample(key, cleaned, metadata)
948
+ processed_count += 1
949
+ else:
950
+ error_count += result["size"]
951
+ failed_ids.extend(result["keys"])
952
+ for key in result["keys"]:
953
+ error_logger.error(
954
+ json.dumps(
955
+ {"id": key, "reason": result["error"]},
956
+ ensure_ascii=False,
957
+ )
958
+ )
959
+ if not args.skip_errors:
960
+ raise RuntimeError(
961
+ f"Batch starting with {result['keys'][0]} failed - terminating"
962
+ )
963
+ logging.warning(
964
+ f"Skipping failed batch starting with {result['keys'][0]}: "
965
+ f"{result['error']}"
966
+ )
967
+
968
+ # ── Main processing loop ──
969
+ main_progress = tqdm(total=total_samples, desc="Denoising Audio")
970
+
971
+ # Launch subprocess-based GPU workers. CUDA_VISIBLE_DEVICES is set in the
972
+ # subprocess Popen environment so it takes effect before import torch.
973
+ pool = GPUWorkerPool(pool_specs, args.feature_extractor_path, args.decoder_path)
974
+ logging.info(f"Submitting tasks... ({num_processes} subprocess workers)")
975
+ try:
976
+ futures = set()
977
+ max_pending = num_processes * 2
978
+
979
+ def drain_completed():
980
+ nonlocal futures
981
+ done, _ = wait(futures, return_when=FIRST_COMPLETED)
982
+ for f in done:
983
+ futures.discard(f)
984
+ result = f.result()
985
+ main_progress.update(result["size"])
986
+ handle_result(result)
987
+ main_progress.set_postfix(
988
+ OK=processed_count,
989
+ Err=error_count,
990
+ )
991
+
992
+ for batch in dataloader:
993
+ if batch.size == 0:
994
+ continue
995
+ if len(futures) >= max_pending:
996
+ drain_completed()
997
+ futures.add(pool.submit(batch))
998
+
999
+ logging.info("Processing remaining pending batches...")
1000
+ while futures:
1001
+ drain_completed()
1002
+
1003
+ except Exception:
1004
+ logging.error("Critical error during processing", exc_info=True)
1005
+ raise
1006
+ finally:
1007
+ pool.shutdown()
1008
+ main_progress.close()
1009
+ if tar_writer is not None:
1010
+ tar_writer.close()
1011
+ if jsonl_file is not None:
1012
+ jsonl_file.close()
1013
+ if shard_idx > 0 and shard_sample_count > 0:
1014
+ last_idx = shard_idx - 1
1015
+ shard_manifest[last_idx] = (
1016
+ os.path.abspath(tar_output_pattern % last_idx),
1017
+ os.path.abspath(jsonl_output_pattern % last_idx),
1018
+ shard_sample_count,
1019
+ shard_duration,
1020
+ )
1021
+
1022
+ # ── Write manifest (data.lst) ──
1023
+ with open(manifest_path, "w", encoding="utf-8") as mf:
1024
+ for idx in sorted(shard_manifest.keys()):
1025
+ tar_path, jsonl_path, count, duration = shard_manifest[idx]
1026
+ mf.write(f"{tar_path} {jsonl_path} {count} {duration:.3f}\n")
1027
+
1028
+ # ── Summary ──
1029
+ total_failed = error_count + write_error_count
1030
+ filtered_and_skipped = total_samples - processed_count - total_failed
1031
+ logging.info(
1032
+ f"Processing Complete - Successful: {processed_count}, Failed: {total_failed}, "
1033
+ f"Filtered/Skipped: {filtered_and_skipped}, Shards written: {shard_idx}"
1034
+ )
1035
+ logging.info(f"Manifest written to: {manifest_path} ({len(shard_manifest)} shards)")
1036
+ if total_failed > 0:
1037
+ logging.info(f"Error details: {error_log_path}")
1038
+ if failed_ids and args.skip_errors:
1039
+ logging.warning(
1040
+ f"Failed sample IDs (count: {len(failed_ids)}): {failed_ids[:100]}..."
1041
+ )
1042
+ if write_error_count > 0 and not args.skip_errors:
1043
+ raise RuntimeError(
1044
+ f"{write_error_count} samples failed to write - check logs for details"
1045
+ )
1046
+
1047
+
1048
+ if __name__ == "__main__":
1049
+ main()
omnivoice/scripts/extract_audio_tokens.py ADDED
@@ -0,0 +1,625 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """
19
+ Extract audio tokens from audio data and pack them into WebDataset shards.
20
+
21
+ Supports two input modes:
22
+
23
+ 1. WebDataset manifest (data.lst):
24
+ python extract_audio_tokens.py \
25
+ --input_manifest data.lst \
26
+ --tar_output_pattern output/audios/shard-%06d.tar \
27
+ --jsonl_output_pattern output/txts/shard-%06d.jsonl
28
+
29
+ 2. Raw JSONL (each line: {"id": "...", "audio_path": "...", "text": "...", ...}):
30
+ python extract_audio_tokens.py \
31
+ --input_jsonl data.jsonl \
32
+ --tar_output_pattern output/audios/shard-%06d.tar \
33
+ --jsonl_output_pattern output/txts/shard-%06d.jsonl
34
+
35
+ Output structure:
36
+ output_dir/
37
+ ├── audios/ # WebDataset tar shards (.npy audio tokens + .json metadata)
38
+ │ ├── shard_000000.tar
39
+ │ └── ...
40
+ ├── txts/ # Per-shard JSONL metadata
41
+ │ ├── shard_000000.jsonl
42
+ │ └── ...
43
+ ├── data.lst # Manifest: <tar_path> <jsonl_path> <sample_count> <total_duration>
44
+ └── errors.jsonl # Failed samples with error details
45
+ """
46
+
47
+ import argparse
48
+ import io
49
+ import json
50
+ import logging
51
+ import multiprocessing as mp
52
+ import os
53
+ import warnings
54
+ from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait
55
+ from pathlib import Path
56
+ from typing import Any
57
+
58
+ import numpy as np
59
+ import torch
60
+ import webdataset as wds
61
+ from torch.utils.data import DataLoader, IterableDataset
62
+ from tqdm.auto import tqdm
63
+ from transformers import AutoFeatureExtractor, HiggsAudioV2TokenizerModel
64
+
65
+ from omnivoice.data.dataset import JsonlDatasetReader, WebDatasetReader
66
+ from omnivoice.utils.common import str2bool
67
+
68
+ warnings.filterwarnings(
69
+ "ignore", category=FutureWarning, module="torch.nn.utils.weight_norm"
70
+ )
71
+
72
+ HIGGS_INPUT_SAMPLE_RATE = 24_000
73
+
74
+
75
+ # Global variables: Store tokenizer and device for each worker process
76
+ worker_tokenizer = None
77
+ worker_feature_extractor = None
78
+
79
+
80
+ def build_parser() -> argparse.ArgumentParser:
81
+ parser = argparse.ArgumentParser(description=__doc__)
82
+ parser.add_argument(
83
+ "--input_manifest",
84
+ default=None,
85
+ help="Path to input dataset manifest (data.lst).",
86
+ )
87
+ parser.add_argument(
88
+ "--input_jsonl",
89
+ default=None,
90
+ help="Path to raw JSONL file (alternative to --input_manifest).",
91
+ )
92
+ parser.add_argument(
93
+ "--tar_output_pattern",
94
+ required=True,
95
+ help="Tar shard pattern passed to WebDataset",
96
+ )
97
+ parser.add_argument(
98
+ "--jsonl_output_pattern",
99
+ required=True,
100
+ help="Jsonl shard pattern passed to WebDataset",
101
+ )
102
+ parser.add_argument(
103
+ "--samples_per_shard",
104
+ type=int,
105
+ default=1000,
106
+ help="Maximum records per shard",
107
+ )
108
+ parser.add_argument(
109
+ "--min_num_shards",
110
+ type=int,
111
+ default=32,
112
+ help="Minimum number of output shards (use to ensure "
113
+ "shard count >= num_gpu * num_workers)",
114
+ )
115
+ parser.add_argument(
116
+ "--tokenizer_path",
117
+ type=str,
118
+ default="eustlb/higgs-audio-v2-tokenizer",
119
+ help="Path to audio tokenizer.",
120
+ )
121
+ parser.add_argument(
122
+ "--skip_errors", action="store_true", help="Skip items that fail to process"
123
+ )
124
+ parser.add_argument(
125
+ "--min_length",
126
+ type=float,
127
+ default=0.0,
128
+ help="Minimum audio duration in seconds (e.g. 2.0)",
129
+ )
130
+ parser.add_argument(
131
+ "--max_length",
132
+ type=float,
133
+ default=float("inf"),
134
+ help="Maximum audio duration in seconds (e.g. 15.0)",
135
+ )
136
+ parser.add_argument(
137
+ "--num_machines",
138
+ type=int,
139
+ default=1,
140
+ help="Total number of machines for distributed runs",
141
+ )
142
+ parser.add_argument(
143
+ "--machine_index",
144
+ type=int,
145
+ default=0,
146
+ help="Zero-based machine index when distributing across multiple "
147
+ "machines (e.g. 0, 1, ... num_machines-1)",
148
+ )
149
+ parser.add_argument(
150
+ "--nj_per_gpu",
151
+ type=int,
152
+ default=3,
153
+ help="Number of worker processes to spawn per GPU.",
154
+ )
155
+ parser.add_argument(
156
+ "--loader_workers",
157
+ type=int,
158
+ default=24,
159
+ help="Number of DataLoader workers for streaming IterableDataset.",
160
+ )
161
+ parser.add_argument(
162
+ "--shuffle",
163
+ type=str2bool,
164
+ default=True,
165
+ help="Shuffle data by default.",
166
+ )
167
+ parser.add_argument(
168
+ "--shuffle-seed",
169
+ type=int,
170
+ default=42,
171
+ help="Random seed for shuffle (default: 42).",
172
+ )
173
+ return parser
174
+
175
+
176
+ def count_lines(path):
177
+ with open(path, "rb") as f:
178
+ return sum(buf.count(b"\n") for buf in iter(lambda: f.read(1 << 20), b""))
179
+
180
+
181
+ def serialise_numpy(key: str, tokens: np.ndarray) -> dict:
182
+ buffer = io.BytesIO()
183
+ np.save(buffer, tokens)
184
+ return {"__key__": key, "npy": buffer.getvalue()}
185
+
186
+
187
+ def process_init(rank_queue, tokenizer_path):
188
+ """
189
+ Initialization function for each worker process.
190
+ Assigns a specific GPU to the process and loads the tokenizer.
191
+ """
192
+ global worker_tokenizer, worker_feature_extractor
193
+
194
+ # Configure worker process logging
195
+ formatter = (
196
+ "%(asctime)s %(levelname)s [%(filename)s:%(lineno)d]"
197
+ " [Worker %(process)d] %(message)s"
198
+ )
199
+ logging.basicConfig(format=formatter, level=logging.INFO, force=True)
200
+
201
+ # Get assigned GPU rank
202
+ rank = rank_queue.get()
203
+ # Determine device
204
+ if rank != -1 and torch.cuda.is_available():
205
+ worker_device = torch.device(f"cuda:{rank}")
206
+ else:
207
+ worker_device = torch.device("cpu")
208
+
209
+ logging.debug(f"Worker process initialized with device: {worker_device}")
210
+ # Load tokenizer onto the specified device
211
+ worker_feature_extractor = AutoFeatureExtractor.from_pretrained(tokenizer_path)
212
+ worker_tokenizer = HiggsAudioV2TokenizerModel.from_pretrained(
213
+ tokenizer_path, device_map=worker_device
214
+ )
215
+ logging.debug(f"Tokenizer loaded successfully on device {worker_device}")
216
+
217
+
218
+ def process_single_sample(sample: dict[str, Any]) -> dict[str, Any]:
219
+ """
220
+ Single-sample processing function executed in worker processes.
221
+ Skips invalid samples during streaming processing.
222
+ """
223
+ try:
224
+ audio_tensor = sample.get("audio", None) # shape (1, T)
225
+ if audio_tensor is None:
226
+ raise ValueError("Sample missing 'audio' field")
227
+
228
+ with torch.inference_mode():
229
+ key = sample["label"]["id"]
230
+ inputs = worker_feature_extractor(
231
+ raw_audio=audio_tensor.squeeze(0).numpy(),
232
+ sampling_rate=HIGGS_INPUT_SAMPLE_RATE,
233
+ return_tensors="pt",
234
+ ).to(worker_tokenizer.device)
235
+ audio_tokens = worker_tokenizer.encode(
236
+ inputs["input_values"],
237
+ ).audio_codes.squeeze(0)
238
+
239
+ assert len(audio_tokens.shape) == 2
240
+ assert audio_tokens.size(0) == 8
241
+
242
+ num_tokens = audio_tokens.size(1)
243
+ metadata = sample["label"]
244
+ metadata["num_tokens"] = num_tokens
245
+
246
+ # Convert to numpy format for subsequent serialization (int16 to save space)
247
+ audio_tokens_np = audio_tokens.to(torch.int16).cpu().numpy()
248
+
249
+ return {
250
+ "status": "success",
251
+ "key": key,
252
+ "audio_tokens": audio_tokens_np,
253
+ "metadata": metadata,
254
+ "error_msg": None,
255
+ }
256
+ except Exception as e:
257
+ sample_id = sample.get("label", {}).get("id", "unknown")
258
+ logging.error(f"Failed to process sample {sample_id}: {e}")
259
+ return {
260
+ "status": "error",
261
+ "key": sample_id,
262
+ "audio_tokens": None,
263
+ "metadata": None,
264
+ "error_msg": str(e),
265
+ }
266
+
267
+
268
+ def _normalise_value(value: Any) -> Any:
269
+ """Convert tensors and NumPy scalars to serialisable Python objects."""
270
+ if isinstance(value, torch.Tensor):
271
+ if value.ndim == 0:
272
+ return value.item()
273
+ return value.cpu().tolist()
274
+ if isinstance(value, np.generic):
275
+ return value.item()
276
+ if isinstance(value, np.ndarray):
277
+ return value.tolist()
278
+ return value
279
+
280
+
281
+ def _encode_metadata(metadata: dict[str, Any]) -> bytes:
282
+ cleaned: dict[str, Any] = {}
283
+ for key, value in metadata.items():
284
+ if value is None:
285
+ continue
286
+ cleaned[key] = _normalise_value(value)
287
+ return json.dumps(cleaned, ensure_ascii=False).encode("utf-8")
288
+
289
+
290
+ class StreamingLengthFilteredDataset(IterableDataset):
291
+ def __init__(
292
+ self,
293
+ base_iterable,
294
+ min_len: float,
295
+ max_len: float,
296
+ sr: int,
297
+ ):
298
+ self.base_iterable = base_iterable
299
+ self.min_len = min_len
300
+ self.max_len = max_len
301
+ self.sr = sr
302
+ self.filtered_count = 0
303
+
304
+ def __iter__(self):
305
+ """Stream samples one by one and filter on the fly."""
306
+ for sample in self.base_iterable:
307
+ try:
308
+ duration = sample["audio"].size(-1) / self.sr
309
+ if self.min_len <= duration <= self.max_len:
310
+ yield sample
311
+ else:
312
+ self.filtered_count += 1
313
+ logging.warning(
314
+ f"Filtered sample (duration out of range): "
315
+ f"{sample['label']['id']} ({duration:.2f}s)"
316
+ )
317
+ except Exception as e:
318
+ logging.warning(f"Skipped invalid sample during streaming: {e}")
319
+ continue
320
+
321
+
322
+ def main() -> None:
323
+ formatter = "%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s"
324
+ logging.basicConfig(format=formatter, level=logging.INFO, force=True)
325
+ parser = build_parser()
326
+ args = parser.parse_args()
327
+ mp.set_start_method("spawn", force=True)
328
+
329
+ # Validate input arguments
330
+ assert bool(args.input_manifest) != bool(
331
+ args.input_jsonl
332
+ ), "Exactly one of --input_manifest or --input_jsonl must be provided."
333
+
334
+ if args.num_machines > 1:
335
+ assert (
336
+ 0 <= args.machine_index < args.num_machines
337
+ ), f"machine_index {args.machine_index} must be in [0, {args.num_machines})"
338
+
339
+ # Build base dataset and count total samples based on input mode
340
+ if args.input_jsonl:
341
+ logging.info(f"Input mode: raw JSONL ({args.input_jsonl})")
342
+ total_samples = count_lines(args.input_jsonl)
343
+ base_dataset = JsonlDatasetReader(
344
+ args.input_jsonl,
345
+ sample_rate=HIGGS_INPUT_SAMPLE_RATE,
346
+ shuffle=args.shuffle,
347
+ shuffle_seed=args.shuffle_seed,
348
+ )
349
+ loader_workers = args.loader_workers
350
+ else:
351
+ logging.info(f"Input mode: WebDataset manifest ({args.input_manifest})")
352
+ manifest_num_lines = count_lines(args.input_manifest)
353
+ loader_workers = min(args.loader_workers, manifest_num_lines)
354
+ total_samples = 0
355
+ manifests = []
356
+ with open(args.input_manifest, "r", encoding="utf-8") as f:
357
+ for line_id, line in tqdm(
358
+ enumerate(f),
359
+ total=manifest_num_lines,
360
+ desc="Calculating dataset length",
361
+ ):
362
+ items = line.strip().split(" ")
363
+ tar_path, jsonl_path, num_items, duration = (
364
+ items[0],
365
+ items[1],
366
+ int(items[2]),
367
+ float(items[3]),
368
+ )
369
+ assert os.path.exists(tar_path), f"File {tar_path} does not exist."
370
+ assert os.path.exists(jsonl_path), f"File {jsonl_path} does not exist."
371
+ assert jsonl_path.endswith(
372
+ ".jsonl"
373
+ ), f"File {jsonl_path} is not a .jsonl file."
374
+ if (
375
+ args.num_machines > 1
376
+ and line_id % args.num_machines != args.machine_index
377
+ ):
378
+ continue
379
+ total_samples += num_items
380
+ manifests.append((tar_path, jsonl_path, num_items, duration))
381
+ logging.info(
382
+ f"Total shards: {manifest_num_lines}, "
383
+ f"Shards for current index: {len(manifests)}"
384
+ )
385
+ base_dataset = WebDatasetReader(
386
+ manifests=manifests,
387
+ sample_rate=HIGGS_INPUT_SAMPLE_RATE,
388
+ evaluation=True,
389
+ )
390
+
391
+ # Adjust samples_per_shard if min_num_shards would be violated
392
+ samples_per_shard = args.samples_per_shard
393
+ if total_samples > 0:
394
+ estimated_shards = max(
395
+ 1, (total_samples + samples_per_shard - 1) // samples_per_shard
396
+ )
397
+ if estimated_shards < args.min_num_shards:
398
+ samples_per_shard = max(1, total_samples // args.min_num_shards)
399
+ logging.info(
400
+ f"Adjusted samples_per_shard from {args.samples_per_shard} to "
401
+ f"{samples_per_shard} to meet min_num_shards={args.min_num_shards} "
402
+ f"(total_samples={total_samples})"
403
+ )
404
+
405
+ # Apply length filter and create DataLoader
406
+ filtered_dataset = StreamingLengthFilteredDataset(
407
+ base_iterable=base_dataset,
408
+ min_len=args.min_length,
409
+ max_len=args.max_length,
410
+ sr=HIGGS_INPUT_SAMPLE_RATE,
411
+ )
412
+ dataloader = DataLoader(
413
+ dataset=filtered_dataset,
414
+ batch_size=None,
415
+ num_workers=loader_workers,
416
+ persistent_workers=loader_workers > 0,
417
+ pin_memory=False,
418
+ )
419
+
420
+ # Configure multi-GPU multi-process setup
421
+ num_devices = torch.cuda.device_count()
422
+ if num_devices == 0:
423
+ logging.warning("No GPUs detected - using CPU for processing")
424
+ num_processes = args.nj_per_gpu
425
+ else:
426
+ num_processes = num_devices * args.nj_per_gpu
427
+ logging.info(
428
+ f"GPU count: {num_devices}, Processes per GPU: {args.nj_per_gpu}, "
429
+ f"Total processes: {num_processes}"
430
+ )
431
+
432
+ # Shared GPU rank queue for process assignment
433
+ manager = mp.Manager()
434
+ rank_queue = manager.Queue()
435
+ for rank in list(range(num_devices)) * args.nj_per_gpu:
436
+ rank_queue.put(rank)
437
+ if num_devices == 0:
438
+ for _ in range(num_processes):
439
+ rank_queue.put(-1)
440
+
441
+ # Prepare output paths
442
+ tar_output_pattern = str(Path(args.tar_output_pattern).expanduser())
443
+ jsonl_output_pattern = str(Path(args.jsonl_output_pattern).expanduser())
444
+ Path(tar_output_pattern).parent.mkdir(parents=True, exist_ok=True)
445
+ Path(jsonl_output_pattern).parent.mkdir(parents=True, exist_ok=True)
446
+
447
+ # Determine output directory from tar_output_pattern
448
+ output_dir = Path(tar_output_pattern).parent.parent
449
+ error_log_path = str(output_dir / "errors.jsonl")
450
+ manifest_path = str(output_dir / "data.lst")
451
+
452
+ # Setup error logger (writes to errors.jsonl)
453
+ error_logger = logging.getLogger("error_log")
454
+ error_logger.setLevel(logging.ERROR)
455
+ error_logger.handlers.clear()
456
+ error_fh = logging.FileHandler(error_log_path, mode="w", encoding="utf-8")
457
+ error_fh.setFormatter(logging.Formatter("%(message)s"))
458
+ error_logger.addHandler(error_fh)
459
+
460
+ # Progress and error tracking
461
+ processed_count = 0
462
+ error_count = 0
463
+ write_error_count = 0
464
+ failed_ids = []
465
+ shard_idx = 0
466
+ shard_sample_count = 0
467
+ shard_duration = 0.0
468
+ shard_manifest = {} # shard_idx -> (tar_path, jsonl_path, count, duration)
469
+
470
+ tar_writer = None
471
+ jsonl_file = None
472
+
473
+ def open_new_shard():
474
+ nonlocal tar_writer, jsonl_file, shard_idx, shard_sample_count, shard_duration
475
+ if tar_writer is not None:
476
+ tar_writer.close()
477
+ if jsonl_file is not None:
478
+ jsonl_file.close()
479
+ # Record manifest for the previous shard
480
+ if shard_idx > 0 and shard_sample_count > 0:
481
+ prev_idx = shard_idx - 1
482
+ shard_manifest[prev_idx] = (
483
+ os.path.abspath(tar_output_pattern % prev_idx),
484
+ os.path.abspath(jsonl_output_pattern % prev_idx),
485
+ shard_sample_count,
486
+ shard_duration,
487
+ )
488
+ tar_fname = tar_output_pattern % shard_idx
489
+ jsonl_fname = jsonl_output_pattern % shard_idx
490
+ tar_writer = wds.TarWriter(tar_fname)
491
+ jsonl_file = open(jsonl_fname, "w", encoding="utf-8")
492
+ shard_idx += 1
493
+ shard_sample_count = 0
494
+ shard_duration = 0.0
495
+
496
+ def write_sample(key, audio_tokens_np, metadata):
497
+ nonlocal shard_sample_count, write_error_count, shard_duration
498
+ assert tar_writer is not None and jsonl_file is not None
499
+ try:
500
+ token_record = serialise_numpy(key, audio_tokens_np)
501
+ json_record = _encode_metadata(metadata)
502
+ tar_writer.write(token_record)
503
+ jsonl_file.write(json_record.decode("utf-8") + "\n")
504
+ shard_sample_count += 1
505
+ shard_duration += metadata.get("audio_duration", 0.0)
506
+ except Exception as exc:
507
+ write_error_count += 1
508
+ failed_ids.append(key)
509
+ error_logger.error(
510
+ json.dumps({"id": key, "reason": str(exc)}, ensure_ascii=False)
511
+ )
512
+ logging.error(f"Write failed for sample {key}: {exc}")
513
+
514
+ def handle_result(result):
515
+ nonlocal processed_count, error_count
516
+ if result["status"] == "success":
517
+ # Rotate shard if needed
518
+ if tar_writer is None or shard_sample_count >= samples_per_shard:
519
+ open_new_shard()
520
+ write_sample(result["key"], result["audio_tokens"], result["metadata"])
521
+ processed_count += 1
522
+ else:
523
+ error_count += 1
524
+ failed_ids.append(result["key"])
525
+ error_logger.error(
526
+ json.dumps(
527
+ {"id": result["key"], "reason": result["error_msg"]},
528
+ ensure_ascii=False,
529
+ )
530
+ )
531
+ if not args.skip_errors:
532
+ raise RuntimeError(
533
+ f"Sample {result['key']} processing failed due "
534
+ f"to {result['error_msg']} - terminating"
535
+ )
536
+ logging.warning(
537
+ f"Skipping failed sample {result['key']}: {result['error_msg']}"
538
+ )
539
+
540
+ main_progress = tqdm(total=total_samples, desc="Extracting Audio Tokens")
541
+
542
+ try:
543
+ with ProcessPoolExecutor(
544
+ max_workers=num_processes,
545
+ initializer=process_init,
546
+ initargs=(rank_queue, args.tokenizer_path),
547
+ ) as executor:
548
+ logging.info(f"Submitting tasks... ({num_processes} workers)")
549
+ futures = set()
550
+ max_pending = num_processes * 10
551
+
552
+ def drain_completed():
553
+ """Wait for at least one future to complete, process all done."""
554
+ nonlocal futures
555
+ done, _ = wait(futures, return_when=FIRST_COMPLETED)
556
+ for f in done:
557
+ futures.discard(f)
558
+ result = f.result()
559
+ main_progress.update(1)
560
+ handle_result(result)
561
+ main_progress.set_postfix(
562
+ Samples=processed_count,
563
+ Errors=error_count,
564
+ )
565
+
566
+ # Stream samples from DataLoader
567
+ for sample in dataloader:
568
+ if len(futures) >= max_pending:
569
+ drain_completed()
570
+
571
+ future = executor.submit(process_single_sample, sample)
572
+ futures.add(future)
573
+
574
+ # Process remaining futures
575
+ logging.info("Processing remaining pending samples...")
576
+ while futures:
577
+ drain_completed()
578
+
579
+ except Exception:
580
+ logging.error("Critical error during processing", exc_info=True)
581
+ raise
582
+ finally:
583
+ main_progress.close()
584
+ if tar_writer is not None:
585
+ tar_writer.close()
586
+ if jsonl_file is not None:
587
+ jsonl_file.close()
588
+ # Record the last shard in the manifest
589
+ if shard_idx > 0 and shard_sample_count > 0:
590
+ last_idx = shard_idx - 1
591
+ shard_manifest[last_idx] = (
592
+ os.path.abspath(tar_output_pattern % last_idx),
593
+ os.path.abspath(jsonl_output_pattern % last_idx),
594
+ shard_sample_count,
595
+ shard_duration,
596
+ )
597
+
598
+ # Write manifest file (data.lst)
599
+ with open(manifest_path, "w", encoding="utf-8") as mf:
600
+ for idx in sorted(shard_manifest.keys()):
601
+ tar_path, jsonl_path, count, duration = shard_manifest[idx]
602
+ mf.write(f"{tar_path} {jsonl_path} {count} {duration:.3f}\n")
603
+
604
+ # Output final statistics
605
+ total_failed = error_count + write_error_count
606
+ filtered_and_skipped = total_samples - processed_count - total_failed
607
+ logging.info(
608
+ f"Processing Complete - Successful: {processed_count}, Failed: {total_failed}, "
609
+ f"Filtered/Skipped: {filtered_and_skipped}, Shards written: {shard_idx}"
610
+ )
611
+ logging.info(f"Manifest written to: {manifest_path} ({len(shard_manifest)} shards)")
612
+ if total_failed > 0:
613
+ logging.info(f"Error details: {error_log_path}")
614
+ if failed_ids and args.skip_errors:
615
+ logging.warning(
616
+ f"Failed sample IDs (count: {len(failed_ids)}): {failed_ids[:100]}..."
617
+ )
618
+ if write_error_count > 0 and not args.skip_errors:
619
+ raise RuntimeError(
620
+ f"{write_error_count} samples failed to write - check logs for details"
621
+ )
622
+
623
+
624
+ if __name__ == "__main__":
625
+ main()
omnivoice/scripts/extract_audio_tokens_add_noise.py ADDED
@@ -0,0 +1,819 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """
19
+ Extract audio tokens from audio data and pack them into WebDataset shards.
20
+
21
+ Extends ``extract_audio_tokens.py`` with optional noise and reverberation
22
+ augmentation on the prompt (reference) portion of the audio. Requires a
23
+ noise manifest and/or RIR manifest.
24
+
25
+ Supports two input modes:
26
+
27
+ 1. WebDataset manifest (data.lst):
28
+ python extract_audio_tokens_add_noise.py \\
29
+ --input_manifest data.lst \\
30
+ --noise_manifest noise.lst \\
31
+ --tar_output_pattern output/audios/shard-%06d.tar \\
32
+ --jsonl_output_pattern output/txts/shard-%06d.jsonl
33
+
34
+ 2. Raw JSONL (each line: {"id": "...", "audio_path": "...", "text": "...", ...}):
35
+ python extract_audio_tokens_add_noise.py \\
36
+ --input_jsonl data.jsonl \\
37
+ --noise_manifest noise.lst \\
38
+ --tar_output_pattern output/audios/shard-%06d.tar \\
39
+ --jsonl_output_pattern output/txts/shard-%06d.jsonl
40
+
41
+ Output structure:
42
+ output_dir/
43
+ ├── audios/ # WebDataset tar shards (.npy audio tokens + .json metadata)
44
+ │ ├── shard_000000.tar
45
+ │ └── ...
46
+ ├── txts/ # Per-shard JSONL metadata
47
+ │ ├── shard_000000.jsonl
48
+ │ └── ...
49
+ ├── data.lst # Manifest: <tar_path> <jsonl_path> <sample_count> <total_duration>
50
+ └── errors.jsonl # Failed samples with error details
51
+ """
52
+
53
+ import argparse
54
+ import io
55
+ import json
56
+ import logging
57
+ import math
58
+ import multiprocessing as mp
59
+ import os
60
+ import random
61
+ import warnings
62
+ from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait
63
+ from pathlib import Path
64
+ from typing import Any
65
+
66
+ import numpy as np
67
+ import torch
68
+ import torch.nn.functional as F
69
+ import webdataset as wds
70
+ from torch.utils.data import DataLoader, IterableDataset
71
+ from tqdm.auto import tqdm
72
+ from transformers import AutoFeatureExtractor, HiggsAudioV2TokenizerModel
73
+
74
+ from omnivoice.data.dataset import JsonlDatasetReader, WebDatasetReader
75
+ from omnivoice.utils.audio import load_audio_bytes
76
+ from omnivoice.utils.common import str2bool
77
+
78
+ warnings.filterwarnings(
79
+ "ignore", category=FutureWarning, module="torch.nn.utils.weight_norm"
80
+ )
81
+
82
+ HIGGS_INPUT_SAMPLE_RATE = 24_000
83
+
84
+ # Global variables: Store tokenizer and device for each worker process
85
+ worker_tokenizer = None
86
+ worker_feature_extractor = None
87
+ worker_noise_sampler = None
88
+ worker_rir_sampler = None
89
+
90
+
91
+ def build_parser() -> argparse.ArgumentParser:
92
+ parser = argparse.ArgumentParser(description=__doc__)
93
+ parser.add_argument(
94
+ "--input_manifest",
95
+ default=None,
96
+ help="Path to input dataset manifest (data.lst).",
97
+ )
98
+ parser.add_argument(
99
+ "--input_jsonl",
100
+ default=None,
101
+ help="Path to raw JSONL file (alternative to --input_manifest).",
102
+ )
103
+ parser.add_argument(
104
+ "--tar_output_pattern",
105
+ required=True,
106
+ help="Tar shard pattern passed to WebDataset",
107
+ )
108
+ parser.add_argument(
109
+ "--jsonl_output_pattern",
110
+ required=True,
111
+ help="Jsonl shard pattern passed to WebDataset",
112
+ )
113
+ parser.add_argument(
114
+ "--samples_per_shard",
115
+ type=int,
116
+ default=1000,
117
+ help="Maximum records per shard",
118
+ )
119
+ parser.add_argument(
120
+ "--min_num_shards",
121
+ type=int,
122
+ default=32,
123
+ help="Minimum number of output shards (use to ensure "
124
+ "shard count >= num_gpu * num_workers)",
125
+ )
126
+ parser.add_argument(
127
+ "--tokenizer_path",
128
+ type=str,
129
+ default="eustlb/higgs-audio-v2-tokenizer",
130
+ help="Path to audio tokenizer.",
131
+ )
132
+ parser.add_argument(
133
+ "--skip_errors", action="store_true", help="Skip items that fail to process"
134
+ )
135
+ parser.add_argument(
136
+ "--min_length",
137
+ type=float,
138
+ default=0.0,
139
+ help="Minimum audio duration in seconds (e.g. 2.0)",
140
+ )
141
+ parser.add_argument(
142
+ "--max_length",
143
+ type=float,
144
+ default=float("inf"),
145
+ help="Maximum audio duration in seconds (e.g. 15.0)",
146
+ )
147
+ parser.add_argument(
148
+ "--num_machines",
149
+ type=int,
150
+ default=1,
151
+ help="Total number of machines for distributed runs",
152
+ )
153
+ parser.add_argument(
154
+ "--machine_index",
155
+ type=int,
156
+ default=0,
157
+ help="Zero-based machine index when distributing across multiple "
158
+ "machines (e.g. 0, 1, ... num_machines-1)",
159
+ )
160
+ parser.add_argument(
161
+ "--nj_per_gpu",
162
+ type=int,
163
+ default=3,
164
+ help="Number of worker processes to spawn per GPU.",
165
+ )
166
+ parser.add_argument(
167
+ "--loader_workers",
168
+ type=int,
169
+ default=24,
170
+ help="Number of DataLoader workers for streaming IterableDataset.",
171
+ )
172
+ parser.add_argument(
173
+ "--shuffle",
174
+ type=str2bool,
175
+ default=True,
176
+ help="Shuffle data by default.",
177
+ )
178
+ parser.add_argument(
179
+ "--shuffle-seed",
180
+ type=int,
181
+ default=42,
182
+ help="Random seed for shuffle (default: 42).",
183
+ )
184
+ parser.add_argument(
185
+ "--noise_manifest",
186
+ default=None,
187
+ help="Path to noise manifest (list of tar files). Enables prompt noise augmentation.",
188
+ )
189
+ parser.add_argument(
190
+ "--rir_manifest",
191
+ default=None,
192
+ help="Path to RIR manifest (list of tar files). Enables prompt reverb augmentation.",
193
+ )
194
+ return parser
195
+
196
+
197
+ def count_lines(path):
198
+ with open(path, "rb") as f:
199
+ return sum(buf.count(b"\n") for buf in iter(lambda: f.read(1 << 20), b""))
200
+
201
+
202
+ def serialise_numpy(key: str, tokens: np.ndarray) -> dict:
203
+ buffer = io.BytesIO()
204
+ np.save(buffer, tokens)
205
+ return {"__key__": key, "npy": buffer.getvalue()}
206
+
207
+
208
+ def _load_aug_audio(data, sample_rate=24000):
209
+ """Simple audio loader for augmentation files."""
210
+ return torch.from_numpy(load_audio_bytes(data, sample_rate))
211
+
212
+
213
+ class SimpleWorkerSampler:
214
+ """A lightweight infinite sampler for noise/RIR within a worker process."""
215
+
216
+ def __init__(self, tar_paths, sample_rate=24000):
217
+ self.dataset = (
218
+ wds.WebDataset(
219
+ tar_paths, shardshuffle=True, nodesplitter=None, workersplitter=None
220
+ )
221
+ .decode()
222
+ .map(lambda s: self._decode(s, sample_rate))
223
+ .select(lambda x: x is not None)
224
+ .shuffle(100)
225
+ .repeat()
226
+ )
227
+ self.iterator = iter(self.dataset)
228
+
229
+ def _decode(self, sample, sample_rate):
230
+ for ext in ["wav", "flac", "mp3"]:
231
+ if ext in sample:
232
+ return _load_aug_audio(sample[ext], sample_rate)
233
+ return None
234
+
235
+ def sample_segment(self, target_len, allow_repeat=True):
236
+ """Get a random segment of noise matching the target length."""
237
+ try:
238
+ audio = next(self.iterator)
239
+ except StopIteration:
240
+ self.iterator = iter(self.dataset)
241
+ audio = next(self.iterator)
242
+
243
+ cur_len = audio.size(-1)
244
+ if cur_len < target_len and allow_repeat:
245
+ if cur_len > 0:
246
+ num_repeats = math.ceil(target_len / cur_len)
247
+ audio = audio.repeat(1, num_repeats)
248
+ else:
249
+ audio = F.pad(audio, (0, target_len), mode="constant")
250
+ cur_len = audio.size(-1)
251
+
252
+ if cur_len > target_len:
253
+ start = random.randint(0, cur_len - target_len)
254
+ audio = audio[..., start : start + target_len]
255
+
256
+ return audio
257
+
258
+
259
+ def _convolve1d(signal: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:
260
+ m = signal.size(-1)
261
+ n = kernel.size(-1)
262
+ padded_size = m + n - 1
263
+ f_signal = torch.fft.rfft(signal, n=padded_size)
264
+ f_kernel = torch.fft.rfft(kernel, n=padded_size)
265
+ f_result = f_signal * f_kernel
266
+ result = torch.fft.irfft(f_result, n=padded_size)
267
+ return result[:padded_size]
268
+
269
+
270
+ def _apply_rir(audio, rir, mix_ratio=0.5):
271
+ rir_scaling_factor = 0.5**15
272
+ N_in = audio.shape[-1]
273
+ rir_d = rir[0, :] * rir_scaling_factor
274
+ aug_d = _convolve1d(audio[0], rir_d)
275
+ shift_index = torch.argmax(torch.abs(rir_d))
276
+ end_index = shift_index + N_in
277
+ if end_index > aug_d.shape[0]:
278
+ augmented = F.pad(aug_d[shift_index:], (0, end_index - aug_d.shape[0]))
279
+ else:
280
+ augmented = aug_d[shift_index:end_index]
281
+ power_before = torch.sum(audio[0] ** 2)
282
+ power_after = torch.sum(augmented**2)
283
+ if power_after > 0:
284
+ augmented *= torch.sqrt(power_before / power_after)
285
+ mixed = (1 - mix_ratio) * audio[0] + mix_ratio * augmented
286
+ return mixed.unsqueeze(0)
287
+
288
+
289
+ def process_init(rank_queue, tokenizer_path, noise_manifest=None, rir_manifest=None):
290
+ """
291
+ Initialization function for each worker process.
292
+ Assigns a specific GPU to the process and loads the tokenizer.
293
+ """
294
+ global worker_tokenizer, worker_feature_extractor, worker_noise_sampler, worker_rir_sampler
295
+
296
+ # Configure worker process logging
297
+ formatter = (
298
+ "%(asctime)s %(levelname)s [%(filename)s:%(lineno)d]"
299
+ " [Worker %(process)d] %(message)s"
300
+ )
301
+ logging.basicConfig(format=formatter, level=logging.INFO, force=True)
302
+
303
+ # Get assigned GPU rank
304
+ rank = rank_queue.get()
305
+ # Determine device
306
+ if rank != -1 and torch.cuda.is_available():
307
+ worker_device = torch.device(f"cuda:{rank}")
308
+ else:
309
+ worker_device = torch.device("cpu")
310
+
311
+ logging.debug(f"Worker process initialized with device: {worker_device}")
312
+ # Load tokenizer onto the specified device
313
+ worker_feature_extractor = AutoFeatureExtractor.from_pretrained(tokenizer_path)
314
+ worker_tokenizer = HiggsAudioV2TokenizerModel.from_pretrained(
315
+ tokenizer_path, device_map=worker_device
316
+ )
317
+ logging.debug(f"Tokenizer loaded successfully on device {worker_device}")
318
+
319
+ # Initialize augmentation samplers (optional)
320
+ if noise_manifest:
321
+ try:
322
+ with open(noise_manifest, "r") as f:
323
+ tars = [l.strip().split()[0] for l in f if l.strip()]
324
+ worker_noise_sampler = SimpleWorkerSampler(
325
+ tars, sample_rate=HIGGS_INPUT_SAMPLE_RATE
326
+ )
327
+ logging.debug("Noise sampler initialized.")
328
+ except Exception as e:
329
+ logging.warning(f"Failed to load noise manifest: {e}")
330
+
331
+ if rir_manifest:
332
+ try:
333
+ with open(rir_manifest, "r") as f:
334
+ tars = [l.strip().split()[0] for l in f if l.strip()]
335
+ worker_rir_sampler = SimpleWorkerSampler(
336
+ tars, sample_rate=HIGGS_INPUT_SAMPLE_RATE
337
+ )
338
+ logging.debug("RIR sampler initialized.")
339
+ except Exception as e:
340
+ logging.warning(f"Failed to load RIR manifest: {e}")
341
+
342
+
343
+ def _augment_prompt(audio_tensor: torch.Tensor) -> tuple[torch.Tensor, int]:
344
+ """Apply noise/reverb augmentation to the front portion of audio.
345
+
346
+ Returns the augmented audio and the sample index where clean audio starts.
347
+ """
348
+ # Pre-normalization
349
+ max_val = audio_tensor.abs().max() + 1e-7
350
+ audio_tensor = (audio_tensor / max_val) * 0.6
351
+
352
+ total_len = audio_tensor.size(-1)
353
+ ratio = random.uniform(0.1, 0.3)
354
+ split_idx = int(total_len * ratio)
355
+ front_part = audio_tensor[:, :split_idx].clone()
356
+
357
+ # Apply noise
358
+ if worker_noise_sampler is not None:
359
+ noise = worker_noise_sampler.sample_segment(split_idx)
360
+ snr_db = random.uniform(5, 15)
361
+ sig_rms = front_part.norm(p=2) / (split_idx**0.5)
362
+ noise_rms = noise.norm(p=2) / (split_idx**0.5)
363
+ if noise_rms > 1e-9:
364
+ snr = 10 ** (snr_db / 20)
365
+ scale = sig_rms / (snr * noise_rms + 1e-8)
366
+ front_part = front_part + noise * scale
367
+
368
+ # Apply RIR (30% probability)
369
+ if worker_rir_sampler is not None and random.random() < 0.3:
370
+ rir = worker_rir_sampler.sample_segment(split_idx, allow_repeat=False)
371
+ reverb_amt = random.uniform(0.3, 1.0)
372
+ try:
373
+ front_part = _apply_rir(front_part, rir, reverb_amt)
374
+ except Exception as e:
375
+ logging.warning(f"RIR failed: {e}")
376
+
377
+ # Merge back
378
+ if front_part.device != audio_tensor.device:
379
+ front_part = front_part.to(audio_tensor.device)
380
+ audio_tensor[:, :split_idx] = front_part
381
+
382
+ # Post-normalization
383
+ max_val = audio_tensor.abs().max() + 1e-7
384
+ audio_tensor = (audio_tensor / max_val) * 0.9
385
+
386
+ return audio_tensor, split_idx
387
+
388
+
389
+ def process_single_sample(sample: dict[str, Any]) -> dict[str, Any]:
390
+ """
391
+ Single-sample processing function executed in worker processes.
392
+ Skips invalid samples during streaming processing.
393
+ """
394
+ try:
395
+ audio_tensor = sample.get("audio", None) # shape (1, T)
396
+ if audio_tensor is None:
397
+ raise ValueError("Sample missing 'audio' field")
398
+
399
+ # Apply prompt augmentation if noise/rir samplers are available
400
+ enable_aug = worker_noise_sampler is not None or worker_rir_sampler is not None
401
+ clean_sample_idx = 0
402
+ if enable_aug:
403
+ audio_tensor, clean_sample_idx = _augment_prompt(audio_tensor)
404
+
405
+ with torch.inference_mode():
406
+ key = sample["label"]["id"]
407
+
408
+ inputs = worker_feature_extractor(
409
+ raw_audio=audio_tensor.squeeze(0).numpy(),
410
+ sampling_rate=HIGGS_INPUT_SAMPLE_RATE,
411
+ return_tensors="pt",
412
+ ).to(worker_tokenizer.device)
413
+ audio_tokens = worker_tokenizer.encode(
414
+ inputs["input_values"],
415
+ ).audio_codes.squeeze(0)
416
+
417
+ assert len(audio_tokens.shape) == 2
418
+ assert audio_tokens.size(0) == 8
419
+
420
+ num_tokens = audio_tokens.size(1)
421
+ metadata = sample["label"]
422
+ metadata["num_tokens"] = num_tokens
423
+
424
+ if enable_aug:
425
+ clean_token_idx = math.ceil(
426
+ clean_sample_idx / worker_tokenizer.config.hop_length
427
+ )
428
+ metadata["clean_start_token_idx"] = clean_token_idx
429
+
430
+ # Convert to numpy format for subsequent serialization (int16 to save space)
431
+ audio_tokens_np = audio_tokens.to(torch.int16).cpu().numpy()
432
+
433
+ return {
434
+ "status": "success",
435
+ "key": key,
436
+ "audio_tokens": audio_tokens_np,
437
+ "metadata": metadata,
438
+ "error_msg": None,
439
+ }
440
+ except Exception as e:
441
+ sample_id = sample.get("label", {}).get("id", "unknown")
442
+ logging.error(f"Failed to process sample {sample_id}: {e}")
443
+ return {
444
+ "status": "error",
445
+ "key": sample_id,
446
+ "audio_tokens": None,
447
+ "metadata": None,
448
+ "error_msg": str(e),
449
+ }
450
+
451
+
452
+ def _normalise_value(value: Any) -> Any:
453
+ """Convert tensors and NumPy scalars to serialisable Python objects."""
454
+ if isinstance(value, torch.Tensor):
455
+ if value.ndim == 0:
456
+ return value.item()
457
+ return value.cpu().tolist()
458
+ if isinstance(value, np.generic):
459
+ return value.item()
460
+ if isinstance(value, np.ndarray):
461
+ return value.tolist()
462
+ return value
463
+
464
+
465
+ def _encode_metadata(metadata: dict[str, Any]) -> bytes:
466
+ cleaned: dict[str, Any] = {}
467
+ for key, value in metadata.items():
468
+ if value is None:
469
+ continue
470
+ cleaned[key] = _normalise_value(value)
471
+ return json.dumps(cleaned, ensure_ascii=False).encode("utf-8")
472
+
473
+
474
+ class StreamingLengthFilteredDataset(IterableDataset):
475
+ def __init__(
476
+ self,
477
+ base_iterable,
478
+ min_len: float,
479
+ max_len: float,
480
+ sr: int,
481
+ ):
482
+ self.base_iterable = base_iterable
483
+ self.min_len = min_len
484
+ self.max_len = max_len
485
+ self.sr = sr
486
+ self.filtered_count = 0
487
+
488
+ def __iter__(self):
489
+ """Stream samples one by one and filter on the fly."""
490
+ for sample in self.base_iterable:
491
+ try:
492
+ duration = sample["audio"].size(-1) / self.sr
493
+ if self.min_len <= duration <= self.max_len:
494
+ yield sample
495
+ else:
496
+ self.filtered_count += 1
497
+ logging.warning(
498
+ f"Filtered sample (duration out of range): "
499
+ f"{sample['label']['id']} ({duration:.2f}s)"
500
+ )
501
+ except Exception as e:
502
+ logging.warning(f"Skipped invalid sample during streaming: {e}")
503
+ continue
504
+
505
+
506
+ def main() -> None:
507
+ formatter = "%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s"
508
+ logging.basicConfig(format=formatter, level=logging.INFO, force=True)
509
+ parser = build_parser()
510
+ args = parser.parse_args()
511
+ mp.set_start_method("spawn", force=True)
512
+
513
+ # Validate input arguments
514
+ assert bool(args.input_manifest) != bool(
515
+ args.input_jsonl
516
+ ), "Exactly one of --input_manifest or --input_jsonl must be provided."
517
+
518
+ if args.num_machines > 1:
519
+ assert (
520
+ 0 <= args.machine_index < args.num_machines
521
+ ), f"machine_index {args.machine_index} must be in [0, {args.num_machines})"
522
+
523
+ # Build base dataset and count total samples based on input mode
524
+ if args.input_jsonl:
525
+ logging.info(f"Input mode: raw JSONL ({args.input_jsonl})")
526
+ total_samples = count_lines(args.input_jsonl)
527
+ base_dataset = JsonlDatasetReader(
528
+ args.input_jsonl,
529
+ sample_rate=HIGGS_INPUT_SAMPLE_RATE,
530
+ shuffle=args.shuffle,
531
+ shuffle_seed=args.shuffle_seed,
532
+ )
533
+ loader_workers = args.loader_workers
534
+ else:
535
+ logging.info(f"Input mode: WebDataset manifest ({args.input_manifest})")
536
+ manifest_num_lines = count_lines(args.input_manifest)
537
+ loader_workers = min(args.loader_workers, manifest_num_lines)
538
+ total_samples = 0
539
+ manifests = []
540
+ with open(args.input_manifest, "r", encoding="utf-8") as f:
541
+ for line_id, line in tqdm(
542
+ enumerate(f),
543
+ total=manifest_num_lines,
544
+ desc="Calculating dataset length",
545
+ ):
546
+ items = line.strip().split(" ")
547
+ tar_path, jsonl_path, num_items, duration = (
548
+ items[0],
549
+ items[1],
550
+ int(items[2]),
551
+ float(items[3]),
552
+ )
553
+ assert os.path.exists(tar_path), f"File {tar_path} does not exist."
554
+ assert os.path.exists(jsonl_path), f"File {jsonl_path} does not exist."
555
+ assert jsonl_path.endswith(
556
+ ".jsonl"
557
+ ), f"File {jsonl_path} is not a .jsonl file."
558
+ if (
559
+ args.num_machines > 1
560
+ and line_id % args.num_machines != args.machine_index
561
+ ):
562
+ continue
563
+ total_samples += num_items
564
+ manifests.append((tar_path, jsonl_path, num_items, duration))
565
+ logging.info(
566
+ f"Total shards: {manifest_num_lines}, "
567
+ f"Shards for current index: {len(manifests)}"
568
+ )
569
+ base_dataset = WebDatasetReader(
570
+ manifests=manifests,
571
+ sample_rate=HIGGS_INPUT_SAMPLE_RATE,
572
+ evaluation=True,
573
+ )
574
+
575
+ # Apply length filter and create DataLoader
576
+ filtered_dataset = StreamingLengthFilteredDataset(
577
+ base_iterable=base_dataset,
578
+ min_len=args.min_length,
579
+ max_len=args.max_length,
580
+ sr=HIGGS_INPUT_SAMPLE_RATE,
581
+ )
582
+ dataloader = DataLoader(
583
+ dataset=filtered_dataset,
584
+ batch_size=None,
585
+ num_workers=loader_workers,
586
+ persistent_workers=loader_workers > 0,
587
+ pin_memory=False,
588
+ )
589
+
590
+ # Adjust samples_per_shard if min_num_shards would be violated
591
+ samples_per_shard = args.samples_per_shard
592
+ if total_samples > 0:
593
+ estimated_shards = max(
594
+ 1, (total_samples + samples_per_shard - 1) // samples_per_shard
595
+ )
596
+ if estimated_shards < args.min_num_shards:
597
+ samples_per_shard = max(1, total_samples // args.min_num_shards)
598
+ logging.info(
599
+ f"Adjusted samples_per_shard from {args.samples_per_shard} to "
600
+ f"{samples_per_shard} to meet min_num_shards={args.min_num_shards} "
601
+ f"(total_samples={total_samples})"
602
+ )
603
+
604
+ # Configure multi-GPU multi-process setup
605
+ num_devices = torch.cuda.device_count()
606
+ if num_devices == 0:
607
+ logging.warning("No GPUs detected - using CPU for processing")
608
+ num_processes = args.nj_per_gpu
609
+ else:
610
+ num_processes = num_devices * args.nj_per_gpu
611
+ logging.info(
612
+ f"GPU count: {num_devices}, Processes per GPU: {args.nj_per_gpu}, "
613
+ f"Total processes: {num_processes}"
614
+ )
615
+ if args.noise_manifest or args.rir_manifest:
616
+ logging.info(
617
+ f"Prompt augmentation enabled - "
618
+ f"noise: {args.noise_manifest or 'off'}, rir: {args.rir_manifest or 'off'}"
619
+ )
620
+
621
+ # Shared GPU rank queue for process assignment
622
+ manager = mp.Manager()
623
+ rank_queue = manager.Queue()
624
+ for rank in list(range(num_devices)) * args.nj_per_gpu:
625
+ rank_queue.put(rank)
626
+ if num_devices == 0:
627
+ for _ in range(num_processes):
628
+ rank_queue.put(-1)
629
+
630
+ # Prepare output paths
631
+ tar_output_pattern = str(Path(args.tar_output_pattern).expanduser())
632
+ jsonl_output_pattern = str(Path(args.jsonl_output_pattern).expanduser())
633
+ Path(tar_output_pattern).parent.mkdir(parents=True, exist_ok=True)
634
+ Path(jsonl_output_pattern).parent.mkdir(parents=True, exist_ok=True)
635
+
636
+ # Determine output directory from tar_output_pattern
637
+ output_dir = Path(tar_output_pattern).parent.parent
638
+ error_log_path = str(output_dir / "errors.jsonl")
639
+ manifest_path = str(output_dir / "data.lst")
640
+
641
+ # Setup error logger (writes to errors.jsonl)
642
+ error_logger = logging.getLogger("error_log")
643
+ error_logger.setLevel(logging.ERROR)
644
+ error_logger.handlers.clear()
645
+ error_fh = logging.FileHandler(error_log_path, mode="w", encoding="utf-8")
646
+ error_fh.setFormatter(logging.Formatter("%(message)s"))
647
+ error_logger.addHandler(error_fh)
648
+
649
+ # Progress and error tracking
650
+ processed_count = 0
651
+ error_count = 0
652
+ write_error_count = 0
653
+ failed_ids = []
654
+ shard_idx = 0
655
+ shard_sample_count = 0
656
+ shard_duration = 0.0
657
+ shard_manifest = {} # shard_idx -> (tar_path, jsonl_path, count, duration)
658
+
659
+ tar_writer = None
660
+ jsonl_file = None
661
+
662
+ def open_new_shard():
663
+ nonlocal tar_writer, jsonl_file, shard_idx, shard_sample_count, shard_duration
664
+ if tar_writer is not None:
665
+ tar_writer.close()
666
+ if jsonl_file is not None:
667
+ jsonl_file.close()
668
+ # Record manifest for the previous shard
669
+ if shard_idx > 0 and shard_sample_count > 0:
670
+ prev_idx = shard_idx - 1
671
+ shard_manifest[prev_idx] = (
672
+ os.path.abspath(tar_output_pattern % prev_idx),
673
+ os.path.abspath(jsonl_output_pattern % prev_idx),
674
+ shard_sample_count,
675
+ shard_duration,
676
+ )
677
+ tar_fname = tar_output_pattern % shard_idx
678
+ jsonl_fname = jsonl_output_pattern % shard_idx
679
+ tar_writer = wds.TarWriter(tar_fname)
680
+ jsonl_file = open(jsonl_fname, "w", encoding="utf-8")
681
+ shard_idx += 1
682
+ shard_sample_count = 0
683
+ shard_duration = 0.0
684
+
685
+ def write_sample(key, audio_tokens_np, metadata):
686
+ nonlocal shard_sample_count, write_error_count, shard_duration
687
+ assert tar_writer is not None and jsonl_file is not None
688
+ try:
689
+ token_record = serialise_numpy(key, audio_tokens_np)
690
+ json_record = _encode_metadata(metadata)
691
+ tar_writer.write(token_record)
692
+ jsonl_file.write(json_record.decode("utf-8") + "\n")
693
+ shard_sample_count += 1
694
+ shard_duration += metadata.get("audio_duration", 0.0)
695
+ except Exception as exc:
696
+ write_error_count += 1
697
+ failed_ids.append(key)
698
+ error_logger.error(
699
+ json.dumps({"id": key, "reason": str(exc)}, ensure_ascii=False)
700
+ )
701
+ logging.error(f"Write failed for sample {key}: {exc}")
702
+
703
+ def handle_result(result):
704
+ nonlocal processed_count, error_count
705
+ if result["status"] == "success":
706
+ # Rotate shard if needed
707
+ if tar_writer is None or shard_sample_count >= samples_per_shard:
708
+ open_new_shard()
709
+ write_sample(result["key"], result["audio_tokens"], result["metadata"])
710
+ processed_count += 1
711
+ else:
712
+ error_count += 1
713
+ failed_ids.append(result["key"])
714
+ error_logger.error(
715
+ json.dumps(
716
+ {"id": result["key"], "reason": result["error_msg"]},
717
+ ensure_ascii=False,
718
+ )
719
+ )
720
+ if not args.skip_errors:
721
+ raise RuntimeError(
722
+ f"Sample {result['key']} processing failed due "
723
+ f"to {result['error_msg']} - terminating"
724
+ )
725
+ logging.warning(
726
+ f"Skipping failed sample {result['key']}: {result['error_msg']}"
727
+ )
728
+
729
+ main_progress = tqdm(total=total_samples, desc="Extracting Audio Tokens")
730
+
731
+ try:
732
+ with ProcessPoolExecutor(
733
+ max_workers=num_processes,
734
+ initializer=process_init,
735
+ initargs=(
736
+ rank_queue,
737
+ args.tokenizer_path,
738
+ args.noise_manifest,
739
+ args.rir_manifest,
740
+ ),
741
+ ) as executor:
742
+ logging.info(f"Submitting tasks... ({num_processes} workers)")
743
+ futures = set()
744
+ max_pending = num_processes * 10
745
+
746
+ def drain_completed():
747
+ """Wait for at least one future to complete, process all done."""
748
+ nonlocal futures
749
+ done, _ = wait(futures, return_when=FIRST_COMPLETED)
750
+ for f in done:
751
+ futures.discard(f)
752
+ result = f.result()
753
+ main_progress.update(1)
754
+ handle_result(result)
755
+ main_progress.set_postfix(
756
+ Samples=processed_count,
757
+ Errors=error_count,
758
+ )
759
+
760
+ # Stream samples from DataLoader
761
+ for sample in dataloader:
762
+ if len(futures) >= max_pending:
763
+ drain_completed()
764
+
765
+ future = executor.submit(process_single_sample, sample)
766
+ futures.add(future)
767
+
768
+ # Process remaining futures
769
+ logging.info("Processing remaining pending samples...")
770
+ while futures:
771
+ drain_completed()
772
+
773
+ except Exception:
774
+ logging.error("Critical error during processing", exc_info=True)
775
+ raise
776
+ finally:
777
+ main_progress.close()
778
+ if tar_writer is not None:
779
+ tar_writer.close()
780
+ if jsonl_file is not None:
781
+ jsonl_file.close()
782
+ # Record the last shard in the manifest
783
+ if shard_idx > 0 and shard_sample_count > 0:
784
+ last_idx = shard_idx - 1
785
+ shard_manifest[last_idx] = (
786
+ os.path.abspath(tar_output_pattern % last_idx),
787
+ os.path.abspath(jsonl_output_pattern % last_idx),
788
+ shard_sample_count,
789
+ shard_duration,
790
+ )
791
+
792
+ # Write manifest file (data.lst)
793
+ with open(manifest_path, "w", encoding="utf-8") as mf:
794
+ for idx in sorted(shard_manifest.keys()):
795
+ tar_path, jsonl_path, count, duration = shard_manifest[idx]
796
+ mf.write(f"{tar_path} {jsonl_path} {count} {duration:.3f}\n")
797
+
798
+ # Output final statistics
799
+ total_failed = error_count + write_error_count
800
+ filtered_and_skipped = total_samples - processed_count - total_failed
801
+ logging.info(
802
+ f"Processing Complete - Successful: {processed_count}, Failed: {total_failed}, "
803
+ f"Filtered/Skipped: {filtered_and_skipped}, Shards written: {shard_idx}"
804
+ )
805
+ logging.info(f"Manifest written to: {manifest_path} ({len(shard_manifest)} shards)")
806
+ if total_failed > 0:
807
+ logging.info(f"Error details: {error_log_path}")
808
+ if failed_ids and args.skip_errors:
809
+ logging.warning(
810
+ f"Failed sample IDs (count: {len(failed_ids)}): {failed_ids[:100]}..."
811
+ )
812
+ if write_error_count > 0 and not args.skip_errors:
813
+ raise RuntimeError(
814
+ f"{write_error_count} samples failed to write - check logs for details"
815
+ )
816
+
817
+
818
+ if __name__ == "__main__":
819
+ main()
omnivoice/scripts/jsonl_to_webdataset.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """
19
+ Pack a JSONL audio dataset into a customed WebDataset shards
20
+ (paired .tar and .jsonl files).
21
+
22
+ Usage:
23
+ python jsonl_to_webdataset.py \
24
+ --input data.jsonl \
25
+ --output output_dir/ \
26
+ --workers 16 \
27
+ --threads 4 \
28
+ --shard-size 1000 \
29
+ --sr 24000
30
+
31
+ Input JSONL format (one JSON object per line):
32
+ {"id": "utt_001", "audio_path": "/data/wavs/001.wav", "text": "hello world", ...}
33
+
34
+ Required fields: "id", "audio_path", "text"
35
+ All other fields are preserved in the output metadata.
36
+
37
+ Output structure:
38
+ output_dir/
39
+ ├── audios/ # WebDataset tar shards
40
+ │ ├── shard_000000.tar
41
+ │ ├── shard_000001.tar
42
+ │ └── ...
43
+ ├── txts/ # Per-shard JSONL metadata (with audio_duration added)
44
+ │ ├── shard_000000.jsonl
45
+ │ ├── shard_000001.jsonl
46
+ │ └── ...
47
+ ├── data.lst # Manifest: <tar_path> <jsonl_path> <sample_count> <total_duration>
48
+ └── errors.jsonl # Failed samples with error details
49
+ """
50
+
51
+ import argparse
52
+ import io
53
+ import json
54
+ import logging
55
+ import multiprocessing as mp
56
+ import os
57
+ import random
58
+ from concurrent.futures import (
59
+ FIRST_COMPLETED,
60
+ ProcessPoolExecutor,
61
+ ThreadPoolExecutor,
62
+ as_completed,
63
+ wait,
64
+ )
65
+ from itertools import islice
66
+ from pathlib import Path
67
+
68
+ import torch
69
+ import torchaudio
70
+ import webdataset as wds
71
+ from tqdm import tqdm
72
+
73
+ import soundfile as sf
74
+
75
+ from omnivoice.utils.audio import load_waveform
76
+ from omnivoice.utils.common import str2bool
77
+
78
+
79
+ def build_parser() -> argparse.ArgumentParser:
80
+ parser = argparse.ArgumentParser(
81
+ description="Pack JSONL audio dataset into WebDataset shards."
82
+ )
83
+ parser.add_argument(
84
+ "--input", type=str, default="data.jsonl", help="Path to input JSONL file"
85
+ )
86
+ parser.add_argument(
87
+ "--output",
88
+ type=str,
89
+ default="emilia",
90
+ help="Path to output directory",
91
+ )
92
+ parser.add_argument(
93
+ "--workers",
94
+ type=int,
95
+ default=16,
96
+ help="Number of worker processes (default: 16)",
97
+ )
98
+ parser.add_argument(
99
+ "--threads",
100
+ type=int,
101
+ default=4,
102
+ help="Number of threads per worker process.",
103
+ )
104
+ parser.add_argument(
105
+ "--shard-size",
106
+ type=int,
107
+ default=1000,
108
+ help="Number of samples per shard (default: 1000)",
109
+ )
110
+ parser.add_argument(
111
+ "--sr", type=int, default=24000, help="Target sample rate (default: 24000)"
112
+ )
113
+ parser.add_argument(
114
+ "--shuffle",
115
+ type=str2bool,
116
+ default=True,
117
+ help="Shuffle data by default.",
118
+ )
119
+ parser.add_argument(
120
+ "--shuffle-seed",
121
+ type=int,
122
+ default=42,
123
+ help="Random seed for shuffle (default: 42)",
124
+ )
125
+ parser.add_argument(
126
+ "--min-duration",
127
+ type=float,
128
+ default=None,
129
+ help="Filter out samples shorter than this (seconds).",
130
+ )
131
+ parser.add_argument(
132
+ "--max-duration",
133
+ type=float,
134
+ default=None,
135
+ help="Filter out samples >= this duration (seconds).",
136
+ )
137
+ return parser
138
+
139
+
140
+ def read_jsonl(file_path):
141
+ with open(file_path, "r", encoding="utf-8") as f:
142
+ for line in f:
143
+ line = line.strip()
144
+ if line:
145
+ yield json.loads(line)
146
+
147
+
148
+ def chunked_reader(iterator, chunk_size):
149
+ it = iter(iterator)
150
+ while chunk := list(islice(it, chunk_size)):
151
+ yield chunk
152
+
153
+
154
+ def process_audio_item(meta, target_sr):
155
+ key = meta.get("id")
156
+ audio_path = meta.get("audio_path")
157
+
158
+ if not key or not audio_path:
159
+ return {
160
+ "error": {
161
+ "id": key,
162
+ "audio_path": audio_path,
163
+ "reason": "missing id or audio_path",
164
+ }
165
+ }
166
+
167
+ try:
168
+ if not os.path.exists(audio_path):
169
+ raise FileNotFoundError(f"{audio_path} not found")
170
+
171
+ waveform, sr = load_waveform(audio_path)
172
+ audio_duration = waveform.shape[1] / sr
173
+ meta["audio_duration"] = audio_duration
174
+
175
+ if target_sr and sr != target_sr:
176
+ waveform = torchaudio.functional.resample(
177
+ torch.from_numpy(waveform), orig_freq=sr, new_freq=target_sr
178
+ ).numpy()
179
+ sr = target_sr
180
+
181
+ audio_buffer = io.BytesIO()
182
+ sf.write(audio_buffer, waveform.T, sr, format="FLAC")
183
+ audio_bytes = audio_buffer.getvalue()
184
+
185
+ sample = {
186
+ "__key__": key,
187
+ "flac": audio_bytes,
188
+ }
189
+
190
+ return {"ok": (sample, meta)}
191
+
192
+ except Exception as e:
193
+ return {"error": {"id": key, "audio_path": audio_path, "reason": str(e)}}
194
+
195
+
196
+ def process_single_shard(
197
+ shard_idx,
198
+ records,
199
+ output_tar_pattern,
200
+ output_jsonl_pattern,
201
+ target_sr,
202
+ num_threads=4,
203
+ min_duration=None,
204
+ max_duration=None,
205
+ ):
206
+ tar_fname = output_tar_pattern % shard_idx
207
+ jsonl_fname = output_jsonl_pattern % shard_idx
208
+
209
+ processed_count = 0
210
+ filtered_count = 0
211
+ error_count = 0
212
+ total_duration = 0.0
213
+ errors = []
214
+
215
+ with wds.TarWriter(tar_fname) as sink, open(
216
+ jsonl_fname, "w", encoding="utf-8"
217
+ ) as jsonl_f:
218
+
219
+ with ThreadPoolExecutor(max_workers=num_threads) as thread_pool:
220
+ futures = []
221
+
222
+ for meta in records:
223
+ f = thread_pool.submit(process_audio_item, meta, target_sr)
224
+ futures.append(f)
225
+
226
+ for f in as_completed(futures):
227
+ result = f.result()
228
+
229
+ if "error" in result:
230
+ error_count += 1
231
+ errors.append(result["error"])
232
+ continue
233
+
234
+ sample, meta = result["ok"]
235
+ dur = meta.get("audio_duration", 0.0)
236
+
237
+ # Duration filtering (based on actual audio_duration computed above)
238
+ if min_duration is not None and dur < min_duration:
239
+ filtered_count += 1
240
+ continue
241
+ if max_duration is not None and dur >= max_duration:
242
+ filtered_count += 1
243
+ continue
244
+
245
+ sink.write(sample)
246
+
247
+ jsonl_f.write(json.dumps(meta, ensure_ascii=False) + "\n")
248
+
249
+ total_duration += dur
250
+ processed_count += 1
251
+
252
+ # Clean up empty shard files
253
+ if processed_count == 0:
254
+ for p in (tar_fname, jsonl_fname):
255
+ if os.path.exists(p):
256
+ os.remove(p)
257
+
258
+ return (
259
+ shard_idx,
260
+ processed_count,
261
+ error_count,
262
+ filtered_count,
263
+ total_duration,
264
+ errors,
265
+ )
266
+
267
+
268
+ def count_lines(path):
269
+ with open(path, "rb") as f:
270
+ return sum(buf.count(b"\n") for buf in iter(lambda: f.read(1 << 20), b""))
271
+
272
+
273
+ def pack_dataset(
274
+ input_jsonl,
275
+ output_dir,
276
+ samples_per_shard=5000,
277
+ num_workers=16,
278
+ target_sr=24000,
279
+ threads_per_worker=4,
280
+ shuffle=False,
281
+ shuffle_seed=None,
282
+ min_duration=None,
283
+ max_duration=None,
284
+ ):
285
+ input_path = Path(input_jsonl)
286
+ output_dir = Path(output_dir)
287
+ output_tar_dir = output_dir / "audios"
288
+ output_tar_dir.mkdir(parents=True, exist_ok=True)
289
+ output_jsonl_dir = output_dir / "txts"
290
+ output_jsonl_dir.mkdir(parents=True, exist_ok=True)
291
+
292
+ output_tar_pattern = str(output_tar_dir / "shard-%06d.tar")
293
+ output_jsonl_pattern = str(output_jsonl_dir / "shard-%06d.jsonl")
294
+
295
+ error_log_path = str(output_dir / "errors.jsonl")
296
+
297
+ # Setup error logger
298
+ error_logger = logging.getLogger("error_log")
299
+ error_logger.setLevel(logging.ERROR)
300
+ error_logger.handlers.clear()
301
+ fh = logging.FileHandler(error_log_path, mode="w", encoding="utf-8")
302
+ fh.setFormatter(logging.Formatter("%(message)s"))
303
+ error_logger.addHandler(fh)
304
+
305
+ shard_manifest = {}
306
+
307
+ print(f"Reading input: {input_path}")
308
+ print(f"Output dir: {output_dir}")
309
+ print(f"Strategy: {num_workers} Processes x {threads_per_worker} Threads")
310
+
311
+ if shuffle:
312
+ print("Load input dataset...")
313
+ entries = list(read_jsonl(input_path))
314
+ random.seed(shuffle_seed)
315
+ random.shuffle(entries)
316
+ print(f"Shuffled {len(entries)} entries (seed={shuffle_seed})")
317
+ total_lines = len(entries)
318
+ chunk_gen = chunked_reader(iter(entries), samples_per_shard)
319
+ else:
320
+ print("Calculating total lines...")
321
+ total_lines = count_lines(input_path)
322
+ chunk_gen = chunked_reader(read_jsonl(input_path), samples_per_shard)
323
+
324
+ if min_duration is not None or max_duration is not None:
325
+ print(
326
+ f"Duration filter: [{min_duration or 0:.2f}s"
327
+ f", {max_duration or float('inf'):.1f}s) (applied after audio decoding)"
328
+ )
329
+
330
+ total_shards_est = (total_lines + samples_per_shard - 1) // samples_per_shard
331
+ print(f"Total samples: {total_lines}, Estimated shards: {total_shards_est}")
332
+
333
+ with ProcessPoolExecutor(max_workers=num_workers) as executor:
334
+
335
+ futures = set()
336
+
337
+ shard_idx = 0
338
+ total_processed = 0
339
+ total_errors = 0
340
+ total_filtered = 0
341
+
342
+ pbar = tqdm(
343
+ total=total_shards_est,
344
+ desc="Shards Processed",
345
+ unit="shard",
346
+ )
347
+
348
+ def submit_next_chunks(limit):
349
+ """Pull up to `limit` chunks from generator, submit them."""
350
+ nonlocal shard_idx
351
+ submitted = 0
352
+ for chunk in chunk_gen:
353
+ f = executor.submit(
354
+ process_single_shard,
355
+ shard_idx,
356
+ chunk,
357
+ output_tar_pattern,
358
+ output_jsonl_pattern,
359
+ target_sr,
360
+ threads_per_worker,
361
+ min_duration,
362
+ max_duration,
363
+ )
364
+ futures.add(f)
365
+ shard_idx += 1
366
+ submitted += 1
367
+ if submitted >= limit:
368
+ break
369
+
370
+ submit_next_chunks(num_workers * 2)
371
+
372
+ while futures:
373
+ done, _ = wait(futures, return_when=FIRST_COMPLETED)
374
+
375
+ for f in done:
376
+ futures.remove(f)
377
+
378
+ try:
379
+ s_idx, p_count, e_count, f_count, s_duration, errors = f.result()
380
+ total_processed += p_count
381
+ total_errors += e_count
382
+ total_filtered += f_count
383
+
384
+ # Write error log
385
+ for err in errors:
386
+ err["shard_idx"] = s_idx
387
+ error_logger.error(json.dumps(err, ensure_ascii=False))
388
+
389
+ if p_count > 0:
390
+ tar_abs = os.path.abspath(output_tar_pattern % s_idx)
391
+ jsonl_abs = os.path.abspath(output_jsonl_pattern % s_idx)
392
+ shard_manifest[s_idx] = (
393
+ tar_abs,
394
+ jsonl_abs,
395
+ p_count,
396
+ s_duration,
397
+ )
398
+
399
+ pbar.set_postfix(
400
+ {
401
+ "Samples": total_processed,
402
+ "Filtered": total_filtered,
403
+ "Errors": total_errors,
404
+ }
405
+ )
406
+ pbar.update(1)
407
+ except Exception as e:
408
+ print(f"Shard task failed: {e}")
409
+
410
+ submit_next_chunks(1)
411
+
412
+ pbar.close()
413
+
414
+ # Write final manifest file (data.lst)
415
+ manifest_path = str(output_dir / "data.lst")
416
+ with open(manifest_path, "w", encoding="utf-8") as mf:
417
+ for idx in sorted(shard_manifest.keys()):
418
+ tar_path, jsonl_path, count, duration = shard_manifest[idx]
419
+ mf.write(f"{tar_path} {jsonl_path} {count} {duration:.3f}\n")
420
+
421
+ print(f"\nDone! Output saved to {output_dir}")
422
+ print(f"Successfully packed: {total_processed}")
423
+ print(f"Filtered by duration: {total_filtered}")
424
+ print(f"Failed: {total_errors}")
425
+ print(f"Manifest written to: {manifest_path} ({len(shard_manifest)} shards)")
426
+ if total_errors > 0:
427
+ print(f"Error details: {error_log_path}")
428
+
429
+
430
+ if __name__ == "__main__":
431
+ mp.set_start_method("spawn", force=True)
432
+
433
+ args = build_parser().parse_args()
434
+ pack_dataset(
435
+ input_jsonl=args.input,
436
+ output_dir=args.output,
437
+ samples_per_shard=args.shard_size,
438
+ num_workers=args.workers,
439
+ target_sr=args.sr,
440
+ threads_per_worker=args.threads,
441
+ shuffle=args.shuffle,
442
+ shuffle_seed=args.shuffle_seed,
443
+ min_duration=args.min_duration,
444
+ max_duration=args.max_duration,
445
+ )
omnivoice/training/__init__.py ADDED
File without changes
omnivoice/training/builder.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Builders for constructing training components.
19
+
20
+ Provides factory functions to assemble the model, tokenizer, and data loaders
21
+ from a ``TrainingConfig``. Called by ``omnivoice.cli.train`` to set up training.
22
+
23
+ Key functions:
24
+ - ``build_model_and_tokenizer()``: Loads the model and text tokenizer.
25
+ - ``build_dataloaders()``: Builds train/eval data loaders from a data config JSON.
26
+ The batching strategy is chosen based on ``TrainingConfig.attn_implementation``:
27
+
28
+ - ``"flex_attention"``: sequence packing via ``PackingIterableDataset`` +
29
+ ``PackingDataCollator``. Batch shape is ``[1, C, batch_tokens]``.
30
+ - other (e.g. ``"sdpa"``): length-grouped padding via
31
+ ``StreamLengthGroupDataset`` + ``PaddingDataCollator``. Batch shape
32
+ is ``[B, C, max_len]`` where B ≥ 1 and max_len ≤ batch_tokens.
33
+ """
34
+
35
+ import logging
36
+ from functools import partial
37
+ from typing import Tuple
38
+
39
+ import torch
40
+ from torch.utils.data import DataLoader
41
+ from transformers import AutoConfig, AutoModel, AutoTokenizer
42
+ from transformers import logging as hf_logging
43
+ from transformers.trainer_utils import seed_worker
44
+
45
+ from omnivoice.data.batching import PackingIterableDataset, StreamLengthGroupDataset
46
+ from omnivoice.data.collator import PackingDataCollator, PaddingDataCollator
47
+ from omnivoice.data.dataset import WebDatasetReader, prepare_data_manifests_from_json
48
+ from omnivoice.data.processor import OmniVoiceSampleProcessor
49
+ from omnivoice.models.omnivoice import OmniVoice, OmniVoiceConfig, _resolve_model_path
50
+ from omnivoice.training.config import TrainingConfig
51
+
52
+ logger = logging.getLogger(__name__)
53
+
54
+
55
+ def build_model_and_tokenizer(
56
+ config: TrainingConfig,
57
+ ) -> Tuple[OmniVoice, AutoTokenizer]:
58
+ """Load Tokenizer and Model, handle resizing and special tokens."""
59
+ logger.info("Initializing Model & Tokenizer...")
60
+
61
+ # 1. Tokenizer
62
+ tokenizer_path = (
63
+ config.init_from_checkpoint
64
+ if config.init_from_checkpoint
65
+ else config.llm_name_or_path
66
+ )
67
+ tokenizer_path = _resolve_model_path(tokenizer_path)
68
+ tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
69
+ if tokenizer.pad_token is None:
70
+ tokenizer.pad_token = tokenizer.eos_token
71
+
72
+ new_tokens = [
73
+ "<|denoise|>",
74
+ "<|lang_start|>",
75
+ "<|lang_end|>",
76
+ "<|instruct_start|>",
77
+ "<|instruct_end|>",
78
+ "<|text_start|>",
79
+ "<|text_end|>",
80
+ ]
81
+
82
+ tokens_to_add = [t for t in new_tokens if t not in tokenizer.get_vocab()]
83
+ if tokens_to_add:
84
+ tokenizer.add_special_tokens({"additional_special_tokens": tokens_to_add})
85
+
86
+ if config.init_from_checkpoint:
87
+ logger.info(f"Loading weights from {config.init_from_checkpoint}")
88
+ model = OmniVoice.from_pretrained(
89
+ config.init_from_checkpoint,
90
+ attn_implementation=config.attn_implementation,
91
+ dtype=torch.float32,
92
+ train=True,
93
+ )
94
+ else:
95
+ resolved_llm = _resolve_model_path(config.llm_name_or_path)
96
+ llm_config = AutoConfig.from_pretrained(resolved_llm)
97
+
98
+ ov_config = OmniVoiceConfig(
99
+ audio_vocab_size=config.audio_vocab_size,
100
+ audio_mask_id=config.audio_mask_id,
101
+ num_audio_codebook=config.num_audio_codebook,
102
+ audio_codebook_weights=config.audio_codebook_weights,
103
+ llm_config=llm_config,
104
+ )
105
+
106
+ original_level = hf_logging.get_verbosity()
107
+ hf_logging.set_verbosity_error() # suppress expected lm_head.weight warnings
108
+
109
+ llm = AutoModel.from_pretrained(
110
+ resolved_llm,
111
+ attn_implementation=config.attn_implementation,
112
+ dtype=torch.float32,
113
+ )
114
+
115
+ hf_logging.set_verbosity(original_level)
116
+ model = OmniVoice(config=ov_config, llm=llm)
117
+
118
+ # 3. Resize Embeddings
119
+ if len(tokenizer) != model.config.llm_config.vocab_size:
120
+ model.llm.resize_token_embeddings(len(tokenizer))
121
+ model.config.llm_config.vocab_size = len(tokenizer)
122
+
123
+ # 4. Config IDs
124
+ model.config.pad_token_id = tokenizer.pad_token_id
125
+ model.config.bos_token_id = tokenizer.bos_token_id
126
+ model.config.eos_token_id = tokenizer.eos_token_id
127
+
128
+ return model, tokenizer
129
+
130
+
131
+ def build_dataloaders(
132
+ config: TrainingConfig, tokenizer: AutoTokenizer
133
+ ) -> Tuple[DataLoader, DataLoader]:
134
+ """Setup Data Pipeline: Manifests -> WDS -> Batching -> Loaders.
135
+
136
+ Batching strategy depends on ``config.attn_implementation``:
137
+ - ``"flex_attention"``: sequence packing (PackingIterableDataset +
138
+ PackingDataCollator). All samples are concatenated into one long sequence.
139
+ - other (e.g. ``"sdpa"``): length-grouped padding
140
+ (LengthGroupedIterableDataset + PaddingDataCollator). Samples with
141
+ similar token lengths are batched together and padded to the same length.
142
+ """
143
+ logger.info("Initializing Data Readers...")
144
+
145
+ processor = OmniVoiceSampleProcessor(
146
+ text_tokenizer=tokenizer,
147
+ num_channels=config.num_audio_codebook,
148
+ audio_mask_id=config.audio_mask_id,
149
+ prompt_ratio_range=config.prompt_ratio_range,
150
+ mask_ratio_range=config.mask_ratio_range,
151
+ drop_cond_ratio=config.drop_cond_ratio,
152
+ language_ratio=config.language_ratio,
153
+ use_pinyin_ratio=config.use_pinyin_ratio,
154
+ instruct_ratio=config.instruct_ratio,
155
+ only_instruct_ratio=config.only_instruct_ratio,
156
+ )
157
+
158
+ train_manifests, dev_manifests = prepare_data_manifests_from_json(
159
+ config.data_config
160
+ )
161
+ raw_train_ds = WebDatasetReader(manifests=train_manifests, evaluation=False)
162
+
163
+ use_packing = config.attn_implementation == "flex_attention"
164
+
165
+ if use_packing:
166
+ train_dataset = PackingIterableDataset(
167
+ raw_train_ds, processor, config.batch_tokens
168
+ )
169
+ collate_fn = PackingDataCollator(processor, config.batch_tokens)
170
+ else:
171
+ train_dataset = StreamLengthGroupDataset(
172
+ raw_train_ds,
173
+ batch_duration=config.batch_tokens,
174
+ min_length=config.min_sample_tokens,
175
+ max_length=config.max_sample_tokens,
176
+ max_sample=config.max_batch_size,
177
+ processor=processor,
178
+ length_fn=lambda s: s["length"],
179
+ )
180
+ collate_fn = PaddingDataCollator(processor, config.batch_tokens)
181
+
182
+ logger.info(
183
+ "Using %s (attn_implementation=%s)",
184
+ "sequence packing" if use_packing else "length-grouped padding",
185
+ config.attn_implementation,
186
+ )
187
+
188
+ init_fn = partial(
189
+ seed_worker,
190
+ num_workers=config.num_workers,
191
+ rank=(
192
+ torch.distributed.get_rank()
193
+ if torch.distributed.is_initialized()
194
+ else 0
195
+ ),
196
+ )
197
+
198
+ train_loader = DataLoader(
199
+ train_dataset,
200
+ batch_size=None,
201
+ num_workers=config.num_workers,
202
+ collate_fn=collate_fn,
203
+ worker_init_fn=init_fn,
204
+ pin_memory=True,
205
+ prefetch_factor=4,
206
+ )
207
+
208
+ eval_loader = None
209
+ if dev_manifests:
210
+ raw_dev_ds = WebDatasetReader(
211
+ manifests=dev_manifests, evaluation=True
212
+ )
213
+ if use_packing:
214
+ dev_dataset = PackingIterableDataset(
215
+ raw_dev_ds, processor, config.batch_tokens
216
+ )
217
+ else:
218
+ dev_dataset = StreamLengthGroupDataset(
219
+ raw_dev_ds,
220
+ batch_duration=config.batch_tokens,
221
+ min_length=config.min_sample_tokens,
222
+ max_length=config.max_sample_tokens,
223
+ max_sample=config.max_batch_size,
224
+ processor=processor,
225
+ length_fn=lambda s: s["length"],
226
+ )
227
+ eval_loader = DataLoader(
228
+ dev_dataset,
229
+ batch_size=None, # Each item is already a collated batch
230
+ num_workers=1,
231
+ collate_fn=collate_fn,
232
+ pin_memory=True,
233
+ prefetch_factor=2,
234
+ )
235
+
236
+ return train_loader, eval_loader
omnivoice/training/checkpoint.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Checkpoint saving, resuming, and training logging.
19
+
20
+ Provides utilities for saving/loading training checkpoints and logging metrics
21
+ to console and trackers (TensorBoard/WandB). Used by ``OmniTrainer``.
22
+
23
+ Key components:
24
+ - ``TrainLogger``: Logs training metrics to console and Accelerate trackers.
25
+ - ``save_checkpoint()``: Saves model, optimizer, and scheduler state.
26
+ - ``load_checkpoint()``: Restores training state from a checkpoint directory.
27
+ """
28
+
29
+ import logging
30
+ import os
31
+ import shutil
32
+ import time
33
+ from typing import Any, Dict, Optional
34
+
35
+ import torch
36
+ from accelerate import Accelerator
37
+ from tqdm.auto import tqdm
38
+
39
+ logger = logging.getLogger(__name__)
40
+
41
+
42
+ class TrainLogger:
43
+ """
44
+ Handles logging to console and trackers (TensorBoard/WandB)
45
+ """
46
+
47
+ def __init__(self, accelerator: Accelerator, total_steps: int, logging_steps: int):
48
+ self.accelerator = accelerator
49
+ self.total_steps = total_steps
50
+ self.logging_steps = logging_steps
51
+ self.start_time = None
52
+ self.progress_bar = None
53
+
54
+ def start(self, start_step: int = 0):
55
+ self.start_time = time.time()
56
+
57
+ if self.accelerator.is_main_process:
58
+ self.progress_bar = tqdm(
59
+ total=self.total_steps,
60
+ initial=start_step,
61
+ desc="Training",
62
+ dynamic_ncols=True,
63
+ disable=not self.accelerator.is_local_main_process,
64
+ )
65
+
66
+ def update(
67
+ self, step: int, loss: Optional[float] = None, lr: Optional[float] = None
68
+ ):
69
+ """
70
+ Called every step to update the progress bar UI.
71
+ """
72
+ if self.progress_bar:
73
+ self.progress_bar.update(1)
74
+
75
+ # Update real-time metrics on the progress bar itself
76
+ postfix = {}
77
+ if loss is not None:
78
+ postfix["loss"] = f"{loss:.4f}"
79
+ if lr is not None:
80
+ postfix["lr"] = f"{lr:.2e}"
81
+
82
+ if postfix:
83
+ self.progress_bar.set_postfix(postfix)
84
+
85
+ def log_metrics(self, step: int, metrics: Dict[str, Any]):
86
+ """
87
+ Called periodically to log to TensorBoard/WandB and console.
88
+ """
89
+ # Log to trackers (TensorBoard, etc.)
90
+ self.accelerator.log(metrics, step=step)
91
+
92
+ if self.accelerator.is_main_process:
93
+ # Format for console log (separate from tqdm)
94
+ # Remove keys that are redundant or too verbose for one line
95
+ formatted_metrics = []
96
+ for k, v in metrics.items():
97
+ if isinstance(v, float):
98
+ val_str = f"{v:.4f}"
99
+ if val_str == "0.0000" and v != 0:
100
+ formatted_metrics.append(f"{k}: {v:.2e}")
101
+ else:
102
+ formatted_metrics.append(f"{k}: {val_str}")
103
+ else:
104
+ formatted_metrics.append(f"{k}: {v}")
105
+
106
+ # Use external logger to write to file, tqdm.write to avoid breaking bar
107
+ msg = f"Step {step} | " + " | ".join(formatted_metrics)
108
+ if self.progress_bar:
109
+ self.progress_bar.write(msg)
110
+ else:
111
+ logger.info(msg)
112
+
113
+ def close(self):
114
+ if self.progress_bar:
115
+ self.progress_bar.close()
116
+
117
+
118
+ def save_checkpoint(
119
+ accelerator: Accelerator,
120
+ model: torch.nn.Module,
121
+ tokenizer: Any,
122
+ output_dir: str,
123
+ step: int,
124
+ keep_last_n: int = 3,
125
+ ):
126
+ """
127
+ Saves model, tokenizer, and accelerator states (optimizer/scheduler).
128
+ Manages rotation of checkpoints.
129
+ """
130
+ checkpoint_dir = os.path.join(output_dir, f"checkpoint-{step}")
131
+
132
+ # 1. Save Accelerator State (Optimizer, Scheduler, RNG, Scaler)
133
+ accelerator.save_state(checkpoint_dir)
134
+
135
+ # 2. Save Model in HF format (config.json + pytorch_model.bin/safetensors)
136
+ unwrap_model = accelerator.unwrap_model(model)
137
+ unwrap_model.save_pretrained(
138
+ checkpoint_dir,
139
+ is_main_process=accelerator.is_main_process,
140
+ save_function=accelerator.save,
141
+ )
142
+
143
+ # 3. Save Tokenizer
144
+ if accelerator.is_main_process:
145
+ tokenizer.save_pretrained(checkpoint_dir)
146
+
147
+ logger.info(f"Saved checkpoint to {checkpoint_dir}")
148
+
149
+ # 4. Rotate checkpoints (Keep last N)
150
+ if accelerator.is_main_process and keep_last_n > 0:
151
+ checkpoints = [
152
+ d
153
+ for d in os.listdir(output_dir)
154
+ if d.startswith("checkpoint-")
155
+ and os.path.isdir(os.path.join(output_dir, d))
156
+ ]
157
+ # Sort by step number
158
+ checkpoints.sort(key=lambda x: int(x.split("-")[-1]))
159
+
160
+ if len(checkpoints) > keep_last_n:
161
+ to_remove = checkpoints[:-keep_last_n]
162
+ for d in to_remove:
163
+ shutil.rmtree(os.path.join(output_dir, d))
164
+ logger.info(f"Removed old checkpoint {d}")
165
+
166
+
167
+ def load_checkpoint(accelerator: Accelerator, checkpoint_path: str):
168
+ """
169
+ Resumes training state.
170
+ """
171
+ logger.info(f"Resuming from {checkpoint_path}")
172
+ accelerator.load_state(checkpoint_path)
173
+
174
+ # Try to infer step
175
+ try:
176
+ clean_path = os.path.normpath(checkpoint_path)
177
+ step = int(os.path.basename(clean_path).split("-")[-1])
178
+ return step
179
+ except ValueError:
180
+ return 0
omnivoice/training/config.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Training configuration dataclass.
19
+
20
+ Defines ``TrainingConfig``, a dataclass that holds all hyperparameters and paths
21
+ for training. Loaded from a JSON config file via ``TrainingConfig.from_json()``
22
+ in ``omnivoice.cli.train``.
23
+ """
24
+
25
+ import json
26
+ from dataclasses import asdict, dataclass, field
27
+ from typing import List, Optional, Tuple
28
+
29
+
30
+ @dataclass
31
+ class TrainingConfig:
32
+ # Key Paths
33
+ output_dir: Optional[str] = None
34
+ data_config: Optional[str] = None
35
+
36
+ # Model Specific
37
+ llm_name_or_path: str = "Qwen/Qwen3-0.6B"
38
+ audio_vocab_size: int = 1025 # valid vocab size + 1 (mask token)
39
+ audio_mask_id: int = 1024 # 1024 is the 1025-th token
40
+ num_audio_codebook: int = 8
41
+
42
+ # Model Training Specific
43
+ audio_codebook_weights: List[float | int] = field(
44
+ default_factory=lambda: [8, 8, 6, 6, 4, 4, 2, 2]
45
+ )
46
+ drop_cond_ratio: float = 0.1
47
+ prompt_ratio_range: Tuple[float, float] = field(default_factory=lambda: (0.0, 0.3))
48
+ mask_ratio_range: Tuple[float, float] = field(default_factory=lambda: (0.0, 1.0))
49
+ language_ratio: float = 0.8
50
+ use_pinyin_ratio: float = 0.3
51
+ instruct_ratio: float = 1.0
52
+ only_instruct_ratio: float = 0.5
53
+
54
+ # Init settings
55
+ resume_from_checkpoint: Optional[str] = None
56
+ init_from_checkpoint: Optional[str] = None
57
+
58
+ # Training Hyperparams
59
+ learning_rate: float = 1e-4
60
+ weight_decay: float = 0.01
61
+ max_grad_norm: float = 1.0
62
+ steps: int = 300000
63
+ seed: int = 42
64
+ lr_scheduler_type: str = "cosine"
65
+ warmup_type: str = "ratio"
66
+ warmup_ratio: float = 0.03
67
+ warmup_steps: int = 2000
68
+
69
+ # Data
70
+ batch_tokens: int = 8192
71
+ gradient_accumulation_steps: int = 1
72
+ num_workers: int = 8
73
+
74
+ # System
75
+ mixed_precision: str = "bf16"
76
+ allow_tf32: bool = True
77
+ use_deepspeed: bool = False
78
+ deepspeed_config: Optional[str] = None
79
+ attn_implementation: str = "flex_attention"
80
+
81
+ # Length-grouped batching (only used when attn_implementation != "flex_attention")
82
+ max_sample_tokens: int = 2000
83
+ min_sample_tokens: int = 50
84
+ max_batch_size: int = 64
85
+
86
+ # Logging
87
+ logging_steps: int = 100
88
+ eval_steps: int = 1000
89
+ save_steps: int = 10000
90
+ keep_last_n_checkpoints: int = -1
91
+
92
+ @classmethod
93
+ def from_json(cls, json_path: str):
94
+ with open(json_path, "r") as f:
95
+ cfg_dict = json.load(f)
96
+ valid_keys = cls.__annotations__.keys()
97
+ filtered_dict = {k: v for k, v in cfg_dict.items() if k in valid_keys}
98
+ instance = cls(**filtered_dict)
99
+ return instance
100
+
101
+ def save_to_json(self, json_path: str):
102
+ data = asdict(self)
103
+ with open(json_path, "w") as f:
104
+ json.dump(data, f, indent=4)
omnivoice/training/trainer.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Training loop for OmniVoice.
19
+
20
+ Wraps the HuggingFace Accelerate training loop with checkpoint saving/resuming,
21
+ evaluation, gradient accumulation, and learning rate scheduling.
22
+ Launched via ``omnivoice.cli.train``.
23
+ """
24
+
25
+ import logging
26
+ import math
27
+ import os
28
+ import sys
29
+ import time
30
+ from datetime import timedelta
31
+ from typing import Any, Optional
32
+
33
+ import torch
34
+ from accelerate import Accelerator, DistributedDataParallelKwargs
35
+ from accelerate.utils import DeepSpeedPlugin, InitProcessGroupKwargs, set_seed
36
+ from torch.utils.data import DataLoader
37
+ from transformers import (
38
+ get_cosine_schedule_with_warmup,
39
+ get_constant_schedule_with_warmup,
40
+ )
41
+
42
+ from omnivoice.training.checkpoint import TrainLogger, load_checkpoint
43
+ from omnivoice.training.checkpoint import save_checkpoint as engine_save_checkpoint
44
+
45
+ logger = logging.getLogger(__name__)
46
+
47
+
48
+ def _to_device(batch, device):
49
+ """Move all tensors in a batch dict to the target device."""
50
+ return {
51
+ k: v.to(device, non_blocking=True) if isinstance(v, torch.Tensor) else v
52
+ for k, v in batch.items()
53
+ }
54
+
55
+
56
+ class OmniTrainer:
57
+ def __init__(
58
+ self,
59
+ model: torch.nn.Module,
60
+ config: Any, # TrainingConfig
61
+ train_dataloader: DataLoader,
62
+ eval_dataloader: Optional[DataLoader] = None,
63
+ tokenizer: Optional[Any] = None,
64
+ optimizer: Optional[torch.optim.Optimizer] = None,
65
+ lr_scheduler: Optional[Any] = None,
66
+ ):
67
+ self.config = config
68
+ self.model = model
69
+ self.tokenizer = tokenizer
70
+ self.train_dataloader = train_dataloader
71
+ self.eval_dataloader = eval_dataloader
72
+
73
+ # 1. Initialize Accelerator
74
+ self.accelerator = self._init_accelerator()
75
+
76
+ # 2. Setup Optimizer & Scheduler if not provided
77
+ if optimizer is None:
78
+ self.optimizer, self.lr_scheduler = self.create_optimizer_and_scheduler()
79
+ else:
80
+ self.optimizer = optimizer
81
+ self.lr_scheduler = lr_scheduler
82
+
83
+ # 3. DeepSpeed Hack (Batch Size fix)
84
+ if self.accelerator.distributed_type == "DEEPSPEED":
85
+ self.accelerator.state.deepspeed_plugin.deepspeed_config[
86
+ "train_micro_batch_size_per_gpu"
87
+ ] = 1
88
+
89
+ # 4. Prepare with Accelerator
90
+ (self.model, self.optimizer, self.lr_scheduler,) = self.accelerator.prepare(
91
+ self.model,
92
+ self.optimizer,
93
+ self.lr_scheduler,
94
+ )
95
+
96
+ self.global_step = 0
97
+ self.epoch = 0
98
+
99
+ def _init_accelerator(self) -> Accelerator:
100
+ """Initialize Accelerator, DeepSpeed, and Logging."""
101
+ # TF32 setup
102
+ if getattr(self.config, "allow_tf32", False):
103
+ torch.set_float32_matmul_precision("high")
104
+
105
+ # Init handlers
106
+ ddp_kwargs = DistributedDataParallelKwargs(find_unused_parameters=False)
107
+ init_kwargs = InitProcessGroupKwargs(timeout=timedelta(minutes=60))
108
+
109
+ # DeepSpeed setup
110
+ deepspeed_plugin = None
111
+ if self.config.use_deepspeed and self.config.deepspeed_config:
112
+ if not os.path.exists(self.config.deepspeed_config):
113
+ raise FileNotFoundError(
114
+ f"DeepSpeed config not found: {self.config.deepspeed_config}"
115
+ )
116
+ deepspeed_plugin = DeepSpeedPlugin(
117
+ hf_ds_config=self.config.deepspeed_config,
118
+ gradient_accumulation_steps=self.config.gradient_accumulation_steps,
119
+ gradient_clipping=self.config.max_grad_norm,
120
+ )
121
+
122
+ accelerator = Accelerator(
123
+ gradient_accumulation_steps=self.config.gradient_accumulation_steps,
124
+ mixed_precision=self.config.mixed_precision,
125
+ log_with="tensorboard",
126
+ project_dir=self.config.output_dir,
127
+ step_scheduler_with_optimizer=False,
128
+ kwargs_handlers=[ddp_kwargs, init_kwargs],
129
+ deepspeed_plugin=deepspeed_plugin,
130
+ split_batches=False,
131
+ )
132
+
133
+ # Logging setup
134
+ if accelerator.is_main_process:
135
+ os.makedirs(self.config.output_dir, exist_ok=True)
136
+ # Try to save config if it has the method
137
+ if hasattr(self.config, "save_to_json"):
138
+ self.config.save_to_json(
139
+ os.path.join(self.config.output_dir, "initial_config.json")
140
+ )
141
+
142
+ logging.basicConfig(
143
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
144
+ datefmt="%m/%d/%Y %H:%M:%S",
145
+ level=logging.INFO,
146
+ handlers=[
147
+ logging.StreamHandler(sys.stdout),
148
+ logging.FileHandler(
149
+ os.path.join(self.config.output_dir, "train.log")
150
+ ),
151
+ ],
152
+ )
153
+ else:
154
+ logging.basicConfig(level=logging.ERROR)
155
+
156
+ logger.info(f"Loaded Config: {self.config}")
157
+ set_seed(self.config.seed)
158
+ accelerator.init_trackers("tensorboard")
159
+ return accelerator
160
+
161
+ def create_optimizer_and_scheduler(self):
162
+ """Default AdamW + configurable LR Scheduler."""
163
+ optimizer = torch.optim.AdamW(
164
+ self.model.parameters(),
165
+ lr=self.config.learning_rate,
166
+ weight_decay=self.config.weight_decay,
167
+ )
168
+
169
+ if self.config.warmup_type == "ratio":
170
+ final_warmup_steps = math.ceil(self.config.steps * self.config.warmup_ratio)
171
+ else:
172
+ final_warmup_steps = self.config.warmup_steps
173
+
174
+ if self.config.lr_scheduler_type == "constant":
175
+ lr_scheduler = get_constant_schedule_with_warmup(
176
+ optimizer=optimizer,
177
+ num_warmup_steps=final_warmup_steps,
178
+ )
179
+ else:
180
+ lr_scheduler = get_cosine_schedule_with_warmup(
181
+ optimizer=optimizer,
182
+ num_warmup_steps=final_warmup_steps,
183
+ num_training_steps=self.config.steps,
184
+ )
185
+ return optimizer, lr_scheduler
186
+
187
+ def save_checkpoint(self, step):
188
+ """Wrapper for engine save_checkpoint."""
189
+ engine_save_checkpoint(
190
+ self.accelerator,
191
+ self.model,
192
+ self.tokenizer,
193
+ self.config.output_dir,
194
+ step,
195
+ self.config.keep_last_n_checkpoints,
196
+ )
197
+ # Save config copy for convenience
198
+ if self.accelerator.is_main_process and hasattr(self.config, "save_to_json"):
199
+ checkpoint_dir = os.path.join(self.config.output_dir, f"checkpoint-{step}")
200
+ self.config.save_to_json(os.path.join(checkpoint_dir, "train_config.json"))
201
+
202
+ def load_checkpoint(self, checkpoint_path):
203
+ """Wrapper for loading."""
204
+ step = load_checkpoint(self.accelerator, checkpoint_path)
205
+ self.global_step = step
206
+ logger.info(f"Resumed from step {self.global_step}")
207
+ return step
208
+
209
+ def evaluate(self):
210
+ """Evaluation loop."""
211
+ if self.eval_dataloader is None:
212
+ return {}
213
+
214
+ self.model.eval()
215
+ logger.info(f"Running evaluation at step {self.global_step}...")
216
+
217
+ local_loss_sum = torch.tensor(0.0, device=self.accelerator.device)
218
+ eval_count = 0
219
+
220
+ with torch.no_grad():
221
+ for eval_batch in self.eval_dataloader:
222
+ eval_batch = _to_device(eval_batch, self.accelerator.device)
223
+ outputs = self.model(**eval_batch)
224
+ local_loss_sum += outputs.loss.detach()
225
+ eval_count += 1
226
+
227
+ if eval_count > 0:
228
+ local_mean = local_loss_sum / eval_count
229
+ else:
230
+ local_mean = torch.tensor(0.0, device=self.accelerator.device)
231
+
232
+ all_means = self.accelerator.gather(local_mean)
233
+ final_eval_loss = all_means.mean().item()
234
+
235
+ eval_metrics = {"eval/loss": final_eval_loss}
236
+ self.accelerator.log(eval_metrics, step=self.global_step)
237
+ logger.info(f"Eval Loss: {final_eval_loss:.4f}")
238
+
239
+ self.accelerator.wait_for_everyone()
240
+ self.model.train()
241
+ return eval_metrics
242
+
243
+ def train(self):
244
+ """Main training loop."""
245
+ logger.info("Starting Training Loop...")
246
+
247
+ # Resume if configured
248
+ if self.config.resume_from_checkpoint:
249
+ self.load_checkpoint(self.config.resume_from_checkpoint)
250
+
251
+ # Handle IterableDataset Epochs
252
+ if hasattr(self.train_dataloader.dataset, "set_epoch"):
253
+ self.train_dataloader.dataset.set_epoch(self.epoch)
254
+
255
+ # Logger
256
+ train_logger = TrainLogger(
257
+ self.accelerator, self.config.steps, self.config.logging_steps
258
+ )
259
+ train_logger.start(self.global_step)
260
+
261
+ self.model.train()
262
+ train_iterator = iter(self.train_dataloader)
263
+
264
+ logging_start_time = time.time()
265
+ logging_start_step = self.global_step
266
+ tr_loss = torch.tensor(0.0).to(self.accelerator.device)
267
+ logging_loss_scalar = 0.0
268
+
269
+ while self.global_step < self.config.steps:
270
+ try:
271
+ batch = next(train_iterator)
272
+ except StopIteration:
273
+ self.epoch += 1
274
+ logger.info(f"Epoch {self.epoch} starting. Resetting dataloader...")
275
+ if hasattr(self.train_dataloader.dataset, "set_epoch"):
276
+ self.train_dataloader.dataset.set_epoch(self.epoch)
277
+
278
+ train_iterator = iter(self.train_dataloader)
279
+ batch = next(train_iterator)
280
+
281
+ batch = _to_device(batch, self.accelerator.device)
282
+
283
+ with self.accelerator.accumulate(self.model):
284
+ outputs = self.model(**batch)
285
+ loss = outputs.loss
286
+ tr_loss += loss.detach()
287
+ self.accelerator.backward(loss)
288
+
289
+ if self.accelerator.sync_gradients:
290
+ # Clipping
291
+ grad_norm = 0.0
292
+ if self.config.max_grad_norm > 0:
293
+ grad_norm = self.accelerator.clip_grad_norm_(
294
+ self.model.parameters(), self.config.max_grad_norm
295
+ )
296
+ grad_norm = (
297
+ grad_norm.item() if grad_norm is not None else 0.0
298
+ )
299
+
300
+ self.optimizer.step()
301
+ self.lr_scheduler.step()
302
+ self.optimizer.zero_grad()
303
+ self.global_step += 1
304
+
305
+ # Logging
306
+ current_lr = self.lr_scheduler.get_last_lr()[0]
307
+ train_logger.update(
308
+ step=self.global_step, loss=loss.item(), lr=current_lr
309
+ )
310
+
311
+ if self.global_step % self.config.logging_steps == 0:
312
+ elapsed = time.time() - logging_start_time
313
+ steps_per_sec = (
314
+ (self.global_step - logging_start_step) / elapsed
315
+ if elapsed > 0
316
+ else 0
317
+ )
318
+
319
+ tr_loss_scalar = self.accelerator.gather(tr_loss).mean().item()
320
+ current_interval_loss = tr_loss_scalar - logging_loss_scalar
321
+ avg_loss = current_interval_loss / (
322
+ self.config.logging_steps
323
+ * self.config.gradient_accumulation_steps
324
+ )
325
+ logging_loss_scalar = tr_loss_scalar
326
+
327
+ logs = {
328
+ "train/loss": avg_loss,
329
+ "train/learning_rate": current_lr,
330
+ "train/grad_norm": grad_norm,
331
+ "train/epoch": self.epoch,
332
+ "train/steps_per_sec": steps_per_sec,
333
+ }
334
+ train_logger.log_metrics(step=self.global_step, metrics=logs)
335
+
336
+ logging_start_time = time.time()
337
+ logging_start_step = self.global_step
338
+
339
+ # Evaluate
340
+ if (
341
+ self.eval_dataloader is not None
342
+ and self.global_step % self.config.eval_steps == 0
343
+ ):
344
+ self.evaluate()
345
+
346
+ # Save
347
+ if self.global_step % self.config.save_steps == 0:
348
+ self.save_checkpoint(self.global_step)
349
+
350
+ # Final Save
351
+ self.save_checkpoint(self.global_step)
352
+ train_logger.close()
353
+ self.accelerator.end_training()
omnivoice/utils/__init__.py ADDED
File without changes
omnivoice/utils/audio.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Audio I/O and processing utilities.
19
+
20
+ Provides functions for loading, resampling, silence removal,
21
+ chunking, cross-fading, and format conversion.
22
+
23
+ All public functions in this module operate on **numpy float32 arrays**
24
+ with shape ``(C, T)`` (channels-first).
25
+ """
26
+
27
+ import io
28
+ import logging
29
+
30
+ import numpy as np
31
+ import soundfile as sf
32
+ import torch
33
+ import torchaudio
34
+ from pydub import AudioSegment
35
+ from pydub.silence import detect_leading_silence, detect_nonsilent, split_on_silence
36
+
37
+ logger = logging.getLogger(__name__)
38
+
39
+
40
+ # ---------------------------------------------------------------------------
41
+ # Loading
42
+ # ---------------------------------------------------------------------------
43
+
44
+
45
+ def load_waveform(audio_path: str):
46
+ """Load audio from a file path, returning (data, sample_rate).
47
+
48
+ Tries two backends in order:
49
+ 1. soundfile — covers WAV/FLAC/OGG etc., no ffmpeg needed.
50
+ 2. librosa — covers MP3/M4A etc. via audioread + ffmpeg.
51
+
52
+ Returns:
53
+ (data, sample_rate) where data is a numpy float32 array of
54
+ shape (C, T).
55
+ """
56
+ try:
57
+ data, sr = sf.read(audio_path, dtype="float32", always_2d=True)
58
+ return data.T, sr # (T, C) → (C, T)
59
+ except Exception:
60
+ # soundfile cannot handle MP3/M4A etc., fall back to librosa.
61
+ import librosa
62
+
63
+ data, sr = librosa.load(audio_path, sr=None, mono=False)
64
+ if data.ndim == 1:
65
+ data = data[np.newaxis, :]
66
+ return data, sr
67
+
68
+
69
+ def load_audio(audio_path: str, sampling_rate: int) -> np.ndarray:
70
+ """Load a waveform from file and resample to the target rate.
71
+
72
+ Parameters:
73
+ audio_path: path of the audio.
74
+ sampling_rate: target sampling rate.
75
+
76
+ Returns:
77
+ Numpy float32 array of shape (1, T).
78
+ """
79
+ data, sr = load_waveform(audio_path)
80
+
81
+ if data.shape[0] > 1:
82
+ data = np.mean(data, axis=0, keepdims=True)
83
+ if sr != sampling_rate:
84
+ data = torchaudio.functional.resample(
85
+ torch.from_numpy(data), orig_freq=sr, new_freq=sampling_rate
86
+ ).numpy()
87
+
88
+ return data
89
+
90
+
91
+ def load_audio_bytes(raw: bytes, sampling_rate: int) -> np.ndarray:
92
+ """Load audio from in-memory bytes and resample.
93
+
94
+ Parameters:
95
+ raw: raw audio file bytes (e.g. from WebDataset).
96
+ sampling_rate: target sampling rate.
97
+
98
+ Returns:
99
+ Numpy float32 array of shape (1, T).
100
+ """
101
+ buf = io.BytesIO(raw)
102
+
103
+ try:
104
+ data, sr = sf.read(buf, dtype="float32", always_2d=True)
105
+ data = data.T # (T, C) → (C, T)
106
+ except Exception:
107
+ import librosa
108
+
109
+ buf.seek(0)
110
+ data, sr = librosa.load(buf, sr=None, mono=False)
111
+ if data.ndim == 1:
112
+ data = data[np.newaxis, :]
113
+
114
+ if data.shape[0] > 1:
115
+ data = np.mean(data, axis=0, keepdims=True)
116
+ if sr != sampling_rate:
117
+ data = torchaudio.functional.resample(
118
+ torch.from_numpy(data), orig_freq=sr, new_freq=sampling_rate
119
+ ).numpy()
120
+
121
+ return data
122
+
123
+
124
+ # ---------------------------------------------------------------------------
125
+ # Audio processing (all numpy in / numpy out)
126
+ # ---------------------------------------------------------------------------
127
+
128
+
129
+ def numpy_to_audiosegment(audio: np.ndarray, sample_rate: int) -> AudioSegment:
130
+ """Convert a numpy float32 array of shape (C, T) to a pydub AudioSegment."""
131
+ audio_int = (audio * 32768.0).clip(-32768, 32767).astype(np.int16)
132
+ if audio_int.shape[0] > 1:
133
+ audio_int = audio_int.T.flatten() # interleave channels
134
+ return AudioSegment(
135
+ data=audio_int.tobytes(),
136
+ sample_width=2,
137
+ frame_rate=sample_rate,
138
+ channels=audio.shape[0],
139
+ )
140
+
141
+
142
+ def audiosegment_to_numpy(aseg: AudioSegment) -> np.ndarray:
143
+ """Convert a pydub AudioSegment to a numpy float32 array of shape (C, T)."""
144
+ data = np.array(aseg.get_array_of_samples()).astype(np.float32) / 32768.0
145
+ if aseg.channels == 1:
146
+ return data[np.newaxis, :]
147
+ return data.reshape(-1, aseg.channels).T
148
+
149
+
150
+ def remove_silence(
151
+ audio: np.ndarray,
152
+ sampling_rate: int,
153
+ mid_sil: int = 300,
154
+ lead_sil: int = 100,
155
+ trail_sil: int = 300,
156
+ ) -> np.ndarray:
157
+ """Remove middle silences longer than *mid_sil* ms and trim edge silences.
158
+
159
+ Parameters:
160
+ audio: numpy array with shape (C, T).
161
+ sampling_rate: sampling rate of the audio.
162
+ mid_sil: middle-silence threshold in ms (0 to skip).
163
+ lead_sil: kept leading silence in ms.
164
+ trail_sil: kept trailing silence in ms.
165
+
166
+ Returns:
167
+ Numpy array with shape (C, T').
168
+ """
169
+ wave = numpy_to_audiosegment(audio, sampling_rate)
170
+
171
+ if mid_sil > 0:
172
+ non_silent_segs = split_on_silence(
173
+ wave,
174
+ min_silence_len=mid_sil,
175
+ silence_thresh=-50,
176
+ keep_silence=mid_sil,
177
+ seek_step=10,
178
+ )
179
+ wave = AudioSegment.silent(duration=0)
180
+ for seg in non_silent_segs:
181
+ wave += seg
182
+
183
+ wave = remove_silence_edges(wave, lead_sil, trail_sil, -50)
184
+
185
+ return audiosegment_to_numpy(wave)
186
+
187
+
188
+ def remove_silence_edges(
189
+ audio: AudioSegment,
190
+ lead_sil: int = 100,
191
+ trail_sil: int = 300,
192
+ silence_threshold: float = -50,
193
+ ) -> AudioSegment:
194
+ """Remove edge silences, keeping *lead_sil* / *trail_sil* ms."""
195
+ start_idx = detect_leading_silence(audio, silence_threshold=silence_threshold)
196
+ start_idx = max(0, start_idx - lead_sil)
197
+ audio = audio[start_idx:]
198
+
199
+ audio = audio.reverse()
200
+ start_idx = detect_leading_silence(audio, silence_threshold=silence_threshold)
201
+ start_idx = max(0, start_idx - trail_sil)
202
+ audio = audio[start_idx:]
203
+ audio = audio.reverse()
204
+
205
+ return audio
206
+
207
+
208
+ def fade_and_pad_audio(
209
+ audio: np.ndarray,
210
+ pad_duration: float = 0.1,
211
+ fade_duration: float = 0.1,
212
+ sample_rate: int = 24000,
213
+ ) -> np.ndarray:
214
+ """Apply fade-in/out and pad with silence to prevent clicks.
215
+
216
+ Args:
217
+ audio: numpy array of shape (C, T).
218
+ pad_duration: silence padding duration per side (seconds).
219
+ fade_duration: fade curve duration (seconds).
220
+ sample_rate: audio sampling rate.
221
+
222
+ Returns:
223
+ Processed numpy array of shape (C, T_new).
224
+ """
225
+ if audio.shape[-1] == 0:
226
+ return audio
227
+
228
+ fade_samples = int(fade_duration * sample_rate)
229
+ pad_samples = int(pad_duration * sample_rate)
230
+
231
+ processed = audio.copy()
232
+
233
+ if fade_samples > 0:
234
+ k = min(fade_samples, processed.shape[-1] // 2)
235
+ if k > 0:
236
+ fade_in = np.linspace(0, 1, k, dtype=np.float32)[np.newaxis, :]
237
+ processed[..., :k] *= fade_in
238
+
239
+ fade_out = np.linspace(1, 0, k, dtype=np.float32)[np.newaxis, :]
240
+ processed[..., -k:] *= fade_out
241
+
242
+ if pad_samples > 0:
243
+ silence = np.zeros(
244
+ (processed.shape[0], pad_samples),
245
+ dtype=processed.dtype,
246
+ )
247
+ processed = np.concatenate([silence, processed, silence], axis=-1)
248
+
249
+ return processed
250
+
251
+
252
+ def trim_long_audio(
253
+ audio: np.ndarray,
254
+ sampling_rate: int,
255
+ max_duration: float = 15.0,
256
+ min_duration: float = 3.0,
257
+ trim_threshold: float = 20.0,
258
+ ) -> np.ndarray:
259
+ """Trim audio to <= *max_duration* by splitting at the largest silence gap.
260
+
261
+ Only trims when the audio exceeds *trim_threshold* seconds.
262
+
263
+ Args:
264
+ audio: numpy array of shape (C, T).
265
+ sampling_rate: audio sampling rate.
266
+ max_duration: maximum duration in seconds.
267
+ min_duration: minimum duration in seconds.
268
+ trim_threshold: only trim if audio is longer than this (seconds).
269
+
270
+ Returns:
271
+ Trimmed numpy array.
272
+ """
273
+ duration = audio.shape[-1] / sampling_rate
274
+ if duration <= trim_threshold:
275
+ return audio
276
+
277
+ seg = numpy_to_audiosegment(audio, sampling_rate)
278
+ nonsilent = detect_nonsilent(
279
+ seg, min_silence_len=100, silence_thresh=-40, seek_step=10
280
+ )
281
+ if not nonsilent:
282
+ return audio
283
+
284
+ max_ms = int(max_duration * 1000)
285
+ min_ms = int(min_duration * 1000)
286
+
287
+ best_split = 0
288
+ for start, end in nonsilent:
289
+ if start > best_split and start <= max_ms:
290
+ best_split = start
291
+ if end > max_ms:
292
+ break
293
+
294
+ if best_split < min_ms:
295
+ best_split = min(max_ms, len(seg))
296
+
297
+ trimmed = seg[:best_split]
298
+ return audiosegment_to_numpy(trimmed)
299
+
300
+
301
+ def cross_fade_chunks(
302
+ chunks: list[np.ndarray],
303
+ sample_rate: int,
304
+ silence_duration: float = 0.3,
305
+ ) -> np.ndarray:
306
+ """Concatenate audio chunks with silence gaps and cross-fade at boundaries.
307
+
308
+ Args:
309
+ chunks: list of numpy arrays, each (C, T).
310
+ sample_rate: audio sample rate.
311
+ silence_duration: total silence gap duration in seconds.
312
+
313
+ Returns:
314
+ Merged numpy array (C, T_total).
315
+ """
316
+ if len(chunks) == 1:
317
+ return chunks[0]
318
+
319
+ total_n = int(silence_duration * sample_rate)
320
+ fade_n = total_n // 3
321
+ silence_n = fade_n
322
+ merged = chunks[0].copy()
323
+
324
+ for chunk in chunks[1:]:
325
+ parts = [merged]
326
+
327
+ fout_n = min(fade_n, merged.shape[-1])
328
+ if fout_n > 0:
329
+ w_out = np.linspace(1, 0, fout_n, dtype=np.float32)[np.newaxis, :]
330
+ parts[-1][..., -fout_n:] *= w_out
331
+
332
+ parts.append(np.zeros((chunks[0].shape[0], silence_n), dtype=np.float32))
333
+
334
+ fade_in = chunk.copy()
335
+ fin_n = min(fade_n, fade_in.shape[-1])
336
+ if fin_n > 0:
337
+ w_in = np.linspace(0, 1, fin_n, dtype=np.float32)[np.newaxis, :]
338
+ fade_in[..., :fin_n] *= w_in
339
+
340
+ parts.append(fade_in)
341
+ merged = np.concatenate(parts, axis=-1)
342
+
343
+ return merged
omnivoice/utils/common.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Shared utility functions."""
19
+
20
+ import argparse
21
+ import random
22
+
23
+ import numpy as np
24
+ import torch
25
+
26
+
27
+ def str2bool(v):
28
+ """Used in argparse.ArgumentParser.add_argument to indicate
29
+ that a type is a bool type and user can enter
30
+
31
+ - yes, true, t, y, 1, to represent True
32
+ - no, false, f, n, 0, to represent False
33
+
34
+ See https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse # noqa
35
+ """
36
+ if isinstance(v, bool):
37
+ return v
38
+ if v.lower() in ("yes", "true", "t", "y", "1"):
39
+ return True
40
+ elif v.lower() in ("no", "false", "f", "n", "0"):
41
+ return False
42
+ else:
43
+ raise argparse.ArgumentTypeError("Boolean value expected.")
44
+
45
+
46
+ def fix_random_seed(random_seed: int):
47
+ """
48
+ Set the same random seed for the libraries and modules.
49
+ Includes the ``random`` module, numpy, and torch.
50
+ """
51
+ random.seed(random_seed)
52
+ np.random.seed(random_seed)
53
+ torch.random.manual_seed(random_seed)
54
+ # Ensure deterministic ID creation
55
+ rd = random.Random()
56
+ rd.seed(random_seed)
omnivoice/utils/data_utils.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Data utilities for batch inference and evaluation.
19
+
20
+ Provides ``read_test_list()`` to parse JSONL test list files used by
21
+ ``omnivoice.cli.infer_batch`` and evaluation scripts.
22
+ """
23
+
24
+ import json
25
+ import logging
26
+ from pathlib import Path
27
+
28
+
29
+ def read_test_list(path):
30
+ """Read a JSONL test list file.
31
+
32
+ Each line should be a JSON object. Only ``id`` and ``text`` are required;
33
+ all other fields are optional (default to ``None``):
34
+ id, text, ref_audio, ref_text, instruct,
35
+ language_id, language_name, duration, speed
36
+
37
+ Note: ``language_name`` is only used by evaluation scripts (under
38
+ ``omnivoice/eval/``) for grouping and reporting results. The model
39
+ itself only consumes ``language_id``.
40
+
41
+ Returns a list of dicts.
42
+ """
43
+ path = Path(path)
44
+ samples = []
45
+ with path.open("r", encoding="utf-8") as f:
46
+ for line_no, line in enumerate(f, 1):
47
+ line = line.strip()
48
+ if not line:
49
+ continue
50
+ try:
51
+ obj = json.loads(line)
52
+ except json.JSONDecodeError:
53
+ logging.warning(f"Skipping malformed JSON at line {line_no}: {line}")
54
+ continue
55
+
56
+ sample = {
57
+ "id": obj.get("id"),
58
+ "text": obj.get("text"),
59
+ "ref_audio": obj.get("ref_audio"),
60
+ "ref_text": obj.get("ref_text"),
61
+ "language_id": obj.get("language_id"),
62
+ "language_name": obj.get("language_name"),
63
+ "duration": obj.get("duration"),
64
+ "speed": obj.get("speed"),
65
+ "instruct": obj.get("instruct"),
66
+ }
67
+ samples.append(sample)
68
+ return samples
omnivoice/utils/duration.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Text duration estimation for TTS generation.
19
+
20
+ Provides ``RuleDurationEstimator``, which estimates audio duration from text
21
+ using character phonetic weights across 600+ languages. Used by
22
+ ``OmniVoice.generate()`` to determine output length when no duration is specified.
23
+ """
24
+
25
+ import bisect
26
+ import unicodedata
27
+ from functools import lru_cache
28
+ from typing import Optional
29
+
30
+
31
+ class RuleDurationEstimator:
32
+ def __init__(self):
33
+ # ==========================================
34
+ # 1. Phonetic Weights Table
35
+ # ==========================================
36
+ # The weight represents the relative speaking time compared to
37
+ # a standard Latin letter.
38
+ # Benchmark: 1.0 = One Latin Character (~40-50ms)
39
+ self.weights = {
40
+ # --- Logographic (1 char = full syllable/word) ---
41
+ "cjk": 3.0, # Chinese, Japanese Kanji, etc.
42
+ # --- Syllabic / Blocks
43
+ "hangul": 2.5, # Korean Hangul
44
+ "kana": 2.2, # Japanese Hiragana/Katakana
45
+ "ethiopic": 3.0, # Amharic/Ge'ez
46
+ "yi": 3.0, # Yi script
47
+ # --- Abugida (Consonant-Vowel complexes) ---
48
+ "indic": 1.8, # Hindi, Bengali, Tamil, etc.
49
+ "thai_lao": 1.5, # Thai, Lao
50
+ "khmer_myanmar": 1.8, # Khmer, Myanmar
51
+ # --- Abjad (Consonant-heavy) ---
52
+ "arabic": 1.5, # Arabic, Persian, Urdu
53
+ "hebrew": 1.5, # Hebrew
54
+ # --- Alphabet (Segmental) ---
55
+ "latin": 1.0, # English, Spanish, French, Vietnamese, etc. (Baseline)
56
+ "cyrillic": 1.0, # Russian, Ukrainian
57
+ "greek": 1.0, # Greek
58
+ "armenian": 1.0, # Armenian
59
+ "georgian": 1.0, # Georgian
60
+ # --- Symbols & Misc ---
61
+ "punctuation": 0.5, # Pause capability
62
+ "space": 0.2, # Word boundary/Breath (0.05 / 0.22)
63
+ "digit": 3.5, # Numbers
64
+ "mark": 0.0, # Diacritics/Accents (Silent modifiers)
65
+ "default": 1.0, # Fallback for unknown scripts
66
+ }
67
+
68
+ # ==========================================
69
+ # 2. Unicode Range Mapping
70
+ # ==========================================
71
+ # Format: (End_Codepoint, Type_Key)
72
+ # Used for fast binary search (bisect).
73
+ self.ranges = [
74
+ (0x02AF, "latin"), # Latin (Basic, Supplement, Ext, IPA)
75
+ (0x03FF, "greek"), # Greek & Coptic
76
+ (0x052F, "cyrillic"), # Cyrillic
77
+ (0x058F, "armenian"), # Armenian
78
+ (0x05FF, "hebrew"), # Hebrew
79
+ (0x077F, "arabic"), # Arabic, Syriac, Arabic Supplement
80
+ (0x089F, "arabic"), # Arabic Extended-B (+ Syriac Supp)
81
+ (0x08FF, "arabic"), # Arabic Extended-A
82
+ (0x097F, "indic"), # Devanagari
83
+ (0x09FF, "indic"), # Bengali
84
+ (0x0A7F, "indic"), # Gurmukhi
85
+ (0x0AFF, "indic"), # Gujarati
86
+ (0x0B7F, "indic"), # Oriya
87
+ (0x0BFF, "indic"), # Tamil
88
+ (0x0C7F, "indic"), # Telugu
89
+ (0x0CFF, "indic"), # Kannada
90
+ (0x0D7F, "indic"), # Malayalam
91
+ (0x0DFF, "indic"), # Sinhala
92
+ (0x0EFF, "thai_lao"), # Thai & Lao
93
+ (0x0FFF, "indic"), # Tibetan (Abugida)
94
+ (0x109F, "khmer_myanmar"), # Myanmar
95
+ (0x10FF, "georgian"), # Georgian
96
+ (0x11FF, "hangul"), # Hangul Jamo
97
+ (0x137F, "ethiopic"), # Ethiopic
98
+ (0x139F, "ethiopic"), # Ethiopic Supplement
99
+ (0x13FF, "default"), # Cherokee
100
+ (0x167F, "default"), # Canadian Aboriginal Syllabics
101
+ (0x169F, "default"), # Ogham
102
+ (0x16FF, "default"), # Runic
103
+ (0x171F, "default"), # Tagalog (Baybayin)
104
+ (0x173F, "default"), # Hanunoo
105
+ (0x175F, "default"), # Buhid
106
+ (0x177F, "default"), # Tagbanwa
107
+ (0x17FF, "khmer_myanmar"), # Khmer
108
+ (0x18AF, "default"), # Mongolian
109
+ (0x18FF, "default"), # Canadian Aboriginal Syllabics Ext
110
+ (0x194F, "indic"), # Limbu
111
+ (0x19DF, "indic"), # Tai Le & New Tai Lue
112
+ (0x19FF, "khmer_myanmar"), # Khmer Symbols
113
+ (0x1A1F, "indic"), # Buginese
114
+ (0x1AAF, "indic"), # Tai Tham
115
+ (0x1B7F, "indic"), # Balinese
116
+ (0x1BBF, "indic"), # Sundanese
117
+ (0x1BFF, "indic"), # Batak
118
+ (0x1C4F, "indic"), # Lepcha
119
+ (0x1C7F, "indic"), # Ol Chiki (Santali)
120
+ (0x1C8F, "cyrillic"), # Cyrillic Extended-C
121
+ (0x1CBF, "georgian"), # Georgian Extended
122
+ (0x1CCF, "indic"), # Sundanese Supplement
123
+ (0x1CFF, "indic"), # Vedic Extensions
124
+ (0x1D7F, "latin"), # Phonetic Extensions
125
+ (0x1DBF, "latin"), # Phonetic Extensions Supplement
126
+ (0x1DFF, "default"), # Combining Diacritical Marks Supplement
127
+ (0x1EFF, "latin"), # Latin Extended Additional (Vietnamese)
128
+ (0x309F, "kana"), # Hiragana
129
+ (0x30FF, "kana"), # Katakana
130
+ (0x312F, "cjk"), # Bopomofo (Pinyin)
131
+ (0x318F, "hangul"), # Hangul Compatibility Jamo
132
+ (0x9FFF, "cjk"), # CJK Unified Ideographs (Main)
133
+ (0xA4CF, "yi"), # Yi Syllables
134
+ (0xA4FF, "default"), # Lisu
135
+ (0xA63F, "default"), # Vai
136
+ (0xA69F, "cyrillic"), # Cyrillic Extended-B
137
+ (0xA6FF, "default"), # Bamum
138
+ (0xA7FF, "latin"), # Latin Extended-D
139
+ (0xA82F, "indic"), # Syloti Nagri
140
+ (0xA87F, "default"), # Phags-pa
141
+ (0xA8DF, "indic"), # Saurashtra
142
+ (0xA8FF, "indic"), # Devanagari Extended
143
+ (0xA92F, "indic"), # Kayah Li
144
+ (0xA95F, "indic"), # Rejang
145
+ (0xA97F, "hangul"), # Hangul Jamo Extended-A
146
+ (0xA9DF, "indic"), # Javanese
147
+ (0xA9FF, "khmer_myanmar"), # Myanmar Extended-B
148
+ (0xAA5F, "indic"), # Cham
149
+ (0xAA7F, "khmer_myanmar"), # Myanmar Extended-A
150
+ (0xAADF, "indic"), # Tai Viet
151
+ (0xAAFF, "indic"), # Meetei Mayek Extensions
152
+ (0xAB2F, "ethiopic"), # Ethiopic Extended-A
153
+ (0xAB6F, "latin"), # Latin Extended-E
154
+ (0xABBF, "default"), # Cherokee Supplement
155
+ (0xABFF, "indic"), # Meetei Mayek
156
+ (0xD7AF, "hangul"), # Hangul Syllables
157
+ (0xFAFF, "cjk"), # CJK Compatibility
158
+ (0xFDFF, "arabic"), # Arabic Presentation Forms-A
159
+ (0xFE6F, "default"), # Variation Selectors
160
+ (0xFEFF, "arabic"), # Arabic Presentation Forms-B
161
+ (0xFFEF, "latin"), # Fullwidth Latin
162
+ ]
163
+ self.breakpoints = [r[0] for r in self.ranges]
164
+
165
+ @lru_cache(maxsize=4096)
166
+ def _get_char_weight(self, char):
167
+ """Determines the weight of a single character."""
168
+ code = ord(char)
169
+ if (65 <= code <= 90) or (97 <= code <= 122):
170
+ return self.weights["latin"]
171
+ if code == 32:
172
+ return self.weights["space"]
173
+
174
+ # Ignore arabic Tatweel
175
+ if code == 0x0640:
176
+ return self.weights["mark"]
177
+
178
+ category = unicodedata.category(char)
179
+
180
+ if category.startswith("M"):
181
+ return self.weights["mark"]
182
+
183
+ if category.startswith("P") or category.startswith("S"):
184
+ return self.weights["punctuation"]
185
+
186
+ if category.startswith("Z"):
187
+ return self.weights["space"]
188
+
189
+ if category.startswith("N"):
190
+ return self.weights["digit"]
191
+
192
+ # 3. Binary search for Unicode Block (此时区间里绝不会再混进标点符号)
193
+ idx = bisect.bisect_left(self.breakpoints, code)
194
+ if idx < len(self.ranges):
195
+ script_type = self.ranges[idx][1]
196
+ return self.weights.get(script_type, self.weights["default"])
197
+
198
+ # 4. Handle upper planes (CJK Ext B/C/D, Historic scripts)
199
+ if code > 0x20000:
200
+ return self.weights["cjk"]
201
+
202
+ return self.weights["default"]
203
+
204
+ def calculate_total_weight(self, text):
205
+ """Sums up the normalized weights for a string."""
206
+ return sum(self._get_char_weight(c) for c in text)
207
+
208
+ def estimate_duration(
209
+ self,
210
+ target_text: str,
211
+ ref_text: str,
212
+ ref_duration: float,
213
+ low_threshold: Optional[float] = 50,
214
+ boost_strength: float = 3,
215
+ ) -> float:
216
+ """
217
+
218
+ Args:
219
+ target_text (str): The text for which we want to estimate the duration.
220
+ ref_text (str): The reference text that was used to measure
221
+ the ref_duration.
222
+ ref_duration (float): The actual duration it took
223
+ to speak the ref_text.
224
+ low_threshold (float): The minimum duration threshold below which the
225
+ estimation will be considered unreliable.
226
+ boost_strength (float): Controls the power-curve boost for short durations.
227
+ Higher values boost small durations more aggressively.
228
+ 1 = no boost (linear), 2 = sqrt-like
229
+
230
+ Returns:
231
+ float: The estimated duration for the target_text based
232
+ on the ref_text and ref_duration.
233
+ """
234
+ if ref_duration <= 0 or not ref_text:
235
+ return 0.0
236
+
237
+ ref_weight = self.calculate_total_weight(ref_text)
238
+ if ref_weight == 0:
239
+ return 0.0
240
+
241
+ speed_factor = ref_weight / ref_duration
242
+ target_weight = self.calculate_total_weight(target_text)
243
+
244
+ estimated_duration = target_weight / speed_factor
245
+ if low_threshold is not None and estimated_duration < low_threshold:
246
+ alpha = 1.0 / boost_strength
247
+ return low_threshold * (estimated_duration / low_threshold) ** alpha
248
+ else:
249
+ return estimated_duration
250
+
251
+
252
+ # ==========================================
253
+ # Example Usage
254
+ # ==========================================
255
+ if __name__ == "__main__":
256
+ estimator = RuleDurationEstimator()
257
+
258
+ ref_txt = "Hello, world."
259
+ ref_dur = 1.5
260
+
261
+ test_cases = [
262
+ ("Hindi (With complex marks)", "नमस्ते दुनिया"),
263
+ ("Arabic (With vowels)", "مَرْحَبًا بِالْعَالَم"),
264
+ ("Vietnamese (Lots of diacritics)", "Chào thế giới"),
265
+ ("Chinese", "你好,世界!"),
266
+ ("Mixed Emoji", "Hello 🌍! This is fun 🎉"),
267
+ ]
268
+
269
+ print("--- Reference ---")
270
+ print(f"Reference Text: '{ref_txt}'")
271
+ print(f"Reference Duration: {ref_dur}s")
272
+ print("-" * 30)
273
+
274
+ for lang, txt in test_cases:
275
+ est_time = estimator.estimate_duration(txt, ref_txt, ref_dur)
276
+ weight = estimator.calculate_total_weight(txt)
277
+
278
+ print(f"[{lang}]")
279
+ print(f"Text: {txt}")
280
+ print(f"Total Weight: {weight:.2f}")
281
+ print(f"Estimated Duration: {est_time:.2f} s")
282
+ print("-" * 30)
omnivoice/utils/lang_map.py ADDED
@@ -0,0 +1,698 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Language name to ISO 639-3 code mapping.
19
+
20
+ Auto-generated from ``docs/lang_id_name_map.tsv``. Provides ``LANG_NAME_TO_ID``
21
+ (for resolving language names to codes) and ``LANG_IDS`` (the set of supported
22
+ ISO 639-3 codes). Used by ``OmniVoice.generate()`` to resolve user-provided
23
+ language names.
24
+ """
25
+
26
+ # Auto-generated from docs/lang_id_name_map.tsv
27
+ # Maps lowercase language name -> language ID code
28
+
29
+ LANG_NAME_TO_ID = {
30
+ "abadi": "kbt",
31
+ "abkhazian": "ab",
32
+ "abron": "abr",
33
+ "abua": "abn",
34
+ "adamawa fulfulde": "fub",
35
+ "adyghe": "ady",
36
+ "afade": "aal",
37
+ "afrikaans": "af",
38
+ "agwagwune": "yay",
39
+ "aja (benin)": "ajg",
40
+ "akebu": "keu",
41
+ "alago": "ala",
42
+ "albanian": "sq",
43
+ "algerian arabic": "arq",
44
+ "algerian saharan arabic": "aao",
45
+ "ambo-pasco quechua": "qva",
46
+ "ambonese malay": "abs",
47
+ "amdo tibetan": "adx",
48
+ "amharic": "am",
49
+ "anaang": "anw",
50
+ "angika": "anp",
51
+ "antankarana malagasy": "xmv",
52
+ "aragonese": "an",
53
+ "arbëreshë albanian": "aae",
54
+ "arequipa-la unión quechua": "qxu",
55
+ "armenian": "hy",
56
+ "ashe": "ahs",
57
+ "ashéninka perené": "prq",
58
+ "askopan": "eiv",
59
+ "assamese": "as",
60
+ "asturian": "ast",
61
+ "atayal": "tay",
62
+ "awak": "awo",
63
+ "ayacucho quechua": "quy",
64
+ "azerbaijani": "az",
65
+ "baatonum": "bba",
66
+ "bacama": "bcy",
67
+ "bade": "bde",
68
+ "bafia": "ksf",
69
+ "bafut": "bfd",
70
+ "bagirmi fulfulde": "fui",
71
+ "bago-kusuntu": "bqg",
72
+ "baharna arabic": "abv",
73
+ "bakoko": "bkh",
74
+ "balanta-ganja": "bjt",
75
+ "balti": "bft",
76
+ "bamenyam": "bce",
77
+ "bamun": "bax",
78
+ "bangwinji": "bsj",
79
+ "banjar": "bjn",
80
+ "bankon": "abb",
81
+ "baoulé": "bci",
82
+ "bara malagasy": "bhr",
83
+ "barok": "bjk",
84
+ "basa (cameroon)": "bas",
85
+ "basa (nigeria)": "bzw",
86
+ "bashkir": "ba",
87
+ "basque": "eu",
88
+ "batak mandailing": "btm",
89
+ "batanga": "bnm",
90
+ "bateri": "btv",
91
+ "bats": "bbl",
92
+ "bayot": "bda",
93
+ "bebele": "beb",
94
+ "belarusian": "be",
95
+ "bengali": "bn",
96
+ "betawi": "bew",
97
+ "bhili": "bhb",
98
+ "bhojpuri": "bho",
99
+ "bilur": "bxf",
100
+ "bima": "bhp",
101
+ "bodo": "brx",
102
+ "boghom": "bux",
103
+ "bokyi": "bky",
104
+ "bomu": "bmq",
105
+ "bondei": "bou",
106
+ "borgu fulfulde": "fue",
107
+ "bosnian": "bs",
108
+ "brahui": "brh",
109
+ "braj": "bra",
110
+ "breton": "br",
111
+ "buduma": "bdm",
112
+ "buginese": "bug",
113
+ "bukharic": "bhh",
114
+ "bulgarian": "bg",
115
+ "bulu (cameroon)": "bum",
116
+ "bundeli": "bns",
117
+ "bunun": "bnn",
118
+ "bura-pabir": "bwr",
119
+ "burak": "bys",
120
+ "burmese": "my",
121
+ "burushaski": "bsk",
122
+ "cacaloxtepec mixtec": "miu",
123
+ "cajatambo north lima quechua": "qvl",
124
+ "cakfem-mushere": "cky",
125
+ "cameroon pidgin": "wes",
126
+ "campidanese sardinian": "sro",
127
+ "cantonese": "yue",
128
+ "catalan": "ca",
129
+ "cebuano": "ceb",
130
+ "cen": "cen",
131
+ "central kurdish": "ckb",
132
+ "central nahuatl": "nhn",
133
+ "central pame": "pbs",
134
+ "central pashto": "pst",
135
+ "central puebla nahuatl": "ncx",
136
+ "central tarahumara": "tar",
137
+ "central yupik": "esu",
138
+ "central-eastern niger fulfulde": "fuq",
139
+ "chadian arabic": "shu",
140
+ "chichewa": "ny",
141
+ "chichicapan zapotec": "zpv",
142
+ "chiga": "cgg",
143
+ "chimalapa zoque": "zoh",
144
+ "chimborazo highland quichua": "qug",
145
+ "chinese": "zh",
146
+ "chiquián ancash quechua": "qxa",
147
+ "chitwania tharu": "the",
148
+ "chokwe": "cjk",
149
+ "chuvash": "cv",
150
+ "cibak": "ckl",
151
+ "coastal konjo": "kjc",
152
+ "copainalá zoque": "zoc",
153
+ "cornish": "kw",
154
+ "corongo ancash quechua": "qwa",
155
+ "croatian": "hr",
156
+ "cross river mbembe": "mfn",
157
+ "cuyamecalco mixtec": "xtu",
158
+ "czech": "cs",
159
+ "dadiya": "dbd",
160
+ "dagbani": "dag",
161
+ "dameli": "dml",
162
+ "danish": "da",
163
+ "dargwa": "dar",
164
+ "dazaga": "dzg",
165
+ "deccan": "dcc",
166
+ "degema": "deg",
167
+ "dera (nigeria)": "kna",
168
+ "dghwede": "dgh",
169
+ "dhatki": "mki",
170
+ "dhivehi": "dv",
171
+ "dhofari arabic": "adf",
172
+ "dijim-bwilim": "cfa",
173
+ "dogri": "dgo",
174
+ "domaaki": "dmk",
175
+ "dotyali": "dty",
176
+ "duala": "dua",
177
+ "dutch": "nl",
178
+ "dũya": "ldb",
179
+ "dyula": "dyu",
180
+ "eastern balochi": "bgp",
181
+ "eastern bolivian guaraní": "gui",
182
+ "eastern egyptian bedawi arabic": "avl",
183
+ "eastern krahn": "kqo",
184
+ "eastern mari": "mhr",
185
+ "eastern yiddish": "ydd",
186
+ "ebrié": "ebr",
187
+ "eggon": "ego",
188
+ "egyptian arabic": "arz",
189
+ "ejagham": "etu",
190
+ "eleme": "elm",
191
+ "eloyi": "afo",
192
+ "embu": "ebu",
193
+ "english": "en",
194
+ "erzya": "myv",
195
+ "esan": "ish",
196
+ "esperanto": "eo",
197
+ "estonian": "et",
198
+ "eton (cameroon)": "eto",
199
+ "ewondo": "ewo",
200
+ "extremaduran": "ext",
201
+ "fang (equatorial guinea)": "fan",
202
+ "fanti": "fat",
203
+ "farefare": "gur",
204
+ "fe'fe'": "fmp",
205
+ "filipino": "fil",
206
+ "filomena mata-coahuitlán totonac": "tlp",
207
+ "finnish": "fi",
208
+ "fipa": "fip",
209
+ "french": "fr",
210
+ "fulah": "ff",
211
+ "galician": "gl",
212
+ "gambian wolof": "wof",
213
+ "ganda": "lg",
214
+ "garhwali": "gbm",
215
+ "gawar-bati": "gwt",
216
+ "gawri": "gwc",
217
+ "gbagyi": "gbr",
218
+ "gbari": "gby",
219
+ "geji": "gyz",
220
+ "gen": "gej",
221
+ "georgian": "ka",
222
+ "german": "de",
223
+ "geser-gorom": "ges",
224
+ "gheg albanian": "aln",
225
+ "ghomálá'": "bbj",
226
+ "gidar": "gid",
227
+ "glavda": "glw",
228
+ "goan konkani": "gom",
229
+ "goaria": "gig",
230
+ "goemai": "ank",
231
+ "gola": "gol",
232
+ "greek": "el",
233
+ "guarani": "gn",
234
+ "guduf-gava": "gdf",
235
+ "guerrero amuzgo": "amu",
236
+ "gujarati": "gu",
237
+ "gujari": "gju",
238
+ "gulf arabic": "afb",
239
+ "gurgula": "ggg",
240
+ "gusii": "guz",
241
+ "gusilay": "gsl",
242
+ "gweno": "gwe",
243
+ "güilá zapotec": "ztu",
244
+ "hadothi": "hoj",
245
+ "hahon": "hah",
246
+ "haitian": "ht",
247
+ "hakha chin": "cnh",
248
+ "hakö": "hao",
249
+ "halia": "hla",
250
+ "hausa": "ha",
251
+ "hawaiian": "haw",
252
+ "hazaragi": "haz",
253
+ "hebrew": "he",
254
+ "hemba": "hem",
255
+ "herero": "hz",
256
+ "highland konjo": "kjk",
257
+ "hijazi arabic": "acw",
258
+ "hindi": "hi",
259
+ "huarijio": "var",
260
+ "huautla mazatec": "mau",
261
+ "huaxcaleca nahuatl": "nhq",
262
+ "huba": "hbb",
263
+ "huitepec mixtec": "mxs",
264
+ "hula": "hul",
265
+ "hungarian": "hu",
266
+ "hunjara-kaina ke": "hkk",
267
+ "hwana": "hwo",
268
+ "ibibio": "ibb",
269
+ "icelandic": "is",
270
+ "idakho-isukha-tiriki": "ida",
271
+ "idoma": "idu",
272
+ "igbo": "ig",
273
+ "igo": "ahl",
274
+ "ikposo": "kpo",
275
+ "ikwere": "ikw",
276
+ "imbabura highland quichua": "qvi",
277
+ "indonesian": "id",
278
+ "indus kohistani": "mvy",
279
+ "interlingua (international auxiliary language association)": "ia",
280
+ "inupiaq": "ik",
281
+ "irish": "ga",
282
+ "iron ossetic": "os",
283
+ "isekiri": "its",
284
+ "isoko": "iso",
285
+ "italian": "it",
286
+ "ito": "itw",
287
+ "itzá": "itz",
288
+ "ixtayutla mixtec": "vmj",
289
+ "izon": "ijc",
290
+ "jambi malay": "jax",
291
+ "japanese": "ja",
292
+ "jaqaru": "jqr",
293
+ "jauja wanca quechua": "qxw",
294
+ "jaunsari": "jns",
295
+ "javanese": "jv",
296
+ "jiba": "juo",
297
+ "jju": "kaj",
298
+ "judeo-moroccan arabic": "aju",
299
+ "juxtlahuaca mixtec": "vmc",
300
+ "kabardian": "kbd",
301
+ "kabras": "lkb",
302
+ "kabuverdianu": "kea",
303
+ "kabyle": "kab",
304
+ "kachi koli": "gjk",
305
+ "kairak": "ckr",
306
+ "kalabari": "ijn",
307
+ "kalasha": "kls",
308
+ "kalenjin": "kln",
309
+ "kalkoti": "xka",
310
+ "kamba": "kam",
311
+ "kamo": "kcq",
312
+ "kanauji": "bjj",
313
+ "kanembu": "kbl",
314
+ "kannada": "kn",
315
+ "karekare": "kai",
316
+ "kashmiri": "ks",
317
+ "kathoriya tharu": "tkt",
318
+ "kati": "bsh",
319
+ "kazakh": "kk",
320
+ "keiyo": "eyo",
321
+ "khams tibetan": "khg",
322
+ "khana": "ogo",
323
+ "khetrani": "xhe",
324
+ "khmer": "km",
325
+ "khowar": "khw",
326
+ "kinga": "zga",
327
+ "kinnauri": "kfk",
328
+ "kinyarwanda": "rw",
329
+ "kirghiz": "ky",
330
+ "kirya-konzəl": "fkk",
331
+ "kochila tharu": "thq",
332
+ "kohistani shina": "plk",
333
+ "kohumono": "bcs",
334
+ "kok borok": "trp",
335
+ "kol (papua new guinea)": "kol",
336
+ "kom (cameroon)": "bkm",
337
+ "koma": "kmy",
338
+ "konkani": "knn",
339
+ "konzo": "koo",
340
+ "korean": "ko",
341
+ "korwa": "kfp",
342
+ "kota (india)": "kfe",
343
+ "koti": "eko",
344
+ "kuanua": "ksd",
345
+ "kuanyama": "kj",
346
+ "kui (india)": "uki",
347
+ "kulung (nigeria)": "bbu",
348
+ "kuot": "kto",
349
+ "kushi": "kuh",
350
+ "kwambi": "kwm",
351
+ "kwasio": "nmg",
352
+ "lala-roba": "lla",
353
+ "lamang": "hia",
354
+ "lao": "lo",
355
+ "larike-wakasihu": "alo",
356
+ "lasi": "lss",
357
+ "latgalian": "ltg",
358
+ "latvian": "lv",
359
+ "levantine arabic": "apc",
360
+ "liana-seti": "ste",
361
+ "liberia kpelle": "xpe",
362
+ "liberian english": "lir",
363
+ "libyan arabic": "ayl",
364
+ "ligurian": "lij",
365
+ "lijili": "mgi",
366
+ "lingala": "ln",
367
+ "lithuanian": "lt",
368
+ "loarki": "lrk",
369
+ "logooli": "rag",
370
+ "logudorese sardinian": "src",
371
+ "loja highland quichua": "qvj",
372
+ "loloda": "loa",
373
+ "longuda": "lnu",
374
+ "loxicha zapotec": "ztp",
375
+ "luba-lulua": "lua",
376
+ "luo": "luo",
377
+ "lushai": "lus",
378
+ "luxembourgish": "lb",
379
+ "maasina fulfulde": "ffm",
380
+ "maba (chad)": "mde",
381
+ "macedo-romanian": "rup",
382
+ "macedonian": "mk",
383
+ "mada (cameroon)": "mxu",
384
+ "mafa": "maf",
385
+ "maithili": "mai",
386
+ "malay": "ms",
387
+ "malayalam": "ml",
388
+ "mali": "gcc",
389
+ "malinaltepec me'phaa": "tcf",
390
+ "maltese": "mt",
391
+ "mandara": "tbf",
392
+ "mandjak": "mfv",
393
+ "manggarai": "mqy",
394
+ "manipuri": "mni",
395
+ "mansoanka": "msw",
396
+ "manx": "gv",
397
+ "maori": "mi",
398
+ "marathi": "mr",
399
+ "marghi central": "mrt",
400
+ "marghi south": "mfm",
401
+ "maria (india)": "mrr",
402
+ "marwari (pakistan)": "mve",
403
+ "masana": "mcn",
404
+ "masikoro malagasy": "msh",
405
+ "matsés": "mcf",
406
+ "mazaltepec zapotec": "zpy",
407
+ "mazatlán mazatec": "vmz",
408
+ "mazatlán mixe": "mzl",
409
+ "mbe": "mfo",
410
+ "mbo (cameroon)": "mbo",
411
+ "mbum": "mdd",
412
+ "medumba": "byv",
413
+ "mekeo": "mek",
414
+ "meru": "mer",
415
+ "mesopotamian arabic": "acm",
416
+ "mewari": "mtr",
417
+ "min nan chinese": "nan",
418
+ "mingrelian": "xmf",
419
+ "mitlatongo mixtec": "vmm",
420
+ "miya": "mkf",
421
+ "mokpwe": "bri",
422
+ "moksha": "mdf",
423
+ "mom jango": "ver",
424
+ "mongolian": "mn",
425
+ "moroccan arabic": "ary",
426
+ "motu": "meu",
427
+ "mpiemo": "mcx",
428
+ "mpumpong": "mgg",
429
+ "mundang": "mua",
430
+ "mungaka": "mhk",
431
+ "musey": "mse",
432
+ "musgu": "mug",
433
+ "musi": "mui",
434
+ "naba": "mne",
435
+ "najdi arabic": "ars",
436
+ "nalik": "nal",
437
+ "nawdm": "nmz",
438
+ "ndonga": "ng",
439
+ "neapolitan": "nap",
440
+ "nepali": "npi",
441
+ "ngamo": "nbh",
442
+ "ngas": "anc",
443
+ "ngiemboon": "nnh",
444
+ "ngizim": "ngi",
445
+ "ngomba": "jgo",
446
+ "ngombale": "nla",
447
+ "nigerian fulfulde": "fuv",
448
+ "nigerian pidgin": "pcm",
449
+ "nimadi": "noe",
450
+ "nobiin": "fia",
451
+ "north mesopotamian arabic": "ayp",
452
+ "north moluccan malay": "max",
453
+ "northern betsimisaraka malagasy": "bmm",
454
+ "northern hindko": "hno",
455
+ "northern kurdish": "kmr",
456
+ "northern pame": "pmq",
457
+ "northern pashto": "pbu",
458
+ "northern uzbek": "uzn",
459
+ "northwest gbaya": "gya",
460
+ "norwegian": "no",
461
+ "norwegian bokmål": "nb",
462
+ "norwegian nynorsk": "nn",
463
+ "notsi": "ncf",
464
+ "nyankpa": "yes",
465
+ "nyungwe": "nyu",
466
+ "nzanyi": "nja",
467
+ "nüpode huitoto": "hux",
468
+ "occitan": "oc",
469
+ "od": "odk",
470
+ "odia": "ory",
471
+ "odual": "odu",
472
+ "omani arabic": "acx",
473
+ "orizaba nahuatl": "nlv",
474
+ "orma": "orc",
475
+ "ormuri": "oru",
476
+ "oromo": "om",
477
+ "pahari-potwari": "phr",
478
+ "paiwan": "pwn",
479
+ "panjabi": "pa",
480
+ "papuan malay": "pmy",
481
+ "parkari koli": "kvx",
482
+ "pedi": "nso",
483
+ "pero": "pip",
484
+ "persian": "fa",
485
+ "petats": "pex",
486
+ "phalura": "phl",
487
+ "piemontese": "pms",
488
+ "piya-kwonci": "piy",
489
+ "plateau malagasy": "plt",
490
+ "polish": "pl",
491
+ "poqomam": "poc",
492
+ "portuguese": "pt",
493
+ "pulaar": "fuc",
494
+ "pular": "fuf",
495
+ "puno quechua": "qxp",
496
+ "pushto": "ps",
497
+ "pökoot": "pko",
498
+ "qaqet": "byx",
499
+ "quiotepec chinantec": "chq",
500
+ "rana tharu": "thr",
501
+ "rangi": "lag",
502
+ "rapoisi": "kyx",
503
+ "ratahan": "rth",
504
+ "rayón zoque": "zor",
505
+ "romanian": "ro",
506
+ "romansh": "rm",
507
+ "rombo": "rof",
508
+ "rotokas": "roo",
509
+ "rukai": "dru",
510
+ "russian": "ru",
511
+ "sacapulteco": "quv",
512
+ "saidi arabic": "aec",
513
+ "sakalava malagasy": "skg",
514
+ "sakizaya": "szy",
515
+ "saleman": "sau",
516
+ "samba daka": "ccg",
517
+ "samba leko": "ndi",
518
+ "san felipe otlaltepec popoloca": "pow",
519
+ "san francisco del mar huave": "hue",
520
+ "san juan atzingo popoloca": "poe",
521
+ "san martín itunyoso triqui": "trq",
522
+ "san miguel el grande mixtec": "mig",
523
+ "sansi": "ssi",
524
+ "sanskrit": "sa",
525
+ "santa ana de tusi pasco quechua": "qxt",
526
+ "santa catarina albarradas zapotec": "ztn",
527
+ "santali": "sat",
528
+ "santiago del estero quichua": "qus",
529
+ "saposa": "sps",
530
+ "saraiki": "skr",
531
+ "sardinian": "sc",
532
+ "saya": "say",
533
+ "sediq": "trv",
534
+ "serbian": "sr",
535
+ "seri": "sei",
536
+ "shina": "scl",
537
+ "shona": "sn",
538
+ "siar-lak": "sjr",
539
+ "sibe": "nco",
540
+ "sicilian": "scn",
541
+ "sihuas ancash quechua": "qws",
542
+ "sikkimese": "sip",
543
+ "sinaugoro": "snc",
544
+ "sindhi": "sd",
545
+ "sindhi bhil": "sbn",
546
+ "sinhala": "si",
547
+ "sinicahua mixtec": "xti",
548
+ "sipacapense": "qum",
549
+ "siwai": "siw",
550
+ "slovak": "sk",
551
+ "slovenian": "sl",
552
+ "solos": "sol",
553
+ "somali": "so",
554
+ "soninke": "snk",
555
+ "south giziga": "giz",
556
+ "south ucayali ashéninka": "cpy",
557
+ "southeastern nochixtlán mixtec": "mxy",
558
+ "southern betsimisaraka malagasy": "bzc",
559
+ "southern pashto": "pbt",
560
+ "southern pastaza quechua": "qup",
561
+ "soyaltepec mazatec": "vmp",
562
+ "spanish": "es",
563
+ "standard arabic": "arb",
564
+ "standard moroccan tamazight": "zgh",
565
+ "sudanese arabic": "apd",
566
+ "sulka": "sua",
567
+ "svan": "sva",
568
+ "swahili": "sw",
569
+ "swedish": "sv",
570
+ "tae'": "rob",
571
+ "tahaggart tamahaq": "thv",
572
+ "taita": "dav",
573
+ "tajik": "tg",
574
+ "tamil": "ta",
575
+ "tandroy-mahafaly malagasy": "tdx",
576
+ "tangale": "tan",
577
+ "tanosy malagasy": "txy",
578
+ "tarok": "yer",
579
+ "tatar": "tt",
580
+ "tedaga": "tuq",
581
+ "telugu": "te",
582
+ "tem": "kdh",
583
+ "teop": "tio",
584
+ "tepeuxila cuicatec": "cux",
585
+ "tepinapa chinantec": "cte",
586
+ "tera": "ttr",
587
+ "terei": "buo",
588
+ "termanu": "twu",
589
+ "tesaka malagasy": "tkg",
590
+ "tetelcingo nahuatl": "nhg",
591
+ "teutila cuicatec": "cut",
592
+ "thai": "th",
593
+ "tibetan": "bo",
594
+ "tidaá mixtec": "mtx",
595
+ "tidore": "tvo",
596
+ "tigak": "tgc",
597
+ "tigre": "tig",
598
+ "tigrinya": "ti",
599
+ "tilquiapan zapotec": "zts",
600
+ "tinputz": "tpz",
601
+ "tlacoapa me'phaa": "tpl",
602
+ "tlacoatzintepec chinantec": "ctl",
603
+ "tlingit": "tli",
604
+ "toki pona": "tok",
605
+ "tomoip": "tqp",
606
+ "tondano": "tdn",
607
+ "tonsea": "txs",
608
+ "tooro": "ttj",
609
+ "torau": "ttu",
610
+ "torwali": "trw",
611
+ "tsimihety malagasy": "xmw",
612
+ "tsotso": "lto",
613
+ "tswana": "tn",
614
+ "tugen": "tuy",
615
+ "tuki": "bag",
616
+ "tula": "tul",
617
+ "tulu": "tcy",
618
+ "tunen": "tvu",
619
+ "tungag": "lcm",
620
+ "tunisian arabic": "aeb",
621
+ "tupuri": "tui",
622
+ "turkana": "tuv",
623
+ "turkish": "tr",
624
+ "turkmen": "tk",
625
+ "tututepec mixtec": "mtu",
626
+ "twi": "tw",
627
+ "ubaghara": "byc",
628
+ "uighur": "ug",
629
+ "ukrainian": "uk",
630
+ "umbundu": "umb",
631
+ "upper sorbian": "hsb",
632
+ "urdu": "ur",
633
+ "ushojo": "ush",
634
+ "uzbek": "uz",
635
+ "vai": "vai",
636
+ "vietnamese": "vi",
637
+ "votic": "vot",
638
+ "võro": "vro",
639
+ "waci gbe": "wci",
640
+ "wadiyara koli": "kxp",
641
+ "waja": "wja",
642
+ "wakhi": "wbl",
643
+ "wanga": "lwg",
644
+ "wapan": "juk",
645
+ "warji": "wji",
646
+ "welsh": "cy",
647
+ "wemale": "weo",
648
+ "western frisian": "fy",
649
+ "western highland purepecha": "pua",
650
+ "western juxtlahuaca mixtec": "jmx",
651
+ "western maninkakan": "mlq",
652
+ "western mari": "mrj",
653
+ "western niger fulfulde": "fuh",
654
+ "western panjabi": "pnb",
655
+ "wolof": "wo",
656
+ "wuzlam": "udl",
657
+ "xanaguía zapotec": "ztg",
658
+ "xhosa": "xh",
659
+ "yace": "ekr",
660
+ "yakut": "sah",
661
+ "yalahatan": "jal",
662
+ "yanahuanca pasco quechua": "qur",
663
+ "yangben": "yav",
664
+ "yaqui": "yaq",
665
+ "yauyos quechua": "qux",
666
+ "yekhee": "ets",
667
+ "yiddish": "yi",
668
+ "yidgha": "ydg",
669
+ "yoruba": "yo",
670
+ "yutanduchi mixtec": "mab",
671
+ "zacatlán-ahuacatlán-tepetzintla nahuatl": "nhi",
672
+ "zarma": "dje",
673
+ "zaza": "zza",
674
+ "zulu": "zu",
675
+ "ömie": "aom",
676
+ }
677
+
678
+ LANG_NAMES = set(LANG_NAME_TO_ID.keys())
679
+ LANG_IDS = set(LANG_NAME_TO_ID.values())
680
+
681
+ # Exceptions where .title() doesn't match the canonical casing from the TSV.
682
+ _TITLE_EXCEPTIONS = {
683
+ "fe'fe'": "Fe'fe'",
684
+ "dũya": "Dũya",
685
+ "santiago del estero quichua": "Santiago del Estero Quichua",
686
+ "santa ana de tusi pasco quechua": "Santa Ana de Tusi Pasco Quechua",
687
+ "malinaltepec me'phaa": "Malinaltepec Me'phaa",
688
+ "tlacoapa me'phaa": "Tlacoapa Me'phaa",
689
+ }
690
+
691
+
692
+ def lang_display_name(name: str) -> str:
693
+ """Return a display-friendly version of a lowercase language name.
694
+
695
+ Uses .title() for most names, with manual exceptions for cases like
696
+ apostrophes and small words (de, del) that should stay lowercase.
697
+ """
698
+ return _TITLE_EXCEPTIONS.get(name, name.title())
omnivoice/utils/text.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Text processing utilities for TTS inference.
19
+
20
+ Provides:
21
+ - ``chunk_text_punctuation()``: Splits long text into model-friendly chunks at
22
+ sentence boundaries, with abbreviation-aware punctuation splitting.
23
+ - ``add_punctuation()``: Appends missing end punctuation (Chinese or English).
24
+ """
25
+
26
+ from typing import List, Optional
27
+
28
+
29
+ SPLIT_PUNCTUATION = set(".,;:!?。,;:!?")
30
+ CLOSING_MARKS = set("\"'""')]》》>」】")
31
+
32
+ END_PUNCTUATION = {
33
+ ";",
34
+ ":",
35
+ ",",
36
+ ".",
37
+ "!",
38
+ "?",
39
+ "…",
40
+ ")",
41
+ "]",
42
+ "}",
43
+ '"',
44
+ "'",
45
+ """,
46
+ "'",
47
+ ";",
48
+ ":",
49
+ ",",
50
+ "。",
51
+ "!",
52
+ "?",
53
+ "、",
54
+ "……",
55
+ ")",
56
+ "】",
57
+ """,
58
+ "'",
59
+ }
60
+
61
+
62
+ ABBREVIATIONS = {
63
+ "Mr.",
64
+ "Mrs.",
65
+ "Ms.",
66
+ "Dr.",
67
+ "Prof.",
68
+ "Sr.",
69
+ "Jr.",
70
+ "Rev.",
71
+ "Fr.",
72
+ "Hon.",
73
+ "Pres.",
74
+ "Gov.",
75
+ "Capt.",
76
+ "Gen.",
77
+ "Sen.",
78
+ "Rep.",
79
+ "Col.",
80
+ "Maj.",
81
+ "Lt.",
82
+ "Cmdr.",
83
+ "Sgt.",
84
+ "Cpl.",
85
+ "Co.",
86
+ "Corp.",
87
+ "Inc.",
88
+ "Ltd.",
89
+ "Est.",
90
+ "Dept.",
91
+ "St.",
92
+ "Ave.",
93
+ "Blvd.",
94
+ "Rd.",
95
+ "Mt.",
96
+ "Ft.",
97
+ "No.",
98
+ "Jan.",
99
+ "Feb.",
100
+ "Mar.",
101
+ "Apr.",
102
+ "Aug.",
103
+ "Sep.",
104
+ "Sept.",
105
+ "Oct.",
106
+ "Nov.",
107
+ "Dec.",
108
+ "i.e.",
109
+ "e.g.",
110
+ "vs.",
111
+ "Vs.",
112
+ "Etc.",
113
+ "approx.",
114
+ "fig.",
115
+ "def.",
116
+ }
117
+
118
+
119
+ def chunk_text_punctuation(
120
+ text: str,
121
+ chunk_len: int,
122
+ min_chunk_len: Optional[int] = None,
123
+ ) -> List[str]:
124
+ """
125
+ Splits the input tokens list into chunks according to punctuations,
126
+ avoiding splits on common abbreviations (e.g., Mr., No.).
127
+ """
128
+
129
+ # 1. Split the tokens according to punctuations.
130
+ sentences = []
131
+ current_sentence = []
132
+
133
+ tokens_list = list(text)
134
+
135
+ for token in tokens_list:
136
+ # If the first token of current sentence is punctuation,
137
+ # append it to the end of the previous sentence.
138
+ if (
139
+ len(current_sentence) == 0
140
+ and len(sentences) != 0
141
+ and (token in SPLIT_PUNCTUATION or token in CLOSING_MARKS)
142
+ ):
143
+ sentences[-1].append(token)
144
+ # Otherwise, append the current token to the current sentence.
145
+ else:
146
+ current_sentence.append(token)
147
+
148
+ # Split the sentence in positions of punctuations.
149
+ if token in SPLIT_PUNCTUATION:
150
+ is_abbreviation = False
151
+
152
+ if token == ".":
153
+ temp_str = "".join(current_sentence).strip()
154
+ if temp_str:
155
+ last_word = temp_str.split()[-1]
156
+ if last_word in ABBREVIATIONS:
157
+ is_abbreviation = True
158
+
159
+ if not is_abbreviation:
160
+ sentences.append(current_sentence)
161
+ current_sentence = []
162
+ # Assume the last few tokens are also a sentence
163
+ if len(current_sentence) != 0:
164
+ sentences.append(current_sentence)
165
+
166
+ # 2. Merge short sentences.
167
+ merged_chunks = []
168
+ current_chunk = []
169
+ for sentence in sentences:
170
+ if len(current_chunk) + len(sentence) <= chunk_len:
171
+ current_chunk.extend(sentence)
172
+ else:
173
+ if len(current_chunk) > 0:
174
+ merged_chunks.append(current_chunk)
175
+ current_chunk = sentence
176
+
177
+ if len(current_chunk) > 0:
178
+ merged_chunks.append(current_chunk)
179
+
180
+ # 4. Post-process: Check for undersized chunks and merge them
181
+ # with the previous chunk or next chunk (if it's the first chunk).
182
+ if min_chunk_len is not None:
183
+ first_chunk_short_flag = (
184
+ len(merged_chunks) > 0 and len(merged_chunks[0]) < min_chunk_len
185
+ )
186
+ final_chunks = []
187
+ for i, chunk in enumerate(merged_chunks):
188
+ if i == 1 and first_chunk_short_flag:
189
+ final_chunks[-1].extend(chunk)
190
+ else:
191
+ if len(chunk) >= min_chunk_len:
192
+ final_chunks.append(chunk)
193
+ else:
194
+ if len(final_chunks) == 0:
195
+ final_chunks.append(chunk)
196
+ else:
197
+ final_chunks[-1].extend(chunk)
198
+ else:
199
+ final_chunks = merged_chunks
200
+
201
+ chunk_strings = [
202
+ "".join(chunk).strip() for chunk in final_chunks if "".join(chunk).strip()
203
+ ]
204
+ return chunk_strings
205
+
206
+
207
+ def add_punctuation(text: str):
208
+ """Add punctuation if there is not in the end of text"""
209
+ text = text.strip()
210
+
211
+ if not text:
212
+ return text
213
+
214
+ if text[-1] not in END_PUNCTUATION:
215
+ is_chinese = any("\u4e00" <= char <= "\u9fff" for char in text)
216
+
217
+ text += "。" if is_chinese else "."
218
+
219
+ return text
omnivoice/utils/voice_design.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # Copyright 2026 Xiaomi Corp. (authors: Han Zhu)
3
+ #
4
+ # See ../../LICENSE for clarification regarding multiple authors
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+
18
+ """Voice-design instruct constants for TTS inference.
19
+
20
+ Defines speaker attribute tags (gender, age, pitch, accent, dialect) and
21
+ translation/validation utilities between English and Chinese. Used by
22
+ ``OmniVoice.generate()`` for voice design mode.
23
+ """
24
+
25
+ import re
26
+
27
+ _ZH_RE = re.compile(r'[\u4e00-\u9fff]')
28
+
29
+ # Category = set of {english: chinese, ...} items that are mutually exclusive.
30
+ # Accent (EN-only) and dialect (ZH-only) are stored as flat sets below.
31
+ _INSTRUCT_CATEGORIES = [
32
+ {"male": "男", "female": "女"},
33
+ {"child": "儿童", "teenager": "少年", "young adult": "青年",
34
+ "middle-aged": "中年", "elderly": "老年"},
35
+ {"very low pitch": "极低音调", "low pitch": "低音调",
36
+ "moderate pitch": "中音调", "high pitch": "高音调",
37
+ "very high pitch": "极高音调"},
38
+ {"whisper": "耳语"},
39
+ # Accent (English-only, no Chinese counterpart)
40
+ {"american accent", "british accent", "australian accent",
41
+ "chinese accent", "canadian accent", "indian accent",
42
+ "korean accent", "portuguese accent", "russian accent", "japanese accent"},
43
+ # Dialect (Chinese-only, no English counterpart)
44
+ {"河南话", "陕西话", "四川话", "贵州话", "云南话", "桂林话",
45
+ "济南话", "石家庄话", "甘肃话", "宁夏话", "青岛话", "东北话"},
46
+ ]
47
+
48
+ _INSTRUCT_EN_TO_ZH = {}
49
+ _INSTRUCT_ZH_TO_EN = {}
50
+ _INSTRUCT_MUTUALLY_EXCLUSIVE = []
51
+ for _cat in _INSTRUCT_CATEGORIES:
52
+ if isinstance(_cat, dict):
53
+ _INSTRUCT_EN_TO_ZH.update(_cat)
54
+ _INSTRUCT_ZH_TO_EN.update({v: k for k, v in _cat.items()})
55
+ _INSTRUCT_MUTUALLY_EXCLUSIVE.append(set(_cat) | set(_cat.values()))
56
+ else:
57
+ _INSTRUCT_MUTUALLY_EXCLUSIVE.append(set(_cat))
58
+
59
+ _INSTRUCT_ALL_VALID = (
60
+ set(_INSTRUCT_EN_TO_ZH) | set(_INSTRUCT_ZH_TO_EN)
61
+ | _INSTRUCT_MUTUALLY_EXCLUSIVE[-2] # accents
62
+ | _INSTRUCT_MUTUALLY_EXCLUSIVE[-1] # dialects
63
+ )
64
+
65
+ _INSTRUCT_VALID_EN = frozenset(i for i in _INSTRUCT_ALL_VALID if not _ZH_RE.search(i))
66
+ _INSTRUCT_VALID_ZH = frozenset(i for i in _INSTRUCT_ALL_VALID if _ZH_RE.search(i))
sync_data/configs/config.json ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "llm_name_or_path": "Qwen/Qwen3-0.6B",
3
+ "audio_vocab_size": 1025,
4
+ "audio_mask_id": 1024,
5
+ "num_audio_codebook": 8,
6
+
7
+ "audio_codebook_weights": [8, 8, 6, 6, 4, 4, 2, 2],
8
+ "drop_cond_ratio": 0.1,
9
+ "prompt_ratio_range": [0.0, 0.3],
10
+ "mask_ratio_range": [0.0, 1.0],
11
+ "language_ratio": 0.8,
12
+ "use_pinyin_ratio": 0.0,
13
+ "instruct_ratio": 0.0,
14
+ "only_instruct_ratio": 0.0,
15
+
16
+ "resume_from_checkpoint": null,
17
+ "init_from_checkpoint": "oddadmix/lahgtna-omnivoice-v2",
18
+
19
+ "learning_rate": 1e-5,
20
+ "weight_decay": 0.01,
21
+ "max_grad_norm": 1.0,
22
+ "steps": 5000,
23
+ "seed": 42,
24
+ "warmup_type": "ratio",
25
+ "warmup_ratio": 0.01,
26
+ "warmup_steps": 0,
27
+
28
+ "batch_tokens": 4096,
29
+ "gradient_accumulation_steps": 2,
30
+ "num_workers": 3,
31
+
32
+ "mixed_precision": "bf16",
33
+ "allow_tf32": true,
34
+ "attn_implementation": "sdpa",
35
+
36
+ "logging_steps": 50,
37
+ "eval_steps": 500,
38
+ "save_steps": 500,
39
+ "keep_last_n_checkpoints": -1
40
+ }
sync_data/configs/data_saudi.json ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "train": [
3
+ {
4
+ "language_id": "ar",
5
+ "manifest_path": ["/home/riftuser/OmniVoice/sync_data/tokens/train/data.lst"],
6
+ "repeat": 1
7
+ }
8
+ ],
9
+ "dev": [
10
+ {
11
+ "language_id": "ar",
12
+ "manifest_path": ["/home/riftuser/OmniVoice/sync_data/tokens/dev/data.lst"],
13
+ "repeat": 1
14
+ }
15
+ ]
16
+ }
sync_data/data/dev_raw.jsonl ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"id": "sample_000194", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000194.wav", "text": "تحت نور القمر، الشوارع لنا.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
2
+ {"id": "sample_000186", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000186.wav", "text": "قبل السباق، نعطيهم تمر للطاقة.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
3
+ {"id": "sample_000122", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000122.wav", "text": "الحراس جايين! بسرعة، اختبي في الظلام!", "language_id": "ar", "instruct": "saudi, conversational, tense"}
4
+ {"id": "sample_000089", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000089.wav", "text": "شوف! لقيت عملة من زمان!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
5
+ {"id": "sample_000090", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000090.wav", "text": "نجهز للحج! وش لازم نجيب معنا؟", "language_id": "ar", "instruct": "saudi, conversational, excited"}
6
+ {"id": "sample_000307", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000307.wav", "text": "يلا نبدا الدرس! تأكد من HP مالك وتحضّر للمستوى الجديد على صفحة ستة وخمسين.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
7
+ {"id": "sample_000119", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000119.wav", "text": "يا هيوستن، طرنا! مهمتنا للمريخ تبدأ الحين!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
8
+ {"id": "sample_000452", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000452.wav", "text": "شغل عدل! ادزلبتس استراتيجية الدفاع عن الواحة. خلنا نحتفل بكوب من القهوة مع GameMaster. رقم الصفحة مئة واثنان وأربعون.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
9
+ {"id": "sample_000127", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000127.wav", "text": "الحراس يغيرون النوبة. هذي فرصتنا نتسلل!", "language_id": "ar", "instruct": "saudi, conversational, tense"}
10
+ {"id": "sample_000146", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000146.wav", "text": "الواحة تطلع مثل السراب، بس صدق.", "language_id": "ar", "instruct": "saudi, conversational, mysterious"}
11
+ {"id": "sample_000189", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000189.wav", "text": "غير الكفر بسرعة، ولا ما نطلع من هنا!", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
12
+ {"id": "sample_000200", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000200.wav", "text": "غلي المويه، بعدين حط الهيل عشان الطعم يصير مضبوط.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
13
+ {"id": "sample_000215", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000215.wav", "text": "افرك الورق على الجرح، العشب هذا مستخدم من زمان.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
14
+ {"id": "sample_000016", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000016.wav", "text": "لازم نعبي موية زيادة للسفرة!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
15
+ {"id": "sample_000132", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000132.wav", "text": "النجوم ترشدنا بليل البر.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
sync_data/data/train_raw.jsonl ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"id": "sample_000364", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000364.wav", "text": "مبروك! انت حليت آخر لغز وربحت جائزة مميزة. تْشوف التفاصيل في صفحة مئة واثنين وأربعين!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
2
+ {"id": "sample_000257", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000257.wav", "text": "شوف! هذا نجم الشمال. المسافرين أول كانوا يستخدمونه عشان يلقون طريقهم في الصحرا.", "language_id": "ar", "instruct": "saudi, conversational, awe-inspired"}
3
+ {"id": "sample_000099", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000099.wav", "text": "يالله بسرعة! عدل حلاوة العيد قبل لا يجون الضيوف!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
4
+ {"id": "sample_000093", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000093.wav", "text": "ياسلام! هالفلس العتيق يضبط بالضبط في يد التمثال!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
5
+ {"id": "sample_000427", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000427.wav", "text": "يلا نخلي اللغز ذا سوا! شوفي صفحة مئة واثنين وأربعين للhint.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
6
+ {"id": "sample_000294", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000294.wav", "text": "استعدوا يا رجيل، العدو جاي من الشرق عقب خمس عشرة دقيقة. صفر واحد تسعة صفر اثنان اثنان واحد اثنان ثلاثة ثلاثة اثنان", "language_id": "ar", "instruct": "saudi, conversational, serious"}
7
+ {"id": "sample_000426", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000426.wav", "text": "شفتي الجمل يرقص جنب الواحَهْ البارحة؟ كان العرض عند ستة وخمسين شارع النجدي. It was super!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
8
+ {"id": "sample_000130", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000130.wav", "text": "الاستعداد لهالرحلة شرف ومسؤولية.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
9
+ {"id": "sample_000229", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000229.wav", "text": "القنبلة جاية! خبّ نفسك!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
10
+ {"id": "sample_000166", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000166.wav", "text": "يتقدمون علينا! اثبتوا!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
11
+ {"id": "sample_000113", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000113.wav", "text": "من البيوت الطينية للأبراج الزجاجية، سماء الرياض تحكي قصة تطورنا.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
12
+ {"id": "sample_000475", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000475.wav", "text": "حياك الله في مجلس الصحارى. مهمتك تبتدي عند الغروب بْتمامَه في ستة وخمسين شارع النجدي.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
13
+ {"id": "sample_000330", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000330.wav", "text": "أبغى منك تنظم تجمع العائلة في ستة وخمسين شارع النجدي. لا تنسى ترسل الدعوة بواتساب.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
14
+ {"id": "sample_000318", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000318.wav", "text": "شفت شي غريب حول الواحة القديمه ليلة أمس؟ هذا مكتوب في سجل رقم خمسة ستة.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
15
+ {"id": "sample_000396", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000396.wav", "text": "حياكم الله في المجلس الاستراتيجي. فريقنا مِستعد يواجه تحديات جديدة في صفحة مئة واثنان وأربعون.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
16
+ {"id": "sample_000161", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000161.wav", "text": "كل خطوة قدام تقربنا من النصر.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
17
+ {"id": "sample_000005", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000005.wav", "text": "الرمل يشبه كثبان الفضا من فوق!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
18
+ {"id": "sample_000447", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000447.wav", "text": "لو سمحت اشرح لي كيف تعاملت مع موقف صعب في شغلك الأخير في Office خمسة وستين شارع النجدي.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
19
+ {"id": "sample_000180", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000180.wav", "text": "يالله نلعب! أراهن إني أفوز!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
20
+ {"id": "sample_000213", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000213.wav", "text": "تدرب على الدعوات، بتساعدك في الرحلة.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
21
+ {"id": "sample_000148", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000148.wav", "text": "أسمع شي بالظلام... يمكن الهوى.", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
22
+ {"id": "sample_000375", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000375.wav", "text": "يا شريك، صار الوقت نقول وداع! لا تنسى puzzle party يوم الجمعة في خمسة ستة شارع النجدي!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
23
+ {"id": "sample_000214", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000214.wav", "text": "رم الشبكة لما تكون الموية راكدة، الصبر هو المفتاح.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
24
+ {"id": "sample_000163", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000163.wav", "text": "لا تطلقون النار لين يقربون!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
25
+ {"id": "sample_000009", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000009.wav", "text": "طور شريحة السرعة في جملك الروبوت للسباق!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
26
+ {"id": "sample_000438", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000438.wav", "text": "قم اتبع الصقر إلى الواحَهْ باستخدام الmap في صفحة ستة وخمسون.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
27
+ {"id": "sample_000256", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000256.wav", "text": "ياخي، اللعبة ذي بالنظارات قوية! حسيت إني أطير فوق الرياض صدق!", "language_id": "ar", "instruct": "saudi, conversational, thrilled"}
28
+ {"id": "sample_000188", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000188.wav", "text": "دوس بنزين! قاعدين نفقدهم!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
29
+ {"id": "sample_000343", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000343.wav", "text": "شوف ذا النقش القديم! كنه لقى كنز مخفي في صفحة مئة واثنين وأربعين من دليل اللعبة.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
30
+ {"id": "sample_000123", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000123.wav", "text": "الأكسجين عندنا في خطر. لازم نوسع البيت الأخضر على طول.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
31
+ {"id": "sample_000136", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000136.wav", "text": "كل خطوة تقربك من الراحة.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
32
+ {"id": "sample_000370", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000370.wav", "text": "قال الملك، 'وشلون الجمل صار في ستة وخمسين شارع Royal؟' يمكن يتفرج على Netflix!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
33
+ {"id": "sample_000403", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000403.wav", "text": "مرحبًا بك في المقابلة! اجلس واستمتع بـ qahwa المشهورة في صفحة ستة وخمسين من دليلنا.", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
34
+ {"id": "sample_000287", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000287.wav", "text": "يا ولد العم! شفت الجمل الجديد للجد؟ اسمه 'Speedster ثلاثة آلاف'!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
35
+ {"id": "sample_000160", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000160.wav", "text": "استعدوا، المعركة هذي بتكون صعبة.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
36
+ {"id": "sample_000112", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000112.wav", "text": "الهبوب جاي! بسرعة، اضرب الخيمة وربط البعارين!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
37
+ {"id": "sample_000460", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000460.wav", "text": "العدو قْرب من الكْثبان. جهز حرس القَصر للمعركة على صفحة مئة واثنان وأربعون.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
38
+ {"id": "sample_000440", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000440.wav", "text": "يا هلا بالمسافر، مرحب فيك عند Checkpoint خمسة ستة! استانس بسباقات الجمال اللي عندنا.", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
39
+ {"id": "sample_000260", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000260.wav", "text": "الرموز القديمة على صخرة الفيل تطلع بس تحت ضوء القمر. يلا، فك رموزها قبل يطلع الفجر!", "language_id": "ar", "instruct": "saudi, conversational, mysterious"}
40
+ {"id": "sample_000157", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000157.wav", "text": "إذا سجلنا الحين، المشروبات علي!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
41
+ {"id": "sample_000350", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000350.wav", "text": "جهّز نفسَك للحج! تأكد من Google Maps وقابلنا عند الوّاحات في ستة وخمسين شارع النجدي.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
42
+ {"id": "sample_000404", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000404.wav", "text": "مرحبتس في Strategy واحد صفر واحد: كيف تدزلب الجمال وتغلب الكثبان! صفحة مئة وثلاثة وعشرون", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
43
+ {"id": "sample_000305", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000305.wav", "text": "تذكر كيف كان الهوا الصحراوي على الكْثُبان عند الأوسيَس صفحة مئة واثنان وأربعون؟", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
44
+ {"id": "sample_000419", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000419.wav", "text": "تعلمتوا الاستراتيجيات. الحين طبقوها علشان تغزون أراضي الصحرة. شوفوا صفحة مئة واثنين وأربعين في كتاب Game Manual.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
45
+ {"id": "sample_000209", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000209.wav", "text": "قل القصيدة الحربية، تذكرنا بشجاعة أجدادنا.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
46
+ {"id": "sample_000010", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000010.wav", "text": "يلّا نلحق القطار قبل لا يفوتنا!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
47
+ {"id": "sample_000236", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000236.wav", "text": "لازم نسيطر على الأهرامات، اندفع الحين!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
48
+ {"id": "sample_000101", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000101.wav", "text": "تجهيز شنطة الحج مثل حل بازل مقدس!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
49
+ {"id": "sample_000367", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000367.wav", "text": "لا تْقَلِق، الجمل عنده GPS. بس اتبع الإحداثيات على صفحة ستة وخمسون.", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
50
+ {"id": "sample_000342", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000342.wav", "text": "عرضك ظليل. ما أقدر أبيع بأقل من مئتي coins.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
51
+ {"id": "sample_000477", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000477.wav", "text": "حياكم في المهرجان! تعالوا عند بوث خمسة ستة لتجربة ما تنساها.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
52
+ {"id": "sample_000423", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000423.wav", "text": "هلا بك يا قايد! حضّر عساكرك للمهمة الأولى في واحة خمسة وستين! شوف الخريطة في جهازك الـTablet.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
53
+ {"id": "sample_000253", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000253.wav", "text": "الشاورما خلصت! دق على المورد واطلب دجاج زيادة، بسرعة!", "language_id": "ar", "instruct": "saudi, conversational, busy"}
54
+ {"id": "sample_000446", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000446.wav", "text": "تْذكّر أيام الوَاحَه، وين وُلِدَت Legends في صفحة مئة واثنان وأربعون.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
55
+ {"id": "sample_000140", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000140.wav", "text": "الدلة جاهزة! اسكبها للمعازيم.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
56
+ {"id": "sample_000109", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000109.wav", "text": "بالعيد، نبدا بزيارة الكبار، وبعدين الصغار. كذا نكرم الحكمة والبراءة مع بعض.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
57
+ {"id": "sample_000450", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000450.wav", "text": "ليه الجمل ما رضى يتفاهم؟ خايف يقسم له الoasis برقم ستة وخمسين!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
58
+ {"id": "sample_000164", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000164.wav", "text": "نكسر خط دفاعهم هنا، نفوز بالمعركة.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
59
+ {"id": "sample_000273", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000273.wav", "text": "يلا، لازم نهرب قبل ما الجمل يزهق! ليفل خمسة يستنانا.", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
60
+ {"id": "sample_000366", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000366.wav", "text": "في الصحرَهْ، لقيت رسالة قديمة من جدّي على صفحة اثنين وأربعين في كتاب Desert Wisdom.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
61
+ {"id": "sample_000153", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000153.wav", "text": "إذا ما سرعت، بنخسر قدام سكوتر!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
62
+ {"id": "sample_000107", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000107.wav", "text": "في العيد، طلبت بساط طاير، بس جاني مكنسة كهرب بداله!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
63
+ {"id": "sample_000359", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000359.wav", "text": "حذر! ذا الجمل يحب ياكل guidebooks. تلقاه عند ستة وخمسين شارع النجدي بعد العصر.", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
64
+ {"id": "sample_000117", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000117.wav", "text": "امش في الجسر اللي بين أبراج مركز المملكة. شوف الرياض من فوق، يا سلام!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
65
+ {"id": "sample_000008", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000008.wav", "text": "كسّر الجدار عشان توقف هجمة الفيروس!", "language_id": "ar", "instruct": "saudi, conversational, mysterious"}
66
+ {"id": "sample_000223", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000223.wav", "text": "اللي ينسى أصله، ما له مستقبل.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
67
+ {"id": "sample_000339", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000339.wav", "text": "هلا والله! أنا دليلك اللي بيخذك في مغامرة وسط النْجود. يلا نبدأ من ستة وخمسين شارع النجدي!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
68
+ {"id": "sample_000182", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000182.wav", "text": "الجمل ذا سلالته صافية، يستاهل كل ريال.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
69
+ {"id": "sample_000013", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000013.wav", "text": "اقبض الطارات على السيف وقت العرضة!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
70
+ {"id": "sample_000196", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000196.wav", "text": "الأساطير تنولد هنا، في شوارعنا.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
71
+ {"id": "sample_000226", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000226.wav", "text": "عبي الشوزن، قاعدين يهجمون علينا!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
72
+ {"id": "sample_000221", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000221.wav", "text": "الصحراء تعلم الصبر، مثل ما يقولون البدو.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
73
+ {"id": "sample_000243", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000243.wav", "text": "خلك منتبه! إذا أطلقت الصقر بدري، بنخسر السباق!", "language_id": "ar", "instruct": "saudi, conversational, competitive"}
74
+ {"id": "sample_000474", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000474.wav", "text": "خلنا نخطط الstrategy لوحتنا! اتصل على صفر واحد تسعة صفر اثنان اثنان واحد اثنان ثلاثة ثلاثة اثنان لعقد مجلس العائلة.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
75
+ {"id": "sample_000293", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000293.wav", "text": "تذكر سوالف جدودنا واحنا واقفين عند بوابة المدينة رقم خمسة ستة جنب برج Kingdom.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
76
+ {"id": "sample_000175", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000175.wav", "text": "طلقة مضبوطه تغير كل شي.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
77
+ {"id": "sample_000275", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000275.wav", "text": "ليش الجمل دخل قبيلة Puzzle؟ عشان يحل ألغاز القفر في level ثلاثة!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
78
+ {"id": "sample_000106", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000106.wav", "text": "من جسر السما في برج المملكة بالرياض، تقدر تلمس الغيوم!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
79
+ {"id": "sample_000456", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000456.wav", "text": "جهز الإمدادات لرحلتنا. لازم نوصل ل Oasis أربعة اثنان قبل غروب الشمس.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
80
+ {"id": "sample_000480", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000480.wav", "text": "علمتني وش شفت في ستة وخمسين شارع النجدي. كان فيه أحد مشبوه؟", "language_id": "ar", "instruct": "saudi, conversational, serious"}
81
+ {"id": "sample_000141", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000141.wav", "text": "كل خطوة بهالرحلة تقربك للإيمان.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
82
+ {"id": "sample_000241", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000241.wav", "text": "الهوى قوي الليلة، ثبت الخيمة زين في الأرض.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
83
+ {"id": "sample_000421", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000421.wav", "text": "اقوموا يا محاربين! حتى الـcamel تخاف من خطتنا! الصفحة مئة واثنان وأربعون في الدليل يشرح الخطة.", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
84
+ {"id": "sample_000126", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000126.wav", "text": "عشان نوصل للمرحلة الجاية، لازم نعيد ترتيب هالرموز العتيقة.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
85
+ {"id": "sample_000245", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000245.wav", "text": "احمِ المها من الصيادين، هي مهددة بالانقراض وتحتاج حمايتنا.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
86
+ {"id": "sample_000444", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000444.wav", "text": "اسرع، حل اللغز! المفتاح مخفي في صفحة مئة واثنين وأربعين من الmanual.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
87
+ {"id": "sample_000199", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000199.wav", "text": "افرد العجينة وزيد الصلصة بترتيب.", "language_id": "ar", "instruct": "saudi, conversational, creative"}
88
+ {"id": "sample_000207", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000207.wav", "text": "جدل السعف زين، السلة بتشيل كثير تمر.", "language_id": "ar", "instruct": "saudi, conversational, creative"}
89
+ {"id": "sample_000259", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000259.wav", "text": "الشركة حقتنا في البلوكتشين محتاجة استثمار أكثر. يلا نعرض على شركات التمويل الجريء السعودية!", "language_id": "ar", "instruct": "saudi, conversational, ambitious"}
90
+ {"id": "sample_000152", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000152.wav", "text": "الموضوع مو بس عن الفوز، هو عن الدقة.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
91
+ {"id": "sample_000195", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000195.wav", "text": "آخر جولة، ما بقى إلا المحترفين!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
92
+ {"id": "sample_000108", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000108.wav", "text": "اللفافة العتيقة تقول: 'الكنز في المكان اللي ظل أطول منارة يبوس أقدم بير وقت العصر.'", "language_id": "ar", "instruct": "saudi, conversational, mysterious"}
93
+ {"id": "sample_000095", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000095.wav", "text": "ياهوه! جا وقت نعلق فوانيس رمضان!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
94
+ {"id": "sample_000145", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000145.wav", "text": "الخريطة تقول الكنز مدفون تحت الرمال اللي تتحرك.", "language_id": "ar", "instruct": "saudi, conversational, mysterious"}
95
+ {"id": "sample_000135", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000135.wav", "text": "إذا ما قتلنا الزحمة، الحر بيقتلنا!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
96
+ {"id": "sample_000159", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000159.wav", "text": "نتقدم، لا توقفون الحين!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
97
+ {"id": "sample_000198", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000198.wav", "text": "حرك الجريش لين يثقل، وبعدين زيد البهارات.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
98
+ {"id": "sample_000387", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000387.wav", "text": "مبروك! الحين وصلت لآخر level، يلا نحتفل في ستة وخمسين شارع.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
99
+ {"id": "sample_000219", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000219.wav", "text": "امش بالليل عشان تتفادى حرارة الصحرا.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
100
+ {"id": "sample_000277", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000277.wav", "text": "ليه الجمل قدّم للوظيفَه؟ يبي stable position!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
101
+ {"id": "sample_000268", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000268.wav", "text": "الفخ النبطي القديم يشتغل! بسرعة، حل لغز خريطة النجوم عشان توقفه!", "language_id": "ar", "instruct": "saudi, conversational, thrilling"}
102
+ {"id": "sample_000190", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000190.wav", "text": "حط القذائف مضبوط، لو غلطنا نضيع!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
103
+ {"id": "sample_000328", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000328.wav", "text": "وش عذرتس يا بنت عند ستة وخمسين شارع الواحة الساعه سبعة؟ شفتي سباق الجمل؟", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
104
+ {"id": "sample_000179", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000179.wav", "text": "إذا تثق بصقرك، بيجيب الفريسة.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
105
+ {"id": "sample_000014", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000014.wav", "text": "الغرفة السرية تكشف الأسرار القديمة وقت الغروب.", "language_id": "ar", "instruct": "saudi, conversational, mysterious"}
106
+ {"id": "sample_000147", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000147.wav", "text": "القافلة تريح، بس البر ما ينام.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
107
+ {"id": "sample_000232", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000232.wav", "text": "حط الحاجز هنا، بيكون وقفتنا الأخيرة.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
108
+ {"id": "sample_000011", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000011.wav", "text": "ساعدني ألقى حرامي الضايع في خربطة الشنط!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
109
+ {"id": "sample_000105", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000105.wav", "text": "تجهيز شنط الحج مثل حل لعبة المكعبات بحبات السبحة!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
110
+ {"id": "sample_000225", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000225.wav", "text": "عبي السلاح بسرعة! إحنا تحت ضرب النار!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
111
+ {"id": "sample_000178", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000178.wav", "text": "عجل بالحصان! قربنا نوصل للنهاية!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
112
+ {"id": "sample_000181", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000181.wav", "text": "لازم نلقى لنا ملجأ قبل ما تجي العاصفة.", "language_id": "ar", "instruct": "saudi, conversational, mysterious"}
113
+ {"id": "sample_000121", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000121.wav", "text": "البطولة لنا! تعب فريقنا ما راح على الفاضي!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
114
+ {"id": "sample_000270", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000270.wav", "text": "العملاق النبطي قاعد يصحى! بسرعة، استخدم العود السحري حقك عشان تصعقه، وبعدين اضربه بسيفك المعقوف!", "language_id": "ar", "instruct": "saudi, conversational, epic"}
115
+ {"id": "sample_000373", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000373.wav", "text": "دور على المفتاح المخفي عشان تفتح الباب، وإلا بتظل هنا للأبد! ترى أقرب phone في الدور ستة وخمسون.", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
116
+ {"id": "sample_000285", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000285.wav", "text": "دور على الأثر القديم في manual صفحة ستة وخمسون.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
117
+ {"id": "sample_000283", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000283.wav", "text": "بسرعة! لازم نلقى الscroll المخفي في المكتبه قبل يرجعون الحراس! المكتبه في دور ثلاثة.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
118
+ {"id": "sample_000206", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000206.wav", "text": "حكم الخيوط زين، هالسجادة بتحمل قصص أهلنا.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
119
+ {"id": "sample_000262", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000262.wav", "text": "لازم نوازن بين الاستدامة والتقنية. زيد المزارع العمودية في المنطقة خمسة.", "language_id": "ar", "instruct": "saudi, conversational, innovative"}
120
+ {"id": "sample_000435", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000435.wav", "text": "بسرعة، علمني، وش هي عاصمة أستراليا؟ تلميحة: شوفي صفحة مئة واثنين وأربعين في الڤايد!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
121
+ {"id": "sample_000291", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000291.wav", "text": "اتفقت القبيلة! بنلتقي في واحة ستة وخمسون. جبو أحسن strategies عندكم!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
122
+ {"id": "sample_000280", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000280.wav", "text": "عدّينا كثبان واجد سوا؛ وداعًا يا رفيقي لين نرجع نلتقي في ليفل عشرة.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
123
+ {"id": "sample_000174", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000174.wav", "text": "محاصرين! لازم نطلعهم بقوة!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
124
+ {"id": "sample_000197", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000197.wav", "text": "سر الكبسة يجي مع ظبط البهارات.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
125
+ {"id": "sample_000278", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000278.wav", "text": "دير بالك! الجمل سرق قْهَوَتِس في المهرجان! الظاهر إنه عنده مئة HP مثل Boss في اللعبة!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
126
+ {"id": "sample_000346", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000346.wav", "text": "هلا بك في الفريق، يا القايد. قاعدتك على ستة وخمسين شارع النجدي. جهّز استراتيجيتك.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
127
+ {"id": "sample_000228", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000228.wav", "text": "عجل! عبي المدفع قبل ما يضربونا!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
128
+ {"id": "sample_000170", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000170.wav", "text": "ما عندنا مؤونة كفاية، لازم ننسحب!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
129
+ {"id": "sample_000234", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000234.wav", "text": "تراجع الحين! تجمع عند نقطة التفتيش الجاية!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
130
+ {"id": "sample_000125", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000125.wav", "text": "ثلاثة، اثنان، واحد، انطلق! دعس البنزين وكون الأول!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
131
+ {"id": "sample_000208", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000208.wav", "text": "طبخ الرز واللحم على نار هادية، الضيوف بيجون قريب.", "language_id": "ar", "instruct": "saudi, conversational, creative"}
132
+ {"id": "sample_000151", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000151.wav", "text": "العدو قريب، لازم نهرب الحين!", "language_id": "ar", "instruct": "saudi, conversational, mysterious"}
133
+ {"id": "sample_000102", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000102.wav", "text": "من فوق برج المملكة، تقدر تشوف باكر من اليوم!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
134
+ {"id": "sample_000204", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000204.wav", "text": "الصبار فيه موية تكفينا أيام.", "language_id": "ar", "instruct": "saudi, conversational, creative"}
135
+ {"id": "sample_000120", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000120.wav", "text": "يا ربعي! علامة الضرب تبين المكان على خريطة الكنز ذي!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
136
+ {"id": "sample_000203", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000203.wav", "text": "خيط الشماغ للعريس، خلي الأطراف زينة.", "language_id": "ar", "instruct": "saudi, conversational, creative"}
137
+ {"id": "sample_000424", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000424.wav", "text": "يا بطل! وش اسمك الملحمي قبل نخلّص العالم؟ حط اسمك هنا وشوف صفحة مئة وواحد.", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
138
+ {"id": "sample_000003", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000003.wav", "text": "حطينا في الدرعية القديمة! يالله بسرعة، عدّل طريقة كلامك لا يحسبونا جنّ الناس هنا!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
139
+ {"id": "sample_000379", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000379.wav", "text": "ذي الأحجار القديمة في Ruins خمسة ستة تحكي سَالْفة ضايعة مع الزمان.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
140
+ {"id": "sample_000381", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000381.wav", "text": "العدو جاي من ورى الرِّمال. جهّز الدفاعات في سيكتور خمسة ستة.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
141
+ {"id": "sample_000454", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000454.wav", "text": "أذكر الأيام الزينات في الصحرا تحت ضو الگمر. تشبه Level خمسة باللعبة في صفحة مئة وثلاثة وعشرون.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
142
+ {"id": "sample_000400", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000400.wav", "text": "النصر لنا! خلونا نركب الجمال ونحتفل، بس لا تنسى تسجل رقم خمسة ستة شارع النجدي في GPS.", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
143
+ {"id": "sample_000384", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000384.wav", "text": "لازم تسوي سعر أحسن لهالبضاعة، ولا بتخاطر تخسر الصفقة. شوف الشروط بصفحة ستة وخمسين من كتيب Steam.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
144
+ {"id": "sample_000162", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000162.wav", "text": "اليد اللي ثابتة تفوز، مو اليد السريعة.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
145
+ {"id": "sample_000265", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000265.wav", "text": "الآلة القديمة تشتغل! بسرعة، حل لغز الكتابة القديمة عشان تدخل الغرفة المخبية!", "language_id": "ar", "instruct": "saudi, conversational, mysterious"}
146
+ {"id": "sample_000248", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000248.wav", "text": "يبه، ليه صخرة الفيل وكل الصخور ذي أشكالها غريبة كذا؟", "language_id": "ar", "instruct": "saudi, conversational, curious"}
147
+ {"id": "sample_000104", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000104.wav", "text": "شد حيلك! هالبقي على الكثبان أخشن من بعير فيه الزغطة!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
148
+ {"id": "sample_000006", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000006.wav", "text": "البس نظارة الواقع عشان تشوف خريطة الكنز المخبية!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
149
+ {"id": "sample_000393", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000393.wav", "text": "مرحبا بكم في بداية مغامرتنا! خلونا نشوف وش فيه بصفحة ستة وخمسون سوى!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
150
+ {"id": "sample_000139", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000139.wav", "text": "الرموز باهتة، بس معناها قوي.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
151
+ {"id": "sample_000463", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000463.wav", "text": "بسرعة، قولي لي وش شفتي ب ستة وخمسين شارع النجدي! كان مجلس Falcon؟", "language_id": "ar", "instruct": "saudi, conversational, excited"}
152
+ {"id": "sample_000453", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000453.wav", "text": "شوف ذا النقوش القديمة! يمكن تكشف secret strategy عن خطة سرية. العنوان: ستة وخمسون شارع النجدي", "language_id": "ar", "instruct": "saudi, conversational, excited"}
153
+ {"id": "sample_000231", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000231.wav", "text": "تراجع للغطاء، الوضع هنا يضيع!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
154
+ {"id": "sample_000279", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000279.wav", "text": "جَمِّع السرعة عشان تفوز بكأس الصحراء. Level ثلاثة ينتظرك.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
155
+ {"id": "sample_000173", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000173.wav", "text": "طلقة مضبوطة يعني فوز مضبوط.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
156
+ {"id": "sample_000264", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000264.wav", "text": "المنطقة الآمنة تضيق! روح برج المملكة عشان تاخذ ميزة المكان العالي!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
157
+ {"id": "sample_000227", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000227.wav", "text": "سوق الدبابة للمرتفع، نحتاج الأفضلية!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
158
+ {"id": "sample_000183", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000183.wav", "text": "الحصان باسمه القوي يشيل فخر القبيلة.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
159
+ {"id": "sample_000115", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000115.wav", "text": "النقوش في الحجر تتكلم عن طرق التجارة القديمة. تقدر تفك شفرة كلامها؟", "language_id": "ar", "instruct": "saudi, conversational, mysterious"}
160
+ {"id": "sample_000114", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000114.wav", "text": "جا وقت نعلق فانوس رمضان! يلا ننور بيتنا للشهر الفضيل.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
161
+ {"id": "sample_000103", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000103.wav", "text": "في العيد، تمنيت بعير... بس جاني لعبة محشية بداله!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
162
+ {"id": "sample_000478", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000478.wav", "text": "مرحبا بكم يا رْجال الصغار! خلونا نبدا الدرس بقوة وشجاعة. شوفوا صفحة مئة واثنان وأربعون في كتاب game.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
163
+ {"id": "sample_000097", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000097.wav", "text": "الجليب العتيق يوسوس، 'حط ريال وتمن أمنية!'", "language_id": "ar", "instruct": "saudi, conversational, mysterious"}
164
+ {"id": "sample_000201", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000201.wav", "text": "هشّك الرز بالشوكة عشان يطلع خفيف.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
165
+ {"id": "sample_000205", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000205.wav", "text": "دربه يرجع بالصيد، الثقة تبني مع الوقت.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
166
+ {"id": "sample_000276", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000276.wav", "text": "سويتِها! الحين الصحراء صارت بأمان. تعالوا نلتقي عند الواحة لاحتفال كبير مع الشلة في ليفل واحد صفر!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
167
+ {"id": "sample_000274", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000274.wav", "text": "ذا الجمل اللي في حوشتس عميل سري ولا بس يعشق قهوة وPlayStation؟", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
168
+ {"id": "sample_000374", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000374.wav", "text": "حيّاكم الله في المهرجان! انبسطوا بسباق الجمال وخذوا تمرات تس مجانًا من booth خمسة ستة.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
169
+ {"id": "sample_000266", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000266.wav", "text": "انتبه! درونات الشركات تفحص المكان. استخدم جهاز الإخفاء السايبر حقك عشان ما ينكشف وجودك.", "language_id": "ar", "instruct": "saudi, conversational, futuristic"}
170
+ {"id": "sample_000344", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000344.wav", "text": "حياك الله في هالمستوى من Puzzle! لا تضيع جملَك في متاهة النفود عند سبعة وستين شارع النبطي.", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
171
+ {"id": "sample_000184", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000184.wav", "text": "كلّم حصانك بهدوء، وبيثق فيك وقت المعركة.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
172
+ {"id": "sample_000224", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000224.wav", "text": "النار تدفي قلوبنا، والقصص تدفي الأرواح.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
173
+ {"id": "sample_000252", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000252.wav", "text": "يالله، وزع الرماة على طرف طويق! ما نبي يخترقون القلعة!", "language_id": "ar", "instruct": "saudi, conversational, competitive"}
174
+ {"id": "sample_000212", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000212.wav", "text": "الغزلان سريعة، امش على آثارها بحذر.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
175
+ {"id": "sample_000218", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000218.wav", "text": "النقوش هذي تحكي قصة سقوط المدينة.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
176
+ {"id": "sample_000401", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000401.wav", "text": "السلام عليكم يا زائرٍ نبيل. أنا رفيقتس اللي بيدزلك في هذي الألغاز الغامضة في Level خمسة من اللعبة.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
177
+ {"id": "sample_000110", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000110.wav", "text": "هالنقوش على الحجر تبين ساعة الماء القديمة في مدائن صالح. تقدر تشغلها من جديد؟", "language_id": "ar", "instruct": "saudi, conversational, mysterious"}
178
+ {"id": "sample_000142", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000142.wav", "text": "الرمل يخبّي أكثر من العظام.", "language_id": "ar", "instruct": "saudi, conversational, mysterious"}
179
+ {"id": "sample_000111", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000111.wav", "text": "ترتيب النقل الجماعي لحجاج حملتنا مثل حل لغز صعب. كل واحد له طلبات مختلفة.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
180
+ {"id": "sample_000192", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000192.wav", "text": "دوّر السيارة! خلك ملك الشوارع!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
181
+ {"id": "sample_000239", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000239.wav", "text": "خل القهوة تغلي ببطء، الطعم يصير مضبوط.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
182
+ {"id": "sample_000448", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000448.wav", "text": "هلا، لقيت الجمل الضايع؟ دور في صفحة مئة واثنين وأربعين من الmanual!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
183
+ {"id": "sample_000202", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000202.wav", "text": "خيط الثوب زين، كل شي مهم للعريس.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
184
+ {"id": "sample_000242", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000242.wav", "text": "ابني الطاحونة في وجه الهوى، لازم تدور بدون مشاكل.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
185
+ {"id": "sample_000263", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000263.wav", "text": "دبابات العدو جاية من الشرق! حمّل الطلقات اللي تخترق الدروع وصوّب!", "language_id": "ar", "instruct": "saudi, conversational, intense"}
186
+ {"id": "sample_000267", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000267.wav", "text": "السباق يبدأ بعد خمسة دقايق! خذ لك سيارة سريعة وتعال لموقف استاد الملك فهد.", "language_id": "ar", "instruct": "saudi, conversational, satirical"}
187
+ {"id": "sample_000414", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000414.wav", "text": "بسرعة! حل اللغز عشان تفتح الجمل قبل توصلنا القبيلة المنافسة. لا تنسى تسجل الرقم في صفحة ستة وخمسون بالدليل!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
188
+ {"id": "sample_000220", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000220.wav", "text": "خلنا ندور أفضل الصفقات في السوق قبل ما نكمل.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
189
+ {"id": "sample_000129", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000129.wav", "text": "لازم نلقى المفتاح المخفي علشان ندخل القبر.", "language_id": "ar", "instruct": "saudi, conversational, mysterious"}
190
+ {"id": "sample_000457", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000457.wav", "text": "شوف ذا الباب القديم! يحسسك إنه Portal مخفي لعالم ثاني، في خريطة ليفل ستة وخمسون.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
191
+ {"id": "sample_000308", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000308.wav", "text": "تسذكر يوم اجتمعنا تحت النجوم بالصحراء؟ كنا نسولف عن PlayStation وشارع خمسة ستة بالرياض.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
192
+ {"id": "sample_000177", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000177.wav", "text": "النجوم بتدلنا بالليل.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
193
+ {"id": "sample_000155", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000155.wav", "text": "ما نخليهم ياخذون التل. اثبتوا!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
194
+ {"id": "sample_000012", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000012.wav", "text": "بسرعة، طلّق الصقور على الطريدة اللي تفر!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
195
+ {"id": "sample_000399", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000399.wav", "text": "تأكد من إرسال تفاصيل المعاهدة إلى المجلس عند الساعة العاشرة صباحًا عبر email.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
196
+ {"id": "sample_000018", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000018.wav", "text": "النجوم تدلنا في الرمل اللي ما له نهاية.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
197
+ {"id": "sample_000271", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000271.wav", "text": "انتبِه لخطواتك. الطريق هنا في ليفل خمسة خطير جدًا وsteep.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
198
+ {"id": "sample_000158", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000158.wav", "text": "ثبت في مكانك، لا تفقد تركيزك!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
199
+ {"id": "sample_000250", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000250.wav", "text": "المترو زحمة! لازم نلقى طريق أسرع للمول.", "language_id": "ar", "instruct": "saudi, conversational, stressed"}
200
+ {"id": "sample_000131", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000131.wav", "text": "لازم نزين الخيمة للاحتفال الكبير!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
201
+ {"id": "sample_000430", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000430.wav", "text": "هلا، خلونا نحفر هنا ونلقي treasure قديم! يمكن نلقى fossil الجمل؟ صفحة ثلاثمئة واثنا عشر في الدليل.", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
202
+ {"id": "sample_000412", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000412.wav", "text": "شفت سباق الجمال عند واحة ستة وخمسين؟ كان رهيب!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
203
+ {"id": "sample_000238", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000238.wav", "text": "الهواء مثالي، خلنا نسبقهم لخط النهاية!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
204
+ {"id": "sample_000144", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000144.wav", "text": "شلون كل محل هنا يبيع نفس الشي؟", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
205
+ {"id": "sample_000340", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000340.wav", "text": "مبروك يا بطل! قِمتَ بقود قبيْلتك للمجد. لين نلتقي مرة ثانية في الويْحَه على صفحة مئة واثنين وأربعين من دليل اللعبة.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
206
+ {"id": "sample_000193", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000193.wav", "text": "دوس بنزين! نتسابق على ملك الشوارع!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
207
+ {"id": "sample_000326", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000326.wav", "text": "تذكر يوم اللي جالك تحدي وغلبته في مقابلة مع شركة RiyadhTech. رقم الصفحة مئة واثنان وأربعون.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
208
+ {"id": "sample_000137", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000137.wav", "text": "الرمل يتحرك مع كل خطوة، يخفي الطريق قدامنا.", "language_id": "ar", "instruct": "saudi, conversational, mysterious"}
209
+ {"id": "sample_000261", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000261.wav", "text": "الخط الأزرق زحمة! حوّل الركاب للخط الأخضر عشان يوصلون المول بالوقت!", "language_id": "ar", "instruct": "saudi, conversational, urgent"}
210
+ {"id": "sample_000211", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000211.wav", "text": "شوف رجوله، قوية. بيكون ممتاز للقافلة.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
211
+ {"id": "sample_000118", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000118.wav", "text": "من بيوت الدرعية الطينية لأبراج الرياض، عمارتنا تحكي قصتنا.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
212
+ {"id": "sample_000337", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000337.wav", "text": "سمعتْ؟ خُطتْ المَلِگ الجديدة سرية مثل رقم الهاتف صفر خمسة صفر واحد اثنان ثلاثة أربعة خمسة ستة سبعة!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
213
+ {"id": "sample_000230", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000230.wav", "text": "حط المتفجرات وارجع، بنفجر الجسر!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
214
+ {"id": "sample_000092", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000092.wav", "text": "قلت 'قزازة موية'، مو 'بعير موية'!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
215
+ {"id": "sample_000240", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000240.wav", "text": "ارفع السيف فوق، العرضة بتبدأ قريب!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
216
+ {"id": "sample_000433", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000433.wav", "text": "تتذكر حكايات Al-Majlis القديمة؟ دايمًا تلهم الشجاعة. تذكر صفحة مئة واثنان وأربعون بالكتاب.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
217
+ {"id": "sample_000254", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000254.wav", "text": "عشان نفتح الدور الجاي، لازم نحل اللغز الاقتصادي ذا. فكر مثل المستثمر!", "language_id": "ar", "instruct": "saudi, conversational, challenging"}
218
+ {"id": "sample_000143", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000143.wav", "text": "الصقر حلق، ودانا وجهتنا.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
219
+ {"id": "sample_000246", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000246.wav", "text": "يا سلام، قطعنا البلاد بساعة وحدة! الهايبرلوب ذا شي ثاني!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
220
+ {"id": "sample_000128", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000128.wav", "text": "طيارات العدو وراك! سو حركات المراوغة!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
221
+ {"id": "sample_000165", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000165.wav", "text": "قريبين نفوز! لا تخففون الضغط!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
222
+ {"id": "sample_000169", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000169.wav", "text": "تحركوا! ما نقدر نجلس هنا أكثر!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
223
+ {"id": "sample_000116", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000116.wav", "text": "المشوار لمكة مو بس للجسم. أنت جاهز روحياً للحج؟", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
224
+ {"id": "sample_000168", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000168.wav", "text": "لو تسجل، العشا علي!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
225
+ {"id": "sample_000297", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000297.wav", "text": "يا زين! جملنا جاب VIP pass للْحَجّ. دق على صفر خمسة صفر واحد اثنان ثلاثة أربعة خمسة ستة سبعة للتفاصيل.", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
226
+ {"id": "sample_000237", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000237.wav", "text": "نحتاج تعزيزات نفك الحصار عن بغداد!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
227
+ {"id": "sample_000191", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000191.wav", "text": "انتبه من الحفر! ما نبي نطيح!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
228
+ {"id": "sample_000468", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000468.wav", "text": "قوّموا المكينة! نْسابق صوب الويحات بسرعة صفر واحد تسعة صفر اثنان اثنان واحد اثنان ثلاثة ثلاثة اثنان!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
229
+ {"id": "sample_000172", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000172.wav", "text": "بهالسرعة بنفوت العشا!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
230
+ {"id": "sample_000100", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000100.wav", "text": "رمول الزمان خشت المفتاح؛ ما يشوفه إلا عين الصقر.", "language_id": "ar", "instruct": "saudi, conversational, mysterious"}
231
+ {"id": "sample_000323", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000323.wav", "text": "مرحبا بك في عالم الصحراء. استعد للمعركة، يا بطل. رحلتك تبدأ الآن في صفحة ستة وخمسون من Game Guide.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
232
+ {"id": "sample_000134", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000134.wav", "text": "لقينا الخريطة! يالله نبدأ المغامرة!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
233
+ {"id": "sample_000314", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000314.wav", "text": "حياك الله في مجلس التخطيط. من فضلك اذكر اسمك ودورك. حنا في غرفة رقم اثني عشر.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
234
+ {"id": "sample_000394", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000394.wav", "text": "مرحبًا بك يا محارب. قول لنا عن رحلتك قُدّام المجلس على صفحة ستة وخمسون.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
235
+ {"id": "sample_000149", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000149.wav", "text": "أحسن لك تكون أسرع من الهوى، وإلا راحت عليك!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
236
+ {"id": "sample_000272", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000272.wav", "text": "صدى الحكمة القديمة باقي يتردد في هالأطلال المْنسية، كنك تلقى شي زي ليفل خمسة في لعبة strategy.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
237
+ {"id": "sample_000133", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000133.wav", "text": "ضرب عازف العود على الأوتار، وبدأوا الناس يصفقون.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
238
+ {"id": "sample_000244", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000244.wav", "text": "تأكد أن كل التوصيلات على الوقت، زحمة المدينة ممكن تسبب تأخير.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
239
+ {"id": "sample_000015", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000015.wav", "text": "شوف! لقيت كتابة قديمة على الجدار ذا!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
240
+ {"id": "sample_000091", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000091.wav", "text": "يبه، ليه نلبس ثياب يديدة للعيد؟", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
241
+ {"id": "sample_000255", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000255.wav", "text": "وناسة عالم الشتاء! نجرب اللعبة الدوارة ولا صالة الجليد أول؟", "language_id": "ar", "instruct": "saudi, conversational, excited"}
242
+ {"id": "sample_000418", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000418.wav", "text": "مرحبًا يا محاربين! خلونا نغزو الديرة ونسجل مئة نقطة!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
243
+ {"id": "sample_000222", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000222.wav", "text": "القبيلة واقفة مع بعض مثل الجدار المتين.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
244
+ {"id": "sample_000167", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000167.wav", "text": "يدك ثابتة وعقلك صافٍ، كذا تفوز.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
245
+ {"id": "sample_000320", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000320.wav", "text": "مبروك! دزيت هالمستوى. لا تنسى تشيك على وقود الجمل بصفحة مئة واثنين وأربعين من الـ User Manual.", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
246
+ {"id": "sample_000338", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000338.wav", "text": "تتذگر طعم القهوة مع التمر بالمجلس؟ أظن إنه كان في صالة رقم اثنان ثلاثة.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
247
+ {"id": "sample_000233", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000233.wav", "text": "حط الفخ هنا، بننصب لهم كمين مع الفجر.", "language_id": "ar", "instruct": "saudi, conversational, critical"}
248
+ {"id": "sample_000235", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000235.wav", "text": "دور القناص قبل ما يضرب مرة ثانية!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
249
+ {"id": "sample_000295", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000295.wav", "text": "بسرعة، دوّر على المفتاح المخفي في القاعة majestic قبل ما يرجعون الحراس! شوف صفحة مئة واثنين وأربعين للخطوات.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
250
+ {"id": "sample_000150", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000150.wav", "text": "لازم نرجع نرتب الصفوف قبل ما يهجمون مرة ثانية.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
251
+ {"id": "sample_000216", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000216.wav", "text": "اطلع بحذر، أفضل التمر فوق.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
252
+ {"id": "sample_000094", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000094.wav", "text": "شوف! الكعبة قدامنا على طول!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
253
+ {"id": "sample_000171", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000171.wav", "text": "شكله الكفر انفجر، لازم نصلحه بسرعة.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
254
+ {"id": "sample_000356", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000356.wav", "text": "ارسل الكشافة لجهة الكثبان الشرقية يدورون عن إشارات كمين. لا تنسى تحدث الخريطة في جهاز GPS اللي معك للإصدار اثنان ثلاثة.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
255
+ {"id": "sample_000392", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000392.wav", "text": "تشوف الصقور يطرن فوق الجبل؟ خلنا ننضم معهم في الصفحة مئة واثنان وأربعون من Mountain Quest!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
256
+ {"id": "sample_000138", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000138.wav", "text": "الغنم جاهزة! يالله نبدأ العزيمة!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
257
+ {"id": "sample_000351", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000351.wav", "text": "حياكم الله في سوق التجارة! شوفوا السرج الخاص بالجمل عندنا بسعر مئة وتسعة وتسعين ريال!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
258
+ {"id": "sample_000096", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000096.wav", "text": "التجهيز للحج مثل لعبة الطناخة بس حقيقية!", "language_id": "ar", "instruct": "saudi, conversational, humorous"}
259
+ {"id": "sample_000210", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000210.wav", "text": "السعر غالي، خلنا نتفق على شي ينفعنا اثنيننا.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
260
+ {"id": "sample_000251", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000251.wav", "text": "متأكد إن البالون ذا يشيلنا كلنا؟ أحس إنه يترنح شوي فوق!", "language_id": "ar", "instruct": "saudi, conversational, nervous"}
261
+ {"id": "sample_000258", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000258.wav", "text": "ياخي، هذا مرشد سياحي تصويري؟ كأنك تمشي بالماضي والمستقبل مع بعض!", "language_id": "ar", "instruct": "saudi, conversational, curious"}
262
+ {"id": "sample_000124", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000124.wav", "text": "العاصفة تقرب! لازم نوصل المنطقة الآمنة بسرعة!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
263
+ {"id": "sample_000269", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000269.wav", "text": "فوت الكورة بين رجلين المدافع وسو تمريرة حايط مع ربيعك عشان تسجل في زقاق السوق!", "language_id": "ar", "instruct": "saudi, conversational, energetic"}
264
+ {"id": "sample_000455", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000455.wav", "text": "اذكر يوم تعلمنا عن قبائل Bedouin وتقاليدهم في صفحة أربعة وثلاثين من كتاب History.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
265
+ {"id": "sample_000467", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000467.wav", "text": "لقَ ذا الواحَهْ المخفّية قبل غروب الشمس وقَم المخيم قريب من الأنقاض القديمة في شارع الملك عبد الله رقم سبعة تسعة.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
266
+ {"id": "sample_000247", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000247.wav", "text": "شوف الحفلة التصويرية ذي! التقنية غيرت جو الترفيه عندنا بشكل!", "language_id": "ar", "instruct": "saudi, conversational, amazed"}
267
+ {"id": "sample_000185", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000185.wav", "text": "حصان الفارس أعز صديق له وقت القتال.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
268
+ {"id": "sample_000154", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000154.wav", "text": "باقي لك هدف واحد. خلها تضبط.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
269
+ {"id": "sample_000442", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000442.wav", "text": "الاجتماع العائلي في الواحة مهم جداً. لازم نسوي الخطة في صفحة مئة واثنان وأربعون.", "language_id": "ar", "instruct": "saudi, conversational, serious"}
270
+ {"id": "sample_000249", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000249.wav", "text": "السيارات الكهربا ساكتة مرة! كأننا نسابق في المستقبل!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
271
+ {"id": "sample_000459", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000459.wav", "text": "تذكر يوم تسابقنا فوق الكْثبان الرملية في Desert Racer، ندزلب غروب الشمس؟ قابلني عند ستة وخمسين شارع النجدي.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
272
+ {"id": "sample_000156", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000156.wav", "text": "قريب توصل، باقي لك لفة!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
273
+ {"id": "sample_000007", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000007.wav", "text": "برمج الدرونات تسقي المزارع اللي فوق!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
274
+ {"id": "sample_000217", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000217.wav", "text": "الحجارة هذي من قرون واقفة، اسمع قصصها.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
275
+ {"id": "sample_000341", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000341.wav", "text": "تْفَكَّر فِي الرِّحْلَة عبر الصّحْرَا لِـ Mecca. تذَكَّر سَوالِف أَجْدَادْنَا اللي قالوها في صفحة مئة واثنين وأربعين.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
276
+ {"id": "sample_000187", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000187.wav", "text": "الدبابة جايه من الشرق! جهز المدفع!", "language_id": "ar", "instruct": "saudi, conversational, serious"}
277
+ {"id": "sample_000302", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000302.wav", "text": "شفت أحد مشبوه قريب من الوَحَه حول الساعه صفر تسعة: صفر صفر؟ يمكن كان لابس قميص مكتوب عليه Desert Eagle.", "language_id": "ar", "instruct": "saudi, conversational, excited"}
278
+ {"id": "sample_000176", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000176.wav", "text": "فاضي! مرر الكورة!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
279
+ {"id": "sample_000017", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000017.wav", "text": "نقوش الحنا حق جدتي مثل القصيد اللي يسيل.", "language_id": "ar", "instruct": "saudi, conversational, reflective"}
280
+ {"id": "sample_000407", "audio_path": "/home/riftuser/OmniVoice/sync_data/data/wavs/sample_000407.wav", "text": "شوف! الكثبان تلمع مثل fireflies! يلا نحل هال puzzle بسرعه!", "language_id": "ar", "instruct": "saudi, conversational, excited"}
sync_data/tokens/dev/data.lst ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /home/riftuser/OmniVoice/sync_data/tokens/dev/audios/shard-000000.tar /home/riftuser/OmniVoice/sync_data/tokens/dev/txts/shard-000000.jsonl 1 4.200
2
+ /home/riftuser/OmniVoice/sync_data/tokens/dev/audios/shard-000001.tar /home/riftuser/OmniVoice/sync_data/tokens/dev/txts/shard-000001.jsonl 1 2.840
3
+ /home/riftuser/OmniVoice/sync_data/tokens/dev/audios/shard-000002.tar /home/riftuser/OmniVoice/sync_data/tokens/dev/txts/shard-000002.jsonl 1 4.840
4
+ /home/riftuser/OmniVoice/sync_data/tokens/dev/audios/shard-000003.tar /home/riftuser/OmniVoice/sync_data/tokens/dev/txts/shard-000003.jsonl 1 4.840
5
+ /home/riftuser/OmniVoice/sync_data/tokens/dev/audios/shard-000004.tar /home/riftuser/OmniVoice/sync_data/tokens/dev/txts/shard-000004.jsonl 1 2.720
6
+ /home/riftuser/OmniVoice/sync_data/tokens/dev/audios/shard-000005.tar /home/riftuser/OmniVoice/sync_data/tokens/dev/txts/shard-000005.jsonl 1 7.280
7
+ /home/riftuser/OmniVoice/sync_data/tokens/dev/audios/shard-000006.tar /home/riftuser/OmniVoice/sync_data/tokens/dev/txts/shard-000006.jsonl 1 3.480
8
+ /home/riftuser/OmniVoice/sync_data/tokens/dev/audios/shard-000007.tar /home/riftuser/OmniVoice/sync_data/tokens/dev/txts/shard-000007.jsonl 1 2.840
9
+ /home/riftuser/OmniVoice/sync_data/tokens/dev/audios/shard-000008.tar /home/riftuser/OmniVoice/sync_data/tokens/dev/txts/shard-000008.jsonl 1 9.720
10
+ /home/riftuser/OmniVoice/sync_data/tokens/dev/audios/shard-000009.tar /home/riftuser/OmniVoice/sync_data/tokens/dev/txts/shard-000009.jsonl 1 3.800
11
+ /home/riftuser/OmniVoice/sync_data/tokens/dev/audios/shard-000010.tar /home/riftuser/OmniVoice/sync_data/tokens/dev/txts/shard-000010.jsonl 1 3.360
12
+ /home/riftuser/OmniVoice/sync_data/tokens/dev/audios/shard-000011.tar /home/riftuser/OmniVoice/sync_data/tokens/dev/txts/shard-000011.jsonl 1 4.880
13
+ /home/riftuser/OmniVoice/sync_data/tokens/dev/audios/shard-000012.tar /home/riftuser/OmniVoice/sync_data/tokens/dev/txts/shard-000012.jsonl 1 3.840
14
+ /home/riftuser/OmniVoice/sync_data/tokens/dev/audios/shard-000013.tar /home/riftuser/OmniVoice/sync_data/tokens/dev/txts/shard-000013.jsonl 1 3.160
15
+ /home/riftuser/OmniVoice/sync_data/tokens/dev/audios/shard-000014.tar /home/riftuser/OmniVoice/sync_data/tokens/dev/txts/shard-000014.jsonl 1 3.360