zziang commited on
Commit
cda1aee
·
verified ·
1 Parent(s): 1bf7d32

whisper probe: 6 low-voicing candidates

Browse files
Files changed (1) hide show
  1. kaggle/whisper_probe.py +144 -0
kaggle/whisper_probe.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Which whisper clips actually work as Ming prompts?
2
+
3
+ a01 was chosen by ear for its breathy delivery, but as a prompt it produces
4
+ hallucinated speech ("字幕by索兰娅" for 「后来店关了,歌还在。」), and the teacher
5
+ does this too, so it is not a distillation artefact. Six other low-voicing clips
6
+ were mined; this bakes each and asks two questions:
7
+
8
+ 1. does the clone say the right words (CER), and
9
+ 2. does it stay breathy (voicing of the output against the prompt's own)
10
+
11
+ A clip that speaks correctly but loses the whisper is a fail: the breathiness is
12
+ the reason we want it.
13
+
14
+ Outputs whisper_probe/{slot}_{i}.wav and metrics.json.
15
+ """
16
+ import json
17
+ import os
18
+ import sys
19
+ import time
20
+ import traceback
21
+ from pathlib import Path
22
+
23
+ import numpy as np
24
+
25
+ ROOT = Path(os.environ.get("WORK_ROOT", "/kaggle/working"))
26
+ REPO = ROOT / "Ming-3.0-tts"
27
+ MODEL = ROOT / "Ming-3.0-tts-0.5b"
28
+ BUNDLE = ROOT / "webfm-eval"
29
+ OUT = ROOT / "whisper_probe"
30
+ SEED = 20261031
31
+
32
+ LINES = [
33
+ "别急,先呼吸。",
34
+ "后来店关了,歌还在。",
35
+ "晚安,我们明天见。",
36
+ ]
37
+
38
+
39
+ def log(msg: str) -> None:
40
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
41
+
42
+
43
+ def patch_fp32() -> None:
44
+ for name in ("ming_tts.py", "modeling_bailingmm.py"):
45
+ p = REPO / name
46
+ s = p.read_text()
47
+ s = s.replace("torch_dtype=torch.bfloat16", "torch_dtype=torch.float32")
48
+ s = s.replace(".eval().to(torch.bfloat16).to(device)", ".eval().to(torch.float32).to(device)")
49
+ s = s.replace("dtype=torch.bfloat16", "dtype=torch.float32")
50
+ p.write_text(s)
51
+
52
+
53
+ def voicing(y: np.ndarray, sr: int) -> float:
54
+ """Periodicity of the strongest frames. Low means breathy, no pitch."""
55
+ win, hop = int(0.04 * sr), int(0.02 * sr)
56
+ if len(y) < win * 2:
57
+ return 0.0
58
+ frames = np.lib.stride_tricks.sliding_window_view(y, win)[::hop]
59
+ energy = (frames ** 2).mean(1)
60
+ idx = np.argsort(energy)[-max(1, int(len(energy) * 0.3)):]
61
+ lo, hi = int(sr / 400), int(sr / 70)
62
+ peaks = []
63
+ for f in frames[idx]:
64
+ f = f - f.mean()
65
+ ac = np.correlate(f, f, "full")[win - 1:]
66
+ if ac[0] <= 0:
67
+ continue
68
+ peaks.append(float(ac[lo:hi].max() / ac[0]))
69
+ return float(np.median(peaks)) if peaks else 0.0
70
+
71
+
72
+ def main() -> None:
73
+ import torch
74
+ import soundfile as sf
75
+ from transformers import pipeline
76
+
77
+ OUT.mkdir(parents=True, exist_ok=True)
78
+ sys.path.insert(0, str(REPO))
79
+ patch_fp32()
80
+ from ming_tts import MingTTS
81
+ sys.path.insert(0, str(BUNDLE / "eval"))
82
+ from score import load_t2s, score_row
83
+
84
+ table = load_t2s()
85
+ voices = json.loads((BUNDLE / "whisper/manifest.json").read_text())["voices"]
86
+ log(f"{len(voices)} whisper candidates x {len(LINES)} lines")
87
+
88
+ tts = MingTTS(str(MODEL), device="cuda", text_normalization=False)
89
+ rows = []
90
+ for v in voices:
91
+ wav_path = str(BUNDLE / v["wav"])
92
+ item = dict(v)
93
+ ces, vs, ws = [], [], []
94
+ for i, text in enumerate(LINES, 1):
95
+ try:
96
+ torch.manual_seed(SEED + i)
97
+ w = tts.synthesize(task="TTS", text=text, language_id="Chinese",
98
+ prompt_wav_path=wav_path, prompt_text=v["prompt_text"],
99
+ use_spk_emb=True, raw_text=True,
100
+ max_decode_steps=max(32, min(400, int(len(text) * 3.5))))
101
+ y = w.cpu().numpy().reshape(-1)
102
+ sf.write(str(OUT / f"{v['slot']}_{i}.wav"), y, 44100)
103
+ vs.append(voicing(y, 44100))
104
+ ws.append(round(y.size / 44100, 2))
105
+ item[f"sec_{i}"] = ws[-1]
106
+ except Exception:
107
+ log(f"{v['slot']} line {i} failed\n{traceback.format_exc()}")
108
+ item["voicing_out"] = float(np.mean(vs)) if vs else 0.0
109
+ item["seconds"] = ws
110
+ rows.append(item)
111
+ log(f"{v['slot']} src_v={v['voicing']:.2f} out_v={item['voicing_out']:.2f} "
112
+ f"sec={ws}")
113
+
114
+ asr = pipeline("automatic-speech-recognition", model="openai/whisper-small",
115
+ device=0, torch_dtype=torch.float16)
116
+
117
+ for r in rows:
118
+ ces = []
119
+ for i, text in enumerate(LINES, 1):
120
+ p = OUT / f"{r['slot']}_{i}.wav"
121
+ if not p.exists():
122
+ continue
123
+ y, _ = sf.read(p, dtype="float32")
124
+ out = asr({"array": y.astype(np.float32), "sampling_rate": 44100},
125
+ generate_kwargs={"language": "zh", "task": "transcribe"})
126
+ hyp = (out.get("text", "") if isinstance(out, dict) else str(out)).strip()
127
+ s = score_row({"text": text, "hyp_text": hyp}, table)
128
+ ces.append(s["cer_norm"])
129
+ r[f"hyp_{i}"] = hyp
130
+ r["cer"] = float(np.mean(ces)) if ces else 1.0
131
+ r["ok"] = bool(r["cer"] < 0.35 and r["voicing_out"] < 0.7)
132
+ log(f"{r['slot']} cer={r['cer']:.3f} v_out={r['voicing_out']:.2f} "
133
+ f"{'PASS' if r['ok'] else 'fail'} {r.get('hyp_1','')[:24]}")
134
+
135
+ rows.sort(key=lambda r: (not r["ok"], r["cer"]))
136
+ (OUT / "metrics.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1))
137
+ log("\n-- ranking --")
138
+ for r in rows:
139
+ log(f" {'✓' if r['ok'] else '✗'} cer={r['cer']:.2f} v {r['voicing']:.2f}->"
140
+ f"{r['voicing_out']:.2f} {r['artist'][:14]:<14} {r['prompt_text'][:18]}")
141
+
142
+
143
+ if __name__ == "__main__":
144
+ main()