webfm-eval / kaggle /style_probe.py
zziang's picture
style probe: FREEFORM instruction and BASIC controls
d8274ac verified
Raw History Blame Contribute Delete
5.79 kB
"""Can whispering be instructed instead of cloned?
Six low-voicing clips all failed as prompts: either the clone lost the breath
(buy1take2, voicing 0.34 -> 0.71) or it kept the breath and invented words
(Rainnight, CER 0.53). Whisper has no F0, and the model's voice conditioning
leans on periodicity, so a 6 s breathy prompt is not enough to carry it.
The repo exposes two text-side controls that were never tried here:
FREEFORM a free-text instruction, e.g. "用气声耳语,很轻"
BASIC speed/pitch/volume from fixed vocabularies
Both keep a *working* prompt (a08) and move the style into the text, which is
the opposite of what we were doing. Success means low CER *and* low voicing of
the output - a soft normal voice is not a whisper.
Writes style_probe/*.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 / "style_probe"
SEED = 20261031
VOICE = "a08"
LINES = ["后来店关了,歌还在。", "晚安,我们明天见。", "别急,先呼吸。"]
TRIALS = [
("plain", {}),
("freeform_whisper", {"task": "FREEFORM",
"instruction": "用气声耳语,很轻,像在深夜贴着耳朵说话。"}),
("freeform_soft", {"task": "FREEFORM",
"instruction": "轻声说,音量很低,气息多,接近耳语。"}),
("basic_low", {"task": "BASIC", "speed": "慢速", "pitch": "低", "volume": "低"}),
("freeform_basic", {"task": "FREEFORM",
"instruction": "用耳语说,很慢,很低,几乎只剩气息。"}),
]
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, sr):
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:
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
import tts_tasks
sys.path.insert(0, str(BUNDLE / "eval"))
from score import load_t2s, score_row
table = load_t2s()
voices = {v["slot"]: v for v in
json.loads((BUNDLE / "mined/manifest.json").read_text())["voices"]}
v = voices[VOICE]
tts = MingTTS(str(MODEL), device="cuda", text_normalization=False)
rows = []
for name, kw in TRIALS:
item = {"trial": name, "kwargs": {k: str(x) for k, x in kw.items()}}
ws, vs = [], []
for i, text in enumerate(LINES, 1):
try:
torch.manual_seed(SEED + i)
w = tts.synthesize(text=text, language_id="Chinese",
prompt_wav_path=str(BUNDLE / v["wav"]),
prompt_text=v["prompt_text"], use_spk_emb=True,
raw_text=True,
max_decode_steps=max(32, min(400, int(len(text) * 3.5))),
**kw)
y = w.cpu().numpy().reshape(-1)
sf.write(str(OUT / f"{name}_{i}.wav"), y, 44100)
ws.append(round(y.size / 44100, 2))
vs.append(voicing(y, 44100))
except Exception:
log(f"{name} line {i} failed\n{traceback.format_exc()}")
item["seconds"] = ws
item["voicing"] = float(np.mean(vs)) if vs else 0.0
rows.append(item)
log(f"{name}: v_out={item['voicing']:.2f} 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['trial']}_{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()
ces.append(score_row({"text": text, "hyp_text": hyp}, table)["cer_norm"])
r[f"hyp_{i}"] = hyp
r["cer"] = float(np.mean(ces)) if ces else 1.0
log(f"{r['trial']} cer={r['cer']:.3f} v={r['voicing']:.2f} {r.get('hyp_1','')[:22]}")
rows.sort(key=lambda r: r["cer"])
(OUT / "metrics.json").write_text(json.dumps(rows, ensure_ascii=False, indent=1))
log("\n-- summary (CER low is good; voicing low means breathy) --")
for r in rows:
log(f" cer={r['cer']:.2f} v={r['voicing']:.2f} {r['trial']}")
if __name__ == "__main__":
main()