arwin0727 commited on
Commit
469825c
·
verified ·
1 Parent(s): 6932ebe

Upload miner.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. miner.py +1197 -0
miner.py ADDED
@@ -0,0 +1,1197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Vocence TTS — Qwen3-TTS loaded in-process (no subprocess/TCP).
3
+
4
+ Loads weights from the HF snapshot path (see ensure_qwen_model_present).
5
+
6
+ Contract:
7
+ Miner(path_hf_repo: Path)
8
+ warmup() -> None
9
+ generate_wav(instruction: str, text: str) -> tuple[np.ndarray, int]
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import io
14
+ import json
15
+ import logging
16
+ import os
17
+ import sys
18
+ import time
19
+ import traceback
20
+ import warnings
21
+ import wave
22
+ from pathlib import Path
23
+ from typing import Any, Mapping, Optional
24
+
25
+ import numpy as np
26
+
27
+ # Prefer SoundFile over SoX for torchaudio I/O when available (avoids sox binary warning).
28
+ os.environ.setdefault("TORCHAUDIO_USE_SOX", "0")
29
+
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # Generation hyperparameters
33
+ # ---------------------------------------------------------------------------
34
+ _GEN_TEMPERATURE = 0.9
35
+ _GEN_TOP_P = 1.0
36
+ _GEN_TOP_K = 50
37
+ _GEN_REPETITION_PENALTY = 1.05
38
+ _GEN_MAX_NEW_TOKENS = 600
39
+ _GEN_DO_SAMPLE = True
40
+
41
+ _GEN_TIMEOUT_SEC = 120.0
42
+
43
+ _VALIDATOR_WEIGHTS: dict[str, float] = {
44
+ "script": 0.30,
45
+ "naturalness": 0.15,
46
+ "gender": 0.10,
47
+ "speed": 0.10,
48
+ "emotion": 0.10,
49
+ "age_group": 0.10,
50
+ "pitch": 0.05,
51
+ "accent": 0.05,
52
+ "tone": 0.05,
53
+ }
54
+
55
+ DEFAULT_HUB_MODEL_ID = "Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign"
56
+ AI_AUDIO_MODEL = "gpt-4o-audio-preview"
57
+
58
+ _MIN_DURATION_SEC = 0.15
59
+ _MAX_DURATION_SEC = 29.5
60
+ _MIN_RMS = 5e-5
61
+ _MAX_ABSOLUTE = 1.0 + 1e-3
62
+
63
+ _VOCENCE_YAML = "vocence_config.yaml"
64
+
65
+ REPO = Path(__file__).resolve().parent
66
+ MAX_AUDIO_SEC = 30
67
+ MAX_TEXT = 2000
68
+ MAX_INST = 600
69
+
70
+
71
+ def _configure_third_party_noise() -> None:
72
+ """Quieter torch/qwen logs; non-fatal warning filters."""
73
+ for name in (
74
+ "qwen_tts",
75
+ "qwen_tts.core",
76
+ "qwen_tts.core.models",
77
+ "transformers",
78
+ "transformers.generation",
79
+ "transformers.modeling_utils",
80
+ "torchaudio",
81
+ "torchaudio.backend",
82
+ "sox",
83
+ ):
84
+ logging.getLogger(name).setLevel(logging.WARNING)
85
+ try:
86
+ from transformers import logging as trl
87
+
88
+ trl.set_verbosity_error()
89
+ except Exception:
90
+ pass
91
+ warnings.filterwarnings(
92
+ "ignore",
93
+ message=".*(pad_token_id|eos_token_id|initializing talker|default values).*",
94
+ category=UserWarning,
95
+ )
96
+ try:
97
+ import torchaudio
98
+
99
+ if hasattr(torchaudio, "set_audio_backend"):
100
+ torchaudio.set_audio_backend("soundfile")
101
+ except Exception:
102
+ pass
103
+
104
+
105
+ _configure_third_party_noise()
106
+
107
+
108
+ # ---------------------------------------------------------------------------
109
+ # Config + Hub download (unchanged contract)
110
+ # ---------------------------------------------------------------------------
111
+
112
+
113
+ def _read_vocence_yaml(repo: Path) -> dict[str, Any]:
114
+ path = repo / _VOCENCE_YAML
115
+ if not path.is_file():
116
+ return {}
117
+ from yaml import safe_load
118
+
119
+ with path.open("r", encoding="utf-8") as fh:
120
+ data = safe_load(fh)
121
+ return data if isinstance(data, Mapping) else {}
122
+
123
+
124
+ def _merge_default_instruction(default: str, user: str) -> str:
125
+ """Prepend default style; duplicate keys in ` | ` parse order: user segment wins (see _parse_instruction)."""
126
+ d = (default or "").strip()
127
+ u = (user or "").strip()
128
+ if not d:
129
+ return u
130
+ if not u:
131
+ return d
132
+ return f"{d} | {u}"
133
+
134
+
135
+ def _coerce_cfg_float(m: Mapping[str, Any], key: str, default: float) -> float:
136
+ v = m.get(key)
137
+ if v is None:
138
+ return default
139
+ try:
140
+ return float(v)
141
+ except (TypeError, ValueError):
142
+ return default
143
+
144
+
145
+ def _coerce_cfg_int(m: Mapping[str, Any], key: str, default: int) -> int:
146
+ v = m.get(key)
147
+ if v is None:
148
+ return default
149
+ try:
150
+ return int(v)
151
+ except (TypeError, ValueError):
152
+ return default
153
+
154
+
155
+ def _coerce_cfg_bool(m: Mapping[str, Any], key: str, default: bool) -> bool:
156
+ v = m.get(key)
157
+ if v is None:
158
+ return default
159
+ if isinstance(v, bool):
160
+ return v
161
+ if isinstance(v, str):
162
+ return v.strip().lower() in ("1", "true", "yes", "on")
163
+ return bool(v)
164
+
165
+
166
+
167
+ def _is_hub_model_id(s: str) -> bool:
168
+ t = (s or "").strip()
169
+ if not t or t[0] in ("/", ".", "~") or "\\" in t or "\n" in t or ".." in t:
170
+ return False
171
+ parts = t.split("/")
172
+ return len(parts) == 2 and all(p for p in parts)
173
+
174
+
175
+ def _hf_snapshot_to_local(repo_id: str, local_dir: str) -> str:
176
+ from huggingface_hub import snapshot_download
177
+
178
+ token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGING_FACE_HUB_TOKEN")
179
+ p = snapshot_download(
180
+ repo_id=repo_id,
181
+ local_dir=local_dir,
182
+ local_dir_use_symlinks=False,
183
+ token=token,
184
+ )
185
+ return str(p)
186
+
187
+
188
+ def _local_dir_for_downloads(repo: Path, runtime: dict[str, Any] | None) -> Path:
189
+ repo = repo.resolve()
190
+ r = runtime or {}
191
+ raw = (os.environ.get("QWEN_TTS_LOCAL_DIR") or r.get("local_model_dir") or "").strip()
192
+ if raw:
193
+ p = Path(raw).expanduser()
194
+ return p.resolve() if p.is_absolute() else (repo / p).resolve()
195
+ hub = str(r.get("hub_model_id", DEFAULT_HUB_MODEL_ID))
196
+ return (repo / "models" / hub.replace("/", "_")).resolve()
197
+
198
+
199
+ def ensure_qwen_model_present(
200
+ repo: Path,
201
+ model_id: str | None,
202
+ download_hub_id: str = DEFAULT_HUB_MODEL_ID,
203
+ *,
204
+ local_download_root: Path,
205
+ ) -> str:
206
+ repo = repo.resolve()
207
+ if (not model_id or not str(model_id).strip()) and (repo / "config.json").is_file():
208
+ return str(repo)
209
+
210
+ if not model_id or not str(model_id).strip():
211
+ target = local_download_root
212
+ if target.is_dir() and (target / "config.json").is_file():
213
+ return str(target)
214
+ print(
215
+ f"[miner] no runtime.model_id; downloading {download_hub_id!r} → {target} …",
216
+ flush=True,
217
+ )
218
+ target.mkdir(parents=True, exist_ok=True)
219
+ return _hf_snapshot_to_local(download_hub_id, str(target))
220
+
221
+ mid = str(model_id).strip()
222
+ if _is_hub_model_id(mid):
223
+ target = local_download_root
224
+ if target.is_dir() and (target / "config.json").is_file():
225
+ print(f"[miner] reusing local snapshot at {target}", flush=True)
226
+ return str(target)
227
+ print(f"[miner] Hub model_id {mid!r}; downloading → {target} …", flush=True)
228
+ target.mkdir(parents=True, exist_ok=True)
229
+ return _hf_snapshot_to_local(mid, str(target))
230
+
231
+ cand = Path(mid).expanduser()
232
+ if not cand.is_absolute():
233
+ cand = (repo / cand).resolve()
234
+ else:
235
+ cand = cand.resolve()
236
+ if cand.is_file():
237
+ cand = cand.parent
238
+ if cand.is_dir() and (cand / "config.json").is_file():
239
+ return str(cand)
240
+ if cand.suffix and not cand.is_dir():
241
+ cand = cand.parent
242
+ print(
243
+ f"[miner] no weights at {cand}; downloading {download_hub_id!r} there …",
244
+ flush=True,
245
+ )
246
+ cand.mkdir(parents=True, exist_ok=True)
247
+ return _hf_snapshot_to_local(download_hub_id, str(cand))
248
+
249
+
250
+ def _f32_to_wav_bytes(waveform: np.ndarray, sample_rate: int) -> bytes:
251
+ w = np.clip(np.asarray(waveform, dtype=np.float32), -1.0, 1.0)
252
+ s16 = (w * 32767.0).astype(np.int16)
253
+ buf = io.BytesIO()
254
+ with wave.open(buf, "wb") as wv:
255
+ wv.setnchannels(1)
256
+ wv.setsampwidth(2)
257
+ wv.setframerate(sample_rate)
258
+ wv.writeframes(s16.tobytes())
259
+ return buf.getvalue()
260
+
261
+
262
+ def _normalize_wav_f32(arr: np.ndarray) -> np.ndarray:
263
+ a = np.asarray(arr, dtype=np.float32).reshape(-1)
264
+ if a.size == 0:
265
+ return a
266
+ mx = float(np.max(np.abs(a)))
267
+ if mx > 1.5:
268
+ a = a / 32768.0
269
+ elif mx > 1.01:
270
+ a = np.clip(a, -1.0, 1.0)
271
+ return a
272
+
273
+
274
+ def _is_valid(wav: np.ndarray, sr: int) -> bool:
275
+ n = wav.shape[0]
276
+ if n == 0:
277
+ return False
278
+ duration = n / float(sr)
279
+ if duration < _MIN_DURATION_SEC or duration > _MAX_DURATION_SEC:
280
+ return False
281
+ rms = float(np.sqrt(np.mean(np.square(wav))))
282
+ if not np.isfinite(rms) or rms < _MIN_RMS:
283
+ return False
284
+ peak = float(np.max(np.abs(wav)))
285
+ if not np.isfinite(peak) or peak > _MAX_ABSOLUTE:
286
+ return False
287
+ return True
288
+
289
+
290
+ def _validity_diagnostics(wav: np.ndarray, sr: int) -> str:
291
+ n = wav.shape[0]
292
+ if n == 0:
293
+ return "empty"
294
+ d = n / float(sr)
295
+ rms = float(np.sqrt(np.mean(np.square(wav)))) if n else 0.0
296
+ peak = float(np.max(np.abs(wav))) if n else 0.0
297
+ return f"duration_s={d:.3f} rms={rms:.4f} peak={peak:.4f}"
298
+
299
+
300
+
301
+ def _parse_instruction(instruction: str) -> dict[str, str]:
302
+ result: dict[str, str] = {}
303
+ for part in instruction.split("|"):
304
+ part = part.strip()
305
+ if ":" in part:
306
+ k, v = part.split(":", 1)
307
+ result[k.strip().lower()] = v.strip().lower()
308
+ return result
309
+
310
+
311
+ _GENDER_PHRASE = {
312
+ "male": "male", "female": "female", "neutral": "gender-neutral",
313
+ }
314
+ _PITCH_PHRASE = {
315
+ "low": "deep low-pitched voice", "mid": "medium natural pitch", "high": "high-pitched voice",
316
+ }
317
+ _SPEED_PHRASE = {
318
+ "slow": "slow deliberate pace", "normal": "natural conversational pace", "fast": "brisk fast pace",
319
+ }
320
+ _AGE_PHRASE = {
321
+ "child": "child", "young_adult": "young adult", "adult": "adult", "senior": "elderly senior",
322
+ }
323
+ _EMOTION_PHRASE = {
324
+ "neutral": "neutral composed delivery",
325
+ "happy": "cheerful happy upbeat warm",
326
+ "sad": "sorrowful sad subdued downcast",
327
+ "angry": "firm angry forceful assertive tense",
328
+ "calm": "calm relaxed measured peaceful unhurried",
329
+ "excited": "excited enthusiastic energetic lively",
330
+ "serious": "serious grave deliberate weighty",
331
+ "fearful": "nervous fearful hesitant trembling",
332
+ }
333
+ _TONE_PHRASE = {
334
+ "warm": "warm", "cold": "cold detached", "friendly": "friendly",
335
+ "formal": "formal", "casual": "casual", "authoritative": "authoritative commanding",
336
+ }
337
+ _ACCENT_PHRASE = {
338
+ "us": "standard American English accent with rhotic r sounds",
339
+ "uk": "standard British English accent with non-rhotic received pronunciation",
340
+ "au": "Australian English accent",
341
+ "in": "Indian English accent",
342
+ "neutral": "neutral international English accent",
343
+ "other": "non-native English accent",
344
+ }
345
+
346
+
347
+ def _build_natural_preamble(parsed: dict[str, str]) -> str:
348
+ gender = _GENDER_PHRASE.get(parsed.get("gender", ""), "")
349
+ age = _AGE_PHRASE.get(parsed.get("age_group", ""), "")
350
+ pitch = _PITCH_PHRASE.get(parsed.get("pitch", ""), "")
351
+ speed = _SPEED_PHRASE.get(parsed.get("speed", ""), "")
352
+ emotion = _EMOTION_PHRASE.get(parsed.get("emotion", ""), "")
353
+ tone = _TONE_PHRASE.get(parsed.get("tone", ""), "")
354
+ accent = _ACCENT_PHRASE.get(parsed.get("accent", ""), "")
355
+
356
+ parts: list[str] = []
357
+
358
+ # Gender-first to avoid timbre drift on emotion-heavy prompts
359
+ identity = " ".join(p for p in [gender, age] if p)
360
+ if identity:
361
+ parts.append(f"a {identity} voice")
362
+ if emotion:
363
+ parts.append(emotion)
364
+ if accent:
365
+ parts.append(f"speaking with a {accent}")
366
+ if pitch:
367
+ parts.append(pitch)
368
+ if speed:
369
+ parts.append(speed)
370
+ if tone:
371
+ parts.append(f"{tone} tone")
372
+
373
+ if not parts:
374
+ return ""
375
+ preamble = "Speak as " + ", ".join(parts) + "."
376
+ return preamble + " Use natural human prosody with realistic breath placement and varied intonation."
377
+
378
+
379
+ def _enhance_instruction(instruction: str) -> str:
380
+ parsed = _parse_instruction(instruction)
381
+ if not parsed:
382
+ return instruction
383
+ preamble = _build_natural_preamble(parsed)
384
+ if not preamble:
385
+ return instruction
386
+ return f"{preamble} {instruction}"
387
+
388
+
389
+ _NUM_WORDS = {
390
+ "0": "zero", "1": "one", "2": "two", "3": "three", "4": "four",
391
+ "5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine",
392
+ "10": "ten", "11": "eleven", "12": "twelve", "13": "thirteen",
393
+ "14": "fourteen", "15": "fifteen", "16": "sixteen", "17": "seventeen",
394
+ "18": "eighteen", "19": "nineteen", "20": "twenty", "30": "thirty",
395
+ "40": "forty", "50": "fifty", "60": "sixty", "70": "seventy",
396
+ "80": "eighty", "90": "ninety", "100": "one hundred",
397
+ }
398
+ _ABBREV = {
399
+ "Mr.": "Mister", "Mrs.": "Missus", "Dr.": "Doctor", "St.": "Saint",
400
+ "etc.": "et cetera", "vs.": "versus", "approx.": "approximately",
401
+ "dept.": "department", "govt.": "government", "mgr.": "manager",
402
+ }
403
+
404
+
405
+ def _normalize_text_for_tts(text: str) -> str:
406
+ import re
407
+
408
+ # Expand known abbreviations
409
+ for abbr, expansion in _ABBREV.items():
410
+ text = text.replace(abbr, expansion)
411
+
412
+ # Expand $N / £N / €N → "N dollars/pounds/euros"
413
+ text = re.sub(r'\$(\d+)', lambda m: f"{_NUM_WORDS.get(m.group(1), m.group(1))} dollars", text)
414
+ text = re.sub(r'£(\d+)', lambda m: f"{_NUM_WORDS.get(m.group(1), m.group(1))} pounds", text)
415
+ text = re.sub(r'€(\d+)', lambda m: f"{_NUM_WORDS.get(m.group(1), m.group(1))} euros", text)
416
+
417
+ # Expand standalone small integers (not part of larger numbers)
418
+ text = re.sub(
419
+ r'\b(\d{1,2})\b',
420
+ lambda m: _NUM_WORDS.get(m.group(1), m.group(1)),
421
+ text,
422
+ )
423
+
424
+ # Add comma pause before coordinating conjunctions in long sentences
425
+ text = re.sub(r'(?<!\,)\s+(but|however|although|though|yet)\s+', r', \1 ', text, flags=re.IGNORECASE)
426
+
427
+ return text.strip()
428
+
429
+
430
+ def _score_wer(wav: np.ndarray, sr: int, target_text: str, whisper_model: Any) -> float:
431
+ if whisper_model is None:
432
+ return 0.5
433
+ try:
434
+ import librosa
435
+
436
+ wav16 = librosa.resample(wav.astype(np.float32), orig_sr=sr, target_sr=16000)
437
+ result = whisper_model.transcribe(wav16, language="en", fp16=False)
438
+ transcript = (result.get("text") or "").strip().lower()
439
+ ref = target_text.strip().lower()
440
+ ref_w = ref.split()
441
+ hyp_w = transcript.split()
442
+ if not ref_w:
443
+ return 1.0 if not hyp_w else 0.0
444
+ n, m = len(ref_w), len(hyp_w)
445
+ prev = list(range(m + 1))
446
+ for i in range(1, n + 1):
447
+ curr = [i] + [0] * m
448
+ for j in range(1, m + 1):
449
+ cost = 0 if ref_w[i - 1] == hyp_w[j - 1] else 1
450
+ curr[j] = min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost)
451
+ prev = curr
452
+ wer = min(1.0, prev[m] / n)
453
+ return max(0.0, 1.0 - wer)
454
+ except Exception:
455
+ return 0.5
456
+
457
+
458
+
459
+ def _try_load_punct_model() -> Any:
460
+ """
461
+ Load deepmultilingualpunctuation PunctuationModel for restoring commas/periods
462
+ to unpunctuated input text before TTS synthesis. Improves prosody and naturalness
463
+ dramatically for run-on text (e.g. raw literary/OCR input).
464
+ Install: pip install deepmultilingualpunctuation
465
+ Returns the model on success, None if unavailable.
466
+ """
467
+ try:
468
+ from deepmultilingualpunctuation import PunctuationModel # type: ignore[import]
469
+ model = PunctuationModel()
470
+ print("[miner] PunctuationModel loaded for text pre-processing", flush=True)
471
+ return model
472
+ except Exception as e:
473
+ print(f"[miner] PunctuationModel unavailable ({e}); punctuation restoration skipped", flush=True)
474
+ return None
475
+
476
+
477
+ def _restore_punctuation(text: str, punct_model: Any) -> str:
478
+ """
479
+ Restore punctuation to text that lacks commas/periods.
480
+ Only applies the model when the text appears to lack punctuation
481
+ (fewer than 1 punctuation mark per 80 characters), so already
482
+ well-punctuated inputs are passed through unchanged.
483
+ Falls back to original text on any error.
484
+ """
485
+ if punct_model is None:
486
+ return text
487
+ stripped = text.strip()
488
+ if not stripped:
489
+ return text
490
+ punct_chars = sum(1 for c in stripped if c in ".,:;!?")
491
+ density = punct_chars / max(len(stripped), 1)
492
+ if density >= 1 / 80:
493
+ return text
494
+ try:
495
+ result: str = punct_model.restore_punctuation(stripped)
496
+ print(
497
+ f"[miner] punctuation restored: {len(stripped)}→{len(result)} chars",
498
+ flush=True,
499
+ )
500
+ return result
501
+ except Exception as e:
502
+ print(f"[miner] punctuation restoration failed ({e}); using original", flush=True)
503
+ return text
504
+
505
+
506
+ _VOICE_TRAIT_ENUMS: dict[str, list[str]] = {
507
+ "gender": ["male", "female", "neutral"],
508
+ "pitch": ["low", "mid", "high"],
509
+ "speed": ["slow", "normal", "fast"],
510
+ "age_group": ["child", "young_adult", "adult", "senior"],
511
+ "emotion": ["neutral", "happy", "sad", "angry", "calm", "excited", "serious", "fearful"],
512
+ "tone": ["warm", "cold", "friendly", "formal", "casual", "authoritative"],
513
+ "accent": ["us", "uk", "au", "in", "neutral", "other"],
514
+ }
515
+ _ORDINAL_TRAITS = {"pitch", "speed", "age_group"}
516
+
517
+ _AI_COMPARE_SYSTEM = """You are an expert TTS evaluator. You will receive N audio candidates, a target instruction, and the target text.
518
+
519
+ For EACH candidate evaluate:
520
+ - transcription: exact words spoken, lowercased, punctuation preserved (string)
521
+ - gender: one of [male, female, neutral]
522
+ - pitch: one of [low, mid, high]
523
+ - speed: one of [slow, normal, fast]
524
+ - age_group: one of [child, young_adult, adult, senior]
525
+ - emotion: one of [neutral, happy, sad, angry, calm, excited, serious, fearful]
526
+ - tone: one of [warm, cold, friendly, formal, casual, authoritative]
527
+ - accent: one of [us, uk, au, in, neutral, other]
528
+ - naturalness_score: integer 1-5 (1=very robotic, 5=indistinguishable from human)
529
+
530
+ Then set "best" to the 0-based index of the candidate that best matches the instruction and sounds most natural.
531
+
532
+ Return ONLY valid JSON in this exact shape (no markdown):
533
+ {
534
+ "candidates": [
535
+ {"transcription": "...", "gender": "...", "pitch": "...", "speed": "...", "age_group": "...", "emotion": "...", "tone": "...", "accent": "...", "naturalness_score": 4},
536
+ ...
537
+ ],
538
+ "best": 0
539
+ }"""
540
+
541
+
542
+ class AIAudioJudge:
543
+
544
+ def __init__(self, api_key: str, model: str = AI_AUDIO_MODEL) -> None:
545
+ import requests as _req
546
+ self._api_key = api_key
547
+ self._model = model
548
+ self._session = _req.Session()
549
+ self._session.headers.update({
550
+ "Authorization": f"Bearer {api_key}",
551
+ "Content-Type": "application/json",
552
+ })
553
+ self._api_ok = False
554
+ self._api_error: str = ""
555
+ self._probe()
556
+
557
+ def _probe(self) -> None:
558
+ import base64
559
+ try:
560
+ r = self._session.post(
561
+ "https://api.openai.com/v1/chat/completions",
562
+ json={"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "hi"}], "max_tokens": 1},
563
+ timeout=15,
564
+ )
565
+ r.raise_for_status()
566
+ print("[miner] scorer-1: API key OK", flush=True)
567
+ except Exception as e:
568
+ self._api_error = f"key_check: {e}"
569
+ print(f"[miner] scorer-1: API key check FAILED ({e})", flush=True)
570
+ return
571
+
572
+ try:
573
+ silent = np.zeros(1600, dtype=np.int16) # 0.1s silence @ 16kHz
574
+ buf = io.BytesIO()
575
+ with wave.open(buf, "wb") as wf:
576
+ wf.setnchannels(1); wf.setsampwidth(2); wf.setframerate(16000)
577
+ wf.writeframes(silent.tobytes())
578
+ b64 = base64.b64encode(buf.getvalue()).decode("ascii")
579
+ r = self._session.post(
580
+ "https://api.openai.com/v1/chat/completions",
581
+ json={
582
+ "model": self._model,
583
+ "messages": [{"role": "user", "content": [
584
+ {"type": "input_audio", "input_audio": {"data": b64, "format": "wav"}},
585
+ {"type": "text", "text": "Say ok"},
586
+ ]}],
587
+ "max_tokens": 1,
588
+ },
589
+ timeout=30,
590
+ )
591
+ r.raise_for_status()
592
+ self._api_ok = True
593
+ print(f"[miner] scorer-1: {self._model} probe OK — AI scoring enabled", flush=True)
594
+ except Exception as e:
595
+ self._api_error = f"audio_model: {e}"
596
+ print(f"[miner] scorer-1: {self._model} probe FAILED ({e})", flush=True)
597
+
598
+ @staticmethod
599
+ def _wav_to_base64(wav: np.ndarray, sr: int) -> str:
600
+ import base64
601
+ pcm16 = np.clip(wav * 32767, -32768, 32767).astype(np.int16)
602
+ buf = io.BytesIO()
603
+ with wave.open(buf, "wb") as wf:
604
+ wf.setnchannels(1)
605
+ wf.setsampwidth(2)
606
+ wf.setframerate(sr)
607
+ wf.writeframes(pcm16.tobytes())
608
+ return base64.b64encode(buf.getvalue()).decode("ascii")
609
+
610
+ def judge_candidates(
611
+ self,
612
+ candidates: list[tuple[np.ndarray, int]],
613
+ target_text: str,
614
+ instruction: str,
615
+ ) -> tuple[int, list[dict[str, Any]]]:
616
+ """
617
+ Send all candidates in one AI call.
618
+ Returns (best_index, list_of_trait_dicts_per_candidate).
619
+ """
620
+ import json as _json
621
+
622
+ content: list[dict] = []
623
+ for i, (wav, sr) in enumerate(candidates):
624
+ content.append({"type": "text", "text": f"Candidate {i}:"})
625
+ content.append({"type": "input_audio", "input_audio": {
626
+ "data": self._wav_to_base64(wav, sr), "format": "wav",
627
+ }})
628
+ content.append({"type": "text", "text": f"Target instruction: {instruction}"})
629
+ content.append({"type": "text", "text": f"Target text: {target_text}"})
630
+
631
+ body = {
632
+ "model": self._model,
633
+ "modalities": ["text"],
634
+ "messages": [
635
+ {"role": "system", "content": _AI_COMPARE_SYSTEM},
636
+ {"role": "user", "content": content},
637
+ ],
638
+ "temperature": 0.0,
639
+ "max_tokens": 800,
640
+ }
641
+ resp = self._session.post(
642
+ "https://api.openai.com/v1/chat/completions", json=body, timeout=120
643
+ )
644
+ if not resp.ok:
645
+ raise RuntimeError(f"{resp.status_code}: {resp.text[:200]}")
646
+ raw = (resp.json()["choices"][0]["message"]["content"] or "").strip()
647
+ if "```" in raw:
648
+ for part in raw.split("```"):
649
+ p = part.strip()
650
+ if p.startswith("json"):
651
+ p = p[4:].strip()
652
+ if p.startswith("{"):
653
+ raw = p
654
+ break
655
+ try:
656
+ data = _json.loads(raw)
657
+ except _json.JSONDecodeError:
658
+ data = {}
659
+
660
+ fallbacks = {
661
+ "gender": "neutral", "pitch": "mid", "speed": "normal", "age_group": "adult",
662
+ "emotion": "neutral", "tone": "casual", "accent": "neutral",
663
+ }
664
+ trait_list: list[dict[str, Any]] = []
665
+ for raw_c in (data.get("candidates") or []):
666
+ out: dict[str, Any] = {"transcription": str(raw_c.get("transcription") or "").strip()}
667
+ for k, enum in _VOICE_TRAIT_ENUMS.items():
668
+ v = str(raw_c.get(k) or "").strip().lower().replace(" ", "_").replace("-", "_")
669
+ out[k] = v if v in enum else fallbacks[k]
670
+ try:
671
+ out["naturalness_score"] = float(max(1, min(5, int(raw_c.get("naturalness_score", 3)))))
672
+ except (TypeError, ValueError):
673
+ out["naturalness_score"] = 3.0
674
+ trait_list.append(out)
675
+
676
+ while len(trait_list) < len(candidates):
677
+ trait_list.append({**fallbacks, "transcription": "", "naturalness_score": 3.0})
678
+
679
+ try:
680
+ ai_best = int(data.get("best", 0))
681
+ if not (0 <= ai_best < len(candidates)):
682
+ ai_best = 0
683
+ except (TypeError, ValueError):
684
+ ai_best = 0
685
+
686
+ return ai_best, trait_list
687
+
688
+
689
+ # ---------------------------------------------------------------------------
690
+ # Qwen2-Audio-7B-Instruct scorer (free local fallback)
691
+ # ---------------------------------------------------------------------------
692
+
693
+
694
+ def _ai_score_element(key: str, expected: str, actual: str) -> float:
695
+ """Mirror validator's `score_element`: ordinal partial credit for pitch/speed/age_group."""
696
+ enum = _VOICE_TRAIT_ENUMS.get(key)
697
+ if not enum:
698
+ return 1.0 if expected == actual else 0.0
699
+ if key in _ORDINAL_TRAITS:
700
+ try:
701
+ i, j = enum.index(str(expected)), enum.index(str(actual))
702
+ except ValueError:
703
+ return 0.0
704
+ d = abs(i - j)
705
+ return 1.0 if d == 0 else (0.5 if d == 1 else 0.0)
706
+ return 1.0 if expected == actual else 0.0
707
+
708
+
709
+ def _wer_simple(reference: str, hypothesis: str) -> float:
710
+ import re
711
+ pat = re.compile(r"\w+", re.UNICODE)
712
+ ref = pat.findall((reference or "").lower())
713
+ hyp = pat.findall((hypothesis or "").lower())
714
+ if not ref:
715
+ return 0.0 if not hyp else 1.0
716
+ n, m = len(ref), len(hyp)
717
+ prev = list(range(m + 1))
718
+ for i in range(1, n + 1):
719
+ curr = [i] + [0] * m
720
+ for j in range(1, m + 1):
721
+ cost = 0 if ref[i - 1] == hyp[j - 1] else 1
722
+ curr[j] = min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost)
723
+ prev = curr
724
+ return min(1.0, prev[m] / n)
725
+
726
+
727
+ def _score_from_traits(
728
+ traits: dict[str, Any],
729
+ target_text: str,
730
+ parsed: dict[str, str],
731
+ ) -> tuple[float, dict[str, float]]:
732
+ """Compute validator-aligned score from already-extracted traits."""
733
+ script_s = max(0.0, 1.0 - _wer_simple(target_text, traits.get("transcription", "")))
734
+ nat_s = (float(traits.get("naturalness_score", 3.0)) - 1.0) / 4.0
735
+ elem_scores: dict[str, float] = {"script": script_s, "naturalness": nat_s}
736
+ for key in ("gender", "pitch", "speed", "age_group", "emotion", "tone", "accent"):
737
+ elem_scores[key] = _ai_score_element(key, parsed.get(key, ""), traits.get(key, ""))
738
+ wsum = sum(_VALIDATOR_WEIGHTS.values())
739
+ total = sum(_VALIDATOR_WEIGHTS[k] * elem_scores[k] for k in _VALIDATOR_WEIGHTS) / wsum
740
+ detail = {
741
+ "wer": script_s,
742
+ "gp": (elem_scores["gender"] + elem_scores["pitch"]) / 2.0,
743
+ "speed": elem_scores["speed"],
744
+ "nat": nat_s,
745
+ "age": elem_scores["age_group"],
746
+ "emo": elem_scores["emotion"],
747
+ "tone": elem_scores["tone"],
748
+ "accent": elem_scores["accent"],
749
+ }
750
+ return total, detail
751
+
752
+
753
+ def _score_fallback(wav: np.ndarray, sr: int, target_text: str, whisper_model: Any) -> tuple[float, dict[str, float]]:
754
+ """Whisper WER fallback when AI judge is unavailable."""
755
+ wer_s = _score_wer(wav, sr, target_text, whisper_model)
756
+ total = 0.30 * wer_s + 0.70 * 0.75
757
+ detail = {"wer": wer_s, "gp": 0.75, "speed": 0.75, "nat": 0.75, "age": 0.75, "emo": 0.75, "tone": 0.75, "accent": 0.75}
758
+ return total, detail
759
+
760
+
761
+
762
+
763
+ def _call_qwen(tts: Any, kwargs: dict) -> tuple[Any, Any]:
764
+ try:
765
+ return tts.generate_voice_design(**kwargs)
766
+ except TypeError:
767
+ for drop in (
768
+ ("max_new_tokens",),
769
+ ("max_new_tokens", "top_k"),
770
+ ("max_new_tokens", "top_k", "repetition_penalty"),
771
+ ("max_new_tokens", "top_k", "repetition_penalty", "top_p"),
772
+ ):
773
+ trimmed = {k: v for k, v in kwargs.items() if k not in drop}
774
+ try:
775
+ return tts.generate_voice_design(**trimmed)
776
+ except TypeError:
777
+ continue
778
+ raise RuntimeError("generate_voice_design failed with all kwarg combinations")
779
+
780
+
781
+ def _instantiate_qwen(
782
+ model_path: str,
783
+ device_map: str,
784
+ dtype_name: str,
785
+ *,
786
+ prefer_flash: bool,
787
+ ) -> Any:
788
+ """Load Qwen3TTSModel; use FlashAttention-2 when installed + CUDA + config, else SDPA."""
789
+ import torch
790
+ from qwen_tts import Qwen3TTSModel
791
+
792
+ use_device = device_map
793
+ if str(use_device).startswith("cuda") and not torch.cuda.is_available():
794
+ print("[miner] CUDA not available; using CPU (slow).", flush=True)
795
+ use_device = "cpu"
796
+ dn = dtype_name
797
+ if use_device == "cpu" and dn == "bfloat16":
798
+ dn = "float32"
799
+ print("[miner] CPU: float32 instead of bfloat16", flush=True)
800
+
801
+ torch_dtype = {"bfloat16": torch.bfloat16, "float16": torch.float16}.get(
802
+ dn, torch.float32
803
+ )
804
+
805
+ attn: str = "sdpa"
806
+ if prefer_flash and str(use_device).startswith("cuda"):
807
+ try:
808
+ import flash_attn # noqa: F401
809
+
810
+ attn = "flash_attention_2"
811
+ except ImportError:
812
+ print("[miner] flash-attn not importable; using sdpa", flush=True)
813
+
814
+ common = dict(
815
+ pretrained_model_name_or_path=model_path,
816
+ device_map=use_device,
817
+ dtype=torch_dtype,
818
+ attn_implementation=attn,
819
+ )
820
+ try:
821
+ tts = Qwen3TTSModel.from_pretrained(**common)
822
+ except Exception as e:
823
+ if attn == "flash_attention_2":
824
+ print(f"[miner] flash_attention_2 failed ({e!s}); retrying with sdpa", flush=True)
825
+ common["attn_implementation"] = "sdpa"
826
+ tts = Qwen3TTSModel.from_pretrained(**common)
827
+ else:
828
+ raise
829
+
830
+ if torch.cuda.is_available():
831
+ free, total = torch.cuda.mem_get_info()
832
+ print(
833
+ f"[miner] Qwen loaded ({common['attn_implementation']}) "
834
+ f"VRAM={(total - free) / 1e9:.1f}GB / {total / 1e9:.1f}GB",
835
+ flush=True,
836
+ )
837
+ else:
838
+ print(f"[miner] Qwen loaded ({common['attn_implementation']}) cpu", flush=True)
839
+ return tts
840
+
841
+
842
+ def _waves_to_mono(waves: Any, sr: Any) -> tuple[np.ndarray, int]:
843
+ first = waves[0] if isinstance(waves, (list, tuple)) else waves
844
+ if first is None:
845
+ raise ValueError("empty audio")
846
+ arr = np.asarray(first, dtype=np.float32)
847
+ if arr.ndim > 1:
848
+ arr = arr.mean(axis=1)
849
+ arr = _normalize_wav_f32(arr)
850
+ return arr, int(sr)
851
+
852
+
853
+ class Miner:
854
+ """
855
+ In-process Qwen3-TTS + sequential best-of-N with configurable weighted selection.
856
+ """
857
+
858
+ def __init__(self, path_hf_repo: Path) -> None:
859
+ self._root = Path(path_hf_repo).resolve()
860
+ cfg = _read_vocence_yaml(self._root)
861
+ runtime = cfg.get("runtime") or {}
862
+ generation = cfg.get("generation") or {}
863
+ limits = cfg.get("limits") or {}
864
+
865
+ self._language = str(runtime.get("default_language", "English"))
866
+ self._cap_instruction = int(limits.get("max_instruction_chars", 600))
867
+ self._cap_text = int(limits.get("max_text_chars", 2000))
868
+ self._max_new_tokens = int(generation.get("max_new_tokens") or _GEN_MAX_NEW_TOKENS)
869
+
870
+ self._temperature = _coerce_cfg_float(generation, "temperature", _GEN_TEMPERATURE)
871
+ self._top_p = _coerce_cfg_float(generation, "top_p", _GEN_TOP_P)
872
+ self._top_k = _coerce_cfg_int(generation, "top_k", _GEN_TOP_K)
873
+ self._repetition_penalty = _coerce_cfg_float(
874
+ generation, "repetition_penalty", _GEN_REPETITION_PENALTY
875
+ )
876
+ self._do_sample = _coerce_cfg_bool(generation, "do_sample", _GEN_DO_SAMPLE)
877
+ _di = generation.get("default_instruction")
878
+ self._default_instruction = (
879
+ str(_di).strip() if _di is not None and str(_di).strip() else ""
880
+ )
881
+
882
+ _local_root = _local_dir_for_downloads(self._root, runtime)
883
+ _hub = str(runtime.get("hub_model_id", DEFAULT_HUB_MODEL_ID))
884
+ model_path = ensure_qwen_model_present(
885
+ self._root,
886
+ os.environ.get("QWEN_TTS_MODEL")
887
+ or os.environ.get("VOCENCE_MODEL_PATH")
888
+ or runtime.get("model_id"),
889
+ _hub,
890
+ local_download_root=_local_root,
891
+ )
892
+ print(f"[miner] loading Qwen from: {model_path}", flush=True)
893
+
894
+ device_pref = str(runtime.get("device_preference", "cuda")).lower()
895
+ device_map = "cuda:0" if device_pref in ("cuda", "cuda:0") else device_pref
896
+ dtype_name = str(runtime.get("dtype", "bfloat16")).lower()
897
+
898
+ try:
899
+ import torch
900
+
901
+ if str(device_map).startswith("cuda") and not torch.cuda.is_available():
902
+ print("[miner] CUDA not available; will use CPU (very slow).", flush=True)
903
+ device_map = "cpu"
904
+ if dtype_name == "bfloat16":
905
+ dtype_name = "float32"
906
+ except ImportError:
907
+ pass
908
+
909
+ prefer_flash = bool(runtime.get("use_flash_attention_2", True))
910
+ try:
911
+ self._tts = _instantiate_qwen(
912
+ model_path, device_map, dtype_name, prefer_flash=prefer_flash
913
+ )
914
+ except Exception as e:
915
+ raise RuntimeError(
916
+ f"Qwen3TTSModel.from_pretrained failed: {e}\n{traceback.format_exc()}"
917
+ ) from e
918
+
919
+ try:
920
+ import whisper
921
+
922
+ size = str(runtime.get("whisper_model", "tiny"))
923
+ self._whisper = whisper.load_model(size)
924
+ print(f"[miner] whisper-{size} loaded for selection", flush=True)
925
+ except Exception as e:
926
+ print(f"[miner] whisper unavailable ({e}); selection falls back", flush=True)
927
+ self._whisper = None
928
+
929
+ self._punct_model = _try_load_punct_model()
930
+
931
+ # Scorer 1: AI judge
932
+ ai_key = os.environ.get("HUGGING_FACE_HUB_TOKEN", "")
933
+ if ai_key:
934
+ try:
935
+ self._ai: Any = AIAudioJudge(ai_key)
936
+ print(f"[miner] scorer-1: AI judge ready (model={AI_AUDIO_MODEL})", flush=True)
937
+ except Exception as e:
938
+ print(f"[miner] scorer-1: AI judge init failed ({e})", flush=True)
939
+ self._ai = None
940
+ else:
941
+ self._ai = None
942
+ print("[miner] scorer-1: AI judge skipped (HUGGING_FACE_HUB_TOKEN not set)", flush=True)
943
+
944
+ # Scorer 2: Whisper WER (fallback — already loaded above)
945
+ active = "AI-Judge" if (self._ai and self._ai._api_ok) else "Whisper-WER"
946
+ print(f"[miner] ready: best-of-3 (qwen×3); active scorer: {active}", flush=True)
947
+ wts = _VALIDATOR_WEIGHTS
948
+ print(
949
+ f"[miner] validator weights: script={wts['script']:.2f} nat={wts['naturalness']:.2f} "
950
+ f"gender={wts['gender']:.2f} speed={wts['speed']:.2f} emotion={wts['emotion']:.2f} "
951
+ f"age={wts['age_group']:.2f} pitch={wts['pitch']:.2f} accent={wts['accent']:.2f} "
952
+ f"tone={wts['tone']:.2f}",
953
+ flush=True,
954
+ )
955
+ print(
956
+ f"[miner] sampling: temperature={self._temperature} top_p={self._top_p} "
957
+ f"top_k={self._top_k} repetition_penalty={self._repetition_penalty} "
958
+ f"do_sample={self._do_sample}",
959
+ flush=True,
960
+ )
961
+ if self._default_instruction:
962
+ print(
963
+ "[miner] default_instruction: prepended to each request (per-key override: user wins)",
964
+ flush=True,
965
+ )
966
+
967
+ def __repr__(self) -> str:
968
+ return "Miner(best-of-3/qwen×3, in_process=True)"
969
+
970
+ def get_status(self) -> dict:
971
+ ai_ok = self._ai is not None and self._ai._api_ok
972
+ whisper_ok = self._whisper is not None
973
+ active = "ai-judge" if ai_ok else ("whisper-wer" if whisper_ok else "none")
974
+ ai_status = "ready" if ai_ok else (
975
+ f"api_error: {self._ai._api_error}" if self._ai is not None else "not configured"
976
+ )
977
+ return {
978
+ "scorer_ai": ai_status,
979
+ "scorer_whisper": "ready" if whisper_ok else "not available",
980
+ "active_scorer": active,
981
+ }
982
+
983
+ def warmup(self) -> None:
984
+ warm_text = "Warmup complete."
985
+ warm_inst = (
986
+ "gender: female | age_group: adult | pitch: mid | speed: normal "
987
+ "| emotion: neutral | tone: casual | accent: us"
988
+ )
989
+ inst = _merge_default_instruction(self._default_instruction, warm_inst)
990
+ if self._cap_instruction:
991
+ inst = inst[: self._cap_instruction]
992
+ kw = self._gen_kwargs(warm_text, inst, sampling=True)
993
+ t0 = time.time()
994
+ waves, sr = _call_qwen(self._tts, kw)
995
+ _waves_to_mono(waves, sr)
996
+ print(f"[miner] warmup ok in {time.time() - t0:.1f}s", flush=True)
997
+
998
+ def generate_wav(self, instruction: str, text: str) -> tuple[np.ndarray, int]:
999
+ text = text[: self._cap_text] if self._cap_text else text
1000
+ inst = _merge_default_instruction(self._default_instruction, instruction)
1001
+ if self._cap_instruction:
1002
+ inst = inst[: self._cap_instruction]
1003
+
1004
+ # Enrich text: punctuation restoration + number/abbreviation expansion.
1005
+ punct_text = _restore_punctuation(text, self._punct_model)
1006
+ rich_text = _normalize_text_for_tts(punct_text)
1007
+ rich_inst = _enhance_instruction(inst)
1008
+ parsed = _parse_instruction(inst)
1009
+ t0 = time.time()
1010
+
1011
+ # Naturalness variant suffixes — each candidate uses a different style hint
1012
+ # to maximize the chance one beats the source audio in pairwise comparison.
1013
+ _NAT_VARIANTS = [
1014
+ "",
1015
+ " Speak like a professional voice actor: warm, fluid delivery with natural pauses and breath.",
1016
+ " Conversational and human: avoid monotone, add subtle rhythm, stress key words naturally.",
1017
+ ]
1018
+
1019
+ # Phase 1: generate 3 Qwen candidates
1020
+ raw_candidates: list[tuple[np.ndarray, int, str]] = []
1021
+ first_rejected: tuple[np.ndarray, int] | None = None
1022
+
1023
+ def _qwen(tag: str, nat_suffix: str = "") -> None:
1024
+ nonlocal first_rejected
1025
+ candidate_inst = (rich_inst + nat_suffix)[: self._cap_instruction] if self._cap_instruction else (rich_inst + nat_suffix)
1026
+ kwargs = self._gen_kwargs(rich_text, candidate_inst, sampling=True)
1027
+ gen_t0 = time.time()
1028
+ try:
1029
+ waves, sr = _call_qwen(self._tts, kwargs)
1030
+ if time.time() - gen_t0 > _GEN_TIMEOUT_SEC:
1031
+ print(f"[{tag}] warning: synthesis exceeded timeout budget", flush=True)
1032
+ wav, sr_i = _waves_to_mono(waves, sr)
1033
+ if _is_valid(wav, sr_i):
1034
+ raw_candidates.append((wav, sr_i, tag))
1035
+ print(f"[{tag}] generated in {time.time()-t0:.1f}s", flush=True)
1036
+ else:
1037
+ if first_rejected is None:
1038
+ first_rejected = (wav, sr_i)
1039
+ print(f"[{tag}] validity failed: {_validity_diagnostics(wav, sr_i)}", flush=True)
1040
+ except Exception as e:
1041
+ print(f"[{tag}] synthesis error: {e}", flush=True)
1042
+
1043
+ _qwen("qwen-1", _NAT_VARIANTS[0])
1044
+ _qwen("qwen-2", _NAT_VARIANTS[1])
1045
+ _qwen("qwen-3", _NAT_VARIANTS[2])
1046
+
1047
+ if not raw_candidates:
1048
+ hint = ""
1049
+ if first_rejected is not None:
1050
+ w, s = first_rejected
1051
+ hint = (
1052
+ f" (first response: {_validity_diagnostics(w, s)}; "
1053
+ f"bounds: duration [{_MIN_DURATION_SEC},{_MAX_DURATION_SEC}]s, "
1054
+ f"peak≤{_MAX_ABSOLUTE}, rms≥{_MIN_RMS})"
1055
+ )
1056
+ raise RuntimeError(
1057
+ f"all synthesis attempts failed validity in {time.time()-t0:.1f}s{hint}"
1058
+ )
1059
+
1060
+ # Phase 2: AI judge → Whisper fallback
1061
+ scores: list[float] = []
1062
+ ai_best = 0
1063
+ best = 0
1064
+ scorer_used = "none"
1065
+
1066
+ if self._ai is not None and self._ai._api_ok:
1067
+ try:
1068
+ print(f"[scorer-1/ai] judging {len(raw_candidates)} candidates...", flush=True)
1069
+ audio_list = [(w, s) for w, s, _ in raw_candidates]
1070
+ ai_best, trait_list = self._ai.judge_candidates(audio_list, text, inst)
1071
+ for i, (wav, sr_i, tag) in enumerate(raw_candidates):
1072
+ total, detail = _score_from_traits(trait_list[i], text, parsed)
1073
+ scores.append(total)
1074
+ print(
1075
+ f"[scorer-1/ai][{tag}] score={total:.3f} wer={detail['wer']:.3f} "
1076
+ f"gp={detail['gp']:.3f} spd={detail['speed']:.3f} "
1077
+ f"nat={detail['nat']:.3f} age={detail['age']:.2f} "
1078
+ f"emo={detail['emo']:.2f} tone={detail['tone']:.2f} "
1079
+ f"accent={detail['accent']:.2f} elapsed={time.time()-t0:.1f}s",
1080
+ flush=True,
1081
+ )
1082
+ best = ai_best
1083
+ scorer_used = "ai-judge"
1084
+ except Exception as e:
1085
+ print(f"[scorer-1/ai] failed ({e}); falling back to Whisper...", flush=True)
1086
+
1087
+ if not scores:
1088
+ print(f"[scorer-2/whisper] judging {len(raw_candidates)} candidates...", flush=True)
1089
+ for wav, sr_i, tag in raw_candidates:
1090
+ total, detail = _score_fallback(wav, sr_i, text, self._whisper)
1091
+ scores.append(total)
1092
+ print(f"[scorer-2/whisper][{tag}] score={total:.3f} wer={detail['wer']:.3f} elapsed={time.time()-t0:.1f}s", flush=True)
1093
+ best = int(np.argmax(scores))
1094
+ scorer_used = "whisper-wer"
1095
+
1096
+ active_scores = scores
1097
+ print(
1098
+ f"[miner] best={raw_candidates[best][2]} score={active_scores[best]:.3f} "
1099
+ f"scorer={scorer_used} total={len(raw_candidates)} elapsed={time.time()-t0:.1f}s",
1100
+ flush=True,
1101
+ )
1102
+ return raw_candidates[best][0], raw_candidates[best][1]
1103
+
1104
+ def _gen_kwargs(self, text: Any, instruction: Any, *, sampling: bool) -> dict:
1105
+ kw: dict[str, Any] = dict(
1106
+ text=text,
1107
+ instruct=instruction,
1108
+ language=self._language,
1109
+ max_new_tokens=self._max_new_tokens,
1110
+ )
1111
+ if sampling:
1112
+ kw.update(
1113
+ do_sample=self._do_sample,
1114
+ temperature=self._temperature,
1115
+ top_p=self._top_p,
1116
+ top_k=self._top_k,
1117
+ repetition_penalty=self._repetition_penalty,
1118
+ )
1119
+ return kw
1120
+
1121
+
1122
+ _engine: Any = None
1123
+ _health: dict[str, Any] = {}
1124
+
1125
+
1126
+ def _run_dev_server() -> None:
1127
+ from contextlib import asynccontextmanager
1128
+
1129
+ import uvicorn
1130
+ from fastapi import Body, FastAPI, HTTPException, status
1131
+ from fastapi.responses import Response
1132
+ from pydantic import BaseModel
1133
+
1134
+ @asynccontextmanager
1135
+ async def _lifespan(_app: Any):
1136
+ global _engine, _health
1137
+ cfg = _read_vocence_yaml(REPO)
1138
+ default_sr = int((cfg.get("generation") or {}).get("sample_rate", 24000))
1139
+ _health = {"sample_rate": default_sr}
1140
+ try:
1141
+ _engine = Miner(REPO)
1142
+ _health["adapter"] = json.dumps(_engine.get_status())
1143
+ except Exception as e:
1144
+ _engine = None
1145
+ _health["adapter"] = json.dumps({"tts_engine": "not loaded"})
1146
+ _health["error"] = f"{type(e).__name__}: {e}"
1147
+ yield
1148
+ _engine = None
1149
+
1150
+ class HealthResponse(BaseModel):
1151
+ status: str
1152
+ model_loaded: bool
1153
+ sample_rate: Optional[int] = None
1154
+ adapter: Optional[str] = None
1155
+
1156
+ app = FastAPI(title="Vocence Qwen3-TTS (dev)", lifespan=_lifespan)
1157
+
1158
+ @app.get("/health", response_model=HealthResponse)
1159
+ async def health() -> HealthResponse:
1160
+ ok = _engine is not None
1161
+ err = _health.get("error")
1162
+ return HealthResponse(
1163
+ status="healthy" if ok else (f"unhealthy: {err}" if err else "unhealthy"),
1164
+ model_loaded=ok,
1165
+ sample_rate=_health.get("sample_rate"),
1166
+ adapter=_health.get("adapter", "qwen3-tts"),
1167
+ )
1168
+
1169
+ @app.post("/speak", response_class=Response, response_model=None)
1170
+ async def speak(
1171
+ text: str = Body(..., min_length=1, max_length=MAX_TEXT, embed=True),
1172
+ instruction: str = Body(..., min_length=1, max_length=MAX_INST, embed=True),
1173
+ ) -> Response:
1174
+ if _engine is None:
1175
+ raise HTTPException(
1176
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
1177
+ detail=f"TTS engine not loaded: {_health.get('error', 'unknown')}",
1178
+ )
1179
+ waveform, sample_rate = _engine.generate_wav(instruction=instruction, text=text)
1180
+ w = np.asarray(waveform)
1181
+ if w.ndim != 1 or w.size == 0:
1182
+ raise HTTPException(status_code=400, detail="invalid waveform")
1183
+ duration = float(w.shape[0]) / float(sample_rate)
1184
+ if duration <= 0 or duration > MAX_AUDIO_SEC:
1185
+ raise HTTPException(status_code=400, detail="invalid duration")
1186
+ return Response(content=_f32_to_wav_bytes(w, int(sample_rate)), media_type="audio/wav")
1187
+
1188
+ import logging
1189
+
1190
+ logging.basicConfig(level=logging.INFO)
1191
+ host = os.environ.get("HOST", "0.0.0.0")
1192
+ port = int(os.environ.get("PORT", "8765"))
1193
+ uvicorn.run(app, host=host, port=port)
1194
+
1195
+
1196
+ if __name__ == "__main__":
1197
+ _run_dev_server()