webfm-eval / kaggle /whisper_probe.py
zziang's picture
whisper probe: 6 low-voicing candidates
cda1aee verified
Raw History Blame Contribute Delete
5.42 kB
"""Which whisper clips actually work as Ming prompts?
a01 was chosen by ear for its breathy delivery, but as a prompt it produces
hallucinated speech ("字幕by索兰娅" for 「后来店关了,歌还在。」), and the teacher
does this too, so it is not a distillation artefact. Six other low-voicing clips
were mined; this bakes each and asks two questions:
1. does the clone say the right words (CER), and
2. does it stay breathy (voicing of the output against the prompt's own)
A clip that speaks correctly but loses the whisper is a fail: the breathiness is
the reason we want it.
Outputs whisper_probe/{slot}_{i}.wav and metrics.json.
"""
import json
import os
import sys
import time
import traceback
from pathlib import Path
import numpy as np
ROOT = Path(os.environ.get("WORK_ROOT", "/kaggle/working"))
REPO = ROOT / "Ming-3.0-tts"
MODEL = ROOT / "Ming-3.0-tts-0.5b"
BUNDLE = ROOT / "webfm-eval"
OUT = ROOT / "whisper_probe"
SEED = 20261031
LINES = [
"别急,先呼吸。",
"后来店关了,歌还在。",
"晚安,我们明天见。",
]
def log(msg: str) -> None:
print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
def patch_fp32() -> None:
for name in ("ming_tts.py", "modeling_bailingmm.py"):
p = REPO / name
s = p.read_text()
s = s.replace("torch_dtype=torch.bfloat16", "torch_dtype=torch.float32")
s = s.replace(".eval().to(torch.bfloat16).to(device)", ".eval().to(torch.float32).to(device)")
s = s.replace("dtype=torch.bfloat16", "dtype=torch.float32")
p.write_text(s)
def voicing(y: np.ndarray, sr: int) -> float:
"""Periodicity of the strongest frames. Low means breathy, no pitch."""
win, hop = int(0.04 * sr), int(0.02 * sr)
if len(y) < win * 2:
return 0.0
frames = np.lib.stride_tricks.sliding_window_view(y, win)[::hop]
energy = (frames ** 2).mean(1)
idx = np.argsort(energy)[-max(1, int(len(energy) * 0.3)):]
lo, hi = int(sr / 400), int(sr / 70)
peaks = []
for f in frames[idx]:
f = f - f.mean()
ac = np.correlate(f, f, "full")[win - 1:]
if ac[0] <= 0:
continue
peaks.append(float(ac[lo:hi].max() / ac[0]))
return float(np.median(peaks)) if peaks else 0.0
def main() -> None:
import torch
import soundfile as sf
from transformers import pipeline
OUT.mkdir(parents=True, exist_ok=True)
sys.path.insert(0, str(REPO))
patch_fp32()
from ming_tts import MingTTS
sys.path.insert(0, str(BUNDLE / "eval"))
from score import load_t2s, score_row
table = load_t2s()
voices = json.loads((BUNDLE / "whisper/manifest.json").read_text())["voices"]
log(f"{len(voices)} whisper candidates x {len(LINES)} lines")
tts = MingTTS(str(MODEL), device="cuda", text_normalization=False)
rows = []
for v in voices:
wav_path = str(BUNDLE / v["wav"])
item = dict(v)
ces, vs, ws = [], [], []
for i, text in enumerate(LINES, 1):
try:
torch.manual_seed(SEED + i)
w = tts.synthesize(task="TTS", text=text, language_id="Chinese",
prompt_wav_path=wav_path, prompt_text=v["prompt_text"],
use_spk_emb=True, raw_text=True,
max_decode_steps=max(32, min(400, int(len(text) * 3.5))))
y = w.cpu().numpy().reshape(-1)
sf.write(str(OUT / f"{v['slot']}_{i}.wav"), y, 44100)
vs.append(voicing(y, 44100))
ws.append(round(y.size / 44100, 2))
item[f"sec_{i}"] = ws[-1]
except Exception:
log(f"{v['slot']} line {i} failed\n{traceback.format_exc()}")
item["voicing_out"] = float(np.mean(vs)) if vs else 0.0
item["seconds"] = ws
rows.append(item)
log(f"{v['slot']} src_v={v['voicing']:.2f} out_v={item['voicing_out']:.2f} "
f"sec={ws}")
asr = pipeline("automatic-speech-recognition", model="openai/whisper-small",
device=0, torch_dtype=torch.float16)
for r in rows:
ces = []
for i, text in enumerate(LINES, 1):
p = OUT / f"{r['slot']}_{i}.wav"
if not p.exists():
continue
y, _ = sf.read(p, dtype="float32")
out = asr({"array": y.astype(np.float32), "sampling_rate": 44100},
generate_kwargs={"language": "zh", "task": "transcribe"})
hyp = (out.get("text", "") if isinstance(out, dict) else str(out)).strip()
s = score_row({"text": text, "hyp_text": hyp}, table)
ces.append(s["cer_norm"])
r[f"hyp_{i}"] = hyp
r["cer"] = float(np.mean(ces)) if ces else 1.0
r["ok"] = bool(r["cer"] < 0.35 and r["voicing_out"] < 0.7)
log(f"{r['slot']} cer={r['cer']:.3f} v_out={r['voicing_out']:.2f} "
f"{'PASS' if r['ok'] else 'fail'} {r.get('hyp_1','')[:24]}")
rows.sort(key=lambda r: (not r["ok"], r["cer"]))
(OUT / "metrics.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1))
log("\n-- ranking --")
for r in rows:
log(f" {'✓' if r['ok'] else '✗'} cer={r['cer']:.2f} v {r['voicing']:.2f}->"
f"{r['voicing_out']:.2f} {r['artist'][:14]:<14} {r['prompt_text'][:18]}")
if __name__ == "__main__":
main()