zziang commited on
Commit
d8274ac
·
verified ·
1 Parent(s): 0354c22

style probe: FREEFORM instruction and BASIC controls

Browse files
Files changed (1) hide show
  1. kaggle/style_probe.py +148 -0
kaggle/style_probe.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Can whispering be instructed instead of cloned?
2
+
3
+ Six low-voicing clips all failed as prompts: either the clone lost the breath
4
+ (buy1take2, voicing 0.34 -> 0.71) or it kept the breath and invented words
5
+ (Rainnight, CER 0.53). Whisper has no F0, and the model's voice conditioning
6
+ leans on periodicity, so a 6 s breathy prompt is not enough to carry it.
7
+
8
+ The repo exposes two text-side controls that were never tried here:
9
+ FREEFORM a free-text instruction, e.g. "用气声耳语,很轻"
10
+ BASIC speed/pitch/volume from fixed vocabularies
11
+
12
+ Both keep a *working* prompt (a08) and move the style into the text, which is
13
+ the opposite of what we were doing. Success means low CER *and* low voicing of
14
+ the output - a soft normal voice is not a whisper.
15
+
16
+ Writes style_probe/*.wav and metrics.json.
17
+ """
18
+ import json
19
+ import os
20
+ import sys
21
+ import time
22
+ import traceback
23
+ from pathlib import Path
24
+
25
+ import numpy as np
26
+
27
+ ROOT = Path(os.environ.get("WORK_ROOT", "/kaggle/working"))
28
+ REPO = ROOT / "Ming-3.0-tts"
29
+ MODEL = ROOT / "Ming-3.0-tts-0.5b"
30
+ BUNDLE = ROOT / "webfm-eval"
31
+ OUT = ROOT / "style_probe"
32
+ SEED = 20261031
33
+ VOICE = "a08"
34
+
35
+ LINES = ["后来店关了,歌还在。", "晚安,我们明天见。", "别急,先呼吸。"]
36
+
37
+ TRIALS = [
38
+ ("plain", {}),
39
+ ("freeform_whisper", {"task": "FREEFORM",
40
+ "instruction": "用气声耳语,很轻,像在深夜贴着耳朵说话。"}),
41
+ ("freeform_soft", {"task": "FREEFORM",
42
+ "instruction": "轻声说,音量很低,气息多,接近耳语。"}),
43
+ ("basic_low", {"task": "BASIC", "speed": "慢速", "pitch": "低", "volume": "低"}),
44
+ ("freeform_basic", {"task": "FREEFORM",
45
+ "instruction": "用耳语说,很慢,很低,几乎只剩气息。"}),
46
+ ]
47
+
48
+
49
+ def log(msg: str) -> None:
50
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
51
+
52
+
53
+ def patch_fp32() -> None:
54
+ for name in ("ming_tts.py", "modeling_bailingmm.py"):
55
+ p = REPO / name
56
+ s = p.read_text()
57
+ s = s.replace("torch_dtype=torch.bfloat16", "torch_dtype=torch.float32")
58
+ s = s.replace(".eval().to(torch.bfloat16).to(device)", ".eval().to(torch.float32).to(device)")
59
+ s = s.replace("dtype=torch.bfloat16", "dtype=torch.float32")
60
+ p.write_text(s)
61
+
62
+
63
+ def voicing(y, sr):
64
+ win, hop = int(0.04 * sr), int(0.02 * sr)
65
+ if len(y) < win * 2:
66
+ return 0.0
67
+ frames = np.lib.stride_tricks.sliding_window_view(y, win)[::hop]
68
+ energy = (frames ** 2).mean(1)
69
+ idx = np.argsort(energy)[-max(1, int(len(energy) * 0.3)):]
70
+ lo, hi = int(sr / 400), int(sr / 70)
71
+ peaks = []
72
+ for f in frames[idx]:
73
+ f = f - f.mean()
74
+ ac = np.correlate(f, f, "full")[win - 1:]
75
+ if ac[0] > 0:
76
+ peaks.append(float(ac[lo:hi].max() / ac[0]))
77
+ return float(np.median(peaks)) if peaks else 0.0
78
+
79
+
80
+ def main() -> None:
81
+ import torch
82
+ import soundfile as sf
83
+ from transformers import pipeline
84
+
85
+ OUT.mkdir(parents=True, exist_ok=True)
86
+ sys.path.insert(0, str(REPO))
87
+ patch_fp32()
88
+ from ming_tts import MingTTS
89
+ import tts_tasks
90
+ sys.path.insert(0, str(BUNDLE / "eval"))
91
+ from score import load_t2s, score_row
92
+
93
+ table = load_t2s()
94
+ voices = {v["slot"]: v for v in
95
+ json.loads((BUNDLE / "mined/manifest.json").read_text())["voices"]}
96
+ v = voices[VOICE]
97
+
98
+ tts = MingTTS(str(MODEL), device="cuda", text_normalization=False)
99
+ rows = []
100
+ for name, kw in TRIALS:
101
+ item = {"trial": name, "kwargs": {k: str(x) for k, x in kw.items()}}
102
+ ws, vs = [], []
103
+ for i, text in enumerate(LINES, 1):
104
+ try:
105
+ torch.manual_seed(SEED + i)
106
+ w = tts.synthesize(text=text, language_id="Chinese",
107
+ prompt_wav_path=str(BUNDLE / v["wav"]),
108
+ prompt_text=v["prompt_text"], use_spk_emb=True,
109
+ raw_text=True,
110
+ max_decode_steps=max(32, min(400, int(len(text) * 3.5))),
111
+ **kw)
112
+ y = w.cpu().numpy().reshape(-1)
113
+ sf.write(str(OUT / f"{name}_{i}.wav"), y, 44100)
114
+ ws.append(round(y.size / 44100, 2))
115
+ vs.append(voicing(y, 44100))
116
+ except Exception:
117
+ log(f"{name} line {i} failed\n{traceback.format_exc()}")
118
+ item["seconds"] = ws
119
+ item["voicing"] = float(np.mean(vs)) if vs else 0.0
120
+ rows.append(item)
121
+ log(f"{name}: v_out={item['voicing']:.2f} sec={ws}")
122
+
123
+ asr = pipeline("automatic-speech-recognition", model="openai/whisper-small",
124
+ device=0, torch_dtype=torch.float16)
125
+ for r in rows:
126
+ ces = []
127
+ for i, text in enumerate(LINES, 1):
128
+ p = OUT / f"{r['trial']}_{i}.wav"
129
+ if not p.exists():
130
+ continue
131
+ y, _ = sf.read(p, dtype="float32")
132
+ out = asr({"array": y.astype(np.float32), "sampling_rate": 44100},
133
+ generate_kwargs={"language": "zh", "task": "transcribe"})
134
+ hyp = (out.get("text", "") if isinstance(out, dict) else str(out)).strip()
135
+ ces.append(score_row({"text": text, "hyp_text": hyp}, table)["cer_norm"])
136
+ r[f"hyp_{i}"] = hyp
137
+ r["cer"] = float(np.mean(ces)) if ces else 1.0
138
+ log(f"{r['trial']} cer={r['cer']:.3f} v={r['voicing']:.2f} {r.get('hyp_1','')[:22]}")
139
+
140
+ rows.sort(key=lambda r: r["cer"])
141
+ (OUT / "metrics.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1))
142
+ log("\n-- summary (CER low is good; voicing low means breathy) --")
143
+ for r in rows:
144
+ log(f" cer={r['cer']:.2f} v={r['voicing']:.2f} {r['trial']}")
145
+
146
+
147
+ if __name__ == "__main__":
148
+ main()