webfm-eval / kaggle /voice_mining.py
zziang's picture
mining: reject probe CER>0.5, drop unusable modulation gate
753f159 verified
Raw History Blame Contribute Delete
13.8 kB
"""Mine replacement prompt voices from DownFlow/ASMR.
The shipped voices failed as Ming prompts because their transcripts do not
describe their audio: v04's promptText covers ~2.8 s of speech while the clip
runs 5.98 s, so the clone learns a broken text/audio alignment that every
generated line inherits (teacher CER 0.83 versus 0.08 for a good prompt).
Two rules here:
1. every candidate is cropped on a phrase boundary and transcribed from the
crop itself, never from the parent 30 s clip's transcript;
2. every candidate is ranked by the only measure that matters: bake it as a
prompt, synthesise three fixed sentences with the teacher, transcribe,
count character errors.
Stages:
STAGE=harvest CPU. stream, filter, crop, re-transcribe, score the signal
STAGE=probe GPU. bake each candidate, run the teacher probe, rank
STAGE=all both
Outputs: voices/{candidates/, candidates.json, probe.json, best.json}
"""
from __future__ import annotations
import hashlib
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"
WORK = ROOT / "voices"
CAND = WORK / "candidates"
DATASET = "DownFlow/ASMR"
N_ARTISTS = int(os.environ.get("N_ARTISTS", "20"))
N_PER_ARTIST = int(os.environ.get("N_PER_ARTIST", "6"))
CROP_S = float(os.environ.get("CROP_S", "6.0"))
MIN_SPEECH_S = float(os.environ.get("MIN_SPEECH_S", "4.5"))
STAGE = os.environ.get("STAGE", "all")
TOP_K = int(os.environ.get("TOP_K", "8"))
MAX_SCAN = int(os.environ.get("MAX_SCAN", "6000"))
PROBE_TEXTS = [
"灯关小一点,我们慢慢来。",
"雨从傍晚开始下,一直没停,窗户上蒙了一层薄薄的水汽。",
"睡不着的夜里,时间会走得特别慢。",
]
BLOCK = [
"操", "肏", "做爱", "阴茎", "阴道", "奶子", "龟头", "高潮", "自慰", "口交",
"性爱", "色情", "淫", "骚", "舔我",
"fuck", "cum", "penis", "pussy", "cock", "orgasm", "horny", "dick",
]
for _p in (WORK, CAND):
_p.mkdir(parents=True, exist_ok=True)
def log(msg: str) -> None:
print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
def is_sfw(text: str) -> bool:
t = (text or "").lower()
return not any(w in t for w in BLOCK)
def frame_rms(y: np.ndarray, sr: int, hop_s: float = 0.01, win_s: float = 0.025) -> np.ndarray:
hop, win = int(sr * hop_s), int(sr * win_s)
if len(y) < win:
return np.zeros(1, dtype=np.float32)
n = 1 + (len(y) - win) // hop
idx = np.arange(win)[None, :] + hop * np.arange(n)[:, None]
return np.sqrt((y[idx] ** 2).mean(axis=1) + 1e-12)
def speech_mask(rms: np.ndarray) -> np.ndarray:
floor = float(np.percentile(rms, 10))
mask = rms > max(floor * 3.0, 1e-4)
gap = 20 # 200 ms at a 10 ms hop
i = 0
while i < len(mask):
if mask[i]:
i += 1
continue
j = i
while j < len(mask) and not mask[j]:
j += 1
if i > 0 and (j - i) < gap and j < len(mask):
mask[i:j] = True
i = j
return mask
def crop_on_phrase(y: np.ndarray, sr: int):
"""Pick a CROP_S window beginning at a phrase onset. Returns (audio, stats)."""
rms = frame_rms(y, sr)
mask = speech_mask(rms)
runs, start = [], (0 if mask[0] else None)
for e in np.flatnonzero(np.diff(mask.astype(np.int8))):
if start is None:
start = e + 1
else:
runs.append((start, int(e) + 1))
start = None
if start is not None:
runs.append((start, len(mask)))
per_10ms = int(sr * 0.01)
need = int(MIN_SPEECH_S * 100)
runs = [r for r in runs if r[1] - r[0] >= need]
if not runs:
return None, {"reject": "no_phrase"}
s, e = max(runs, key=lambda r: float(rms[r[0]:r[1]].mean()))
n = int(CROP_S * 100)
if e - s < n:
s = max(s, e - n)
else:
e = s + n
seg = np.asarray(y[s * per_10ms: e * per_10ms], dtype=np.float32)
if seg.size < per_10ms * 100 * 0.8:
return None, {"reject": "short_crop"}
peak = float(np.abs(seg).max())
if peak > 0:
seg = seg * (0.90 / peak)
noise = rms[~mask] if (~mask).any() else rms
speech = rms[s:e][mask[s:e]]
snr = 10 * np.log10(max(1e-8, float(speech.mean()) ** 2 / max(1e-8, float(noise.mean()) ** 2)))
stats = {
"speech_ratio": float(mask[s:e].mean()),
"snr_db": float(snr),
"clip_ratio": float((np.abs(seg) > 0.995).mean()),
}
return seg, stats
def spectral_flatness(y: np.ndarray, sr: int) -> float:
win = int(0.025 * sr)
if len(y) < win:
return 1.0
frames = np.lib.stride_tricks.sliding_window_view(y, win)[:: int(0.01 * sr)]
spec = np.abs(np.fft.rfft(frames * np.hanning(win), axis=1)) + 1e-10
return float(np.median(np.exp(np.log(spec).mean(axis=1)) / spec.mean(axis=1)))
def speech_modulation(y: np.ndarray, sr: int) -> float:
"""Share of envelope energy in the 2-8 Hz syllabic band.
Speech has a syllabic rhythm; rustling, tapping and room tone do not. This
is the physical counterpart to the transcript: whisper-small happily
invents a caption over pure noise ("字幕by索兰娅"), so the transcript alone
cannot tell us whether anyone is talking.
"""
hop = int(0.01 * sr)
if len(y) < hop * 50:
return 0.0
n = len(y) // hop
env = np.sqrt((y[: n * hop].reshape(n, hop) ** 2).mean(axis=1) + 1e-12)
env = env - env.mean()
spec = np.abs(np.fft.rfft(env))
freqs = np.fft.rfftfreq(len(env), 0.01)
total = spec.sum() + 1e-12
return float(spec[(freqs >= 2.0) & (freqs <= 8.0)].sum() / total)
ASR_ARTIFACTS = ("字幕", "by索", "谢谢观看", "请订阅", "amara", "subtitles", "感谢观看")
def repeated_run(text: str) -> float:
"""Share of the transcript taken by its longest repeated character run."""
if not text:
return 1.0
best, cur = 1, 1
for a, b in zip(text, text[1:]):
cur = cur + 1 if a == b else 1
best = max(best, cur)
return best / len(text)
def build_asr():
import torch
from transformers import pipeline
pipe = pipeline("automatic-speech-recognition", model="openai/whisper-small",
device=0, torch_dtype=torch.float16)
def asr(y: np.ndarray, sr: int) -> str:
out = pipe({"array": y.astype(np.float32), "sampling_rate": sr},
generate_kwargs={"language": "zh", "task": "transcribe"})
return (out.get("text", "") if isinstance(out, dict) else str(out)).strip()
return asr
def harvest(asr) -> list[dict]:
import soundfile as sf
from datasets import load_dataset
ds = load_dataset(DATASET, split="train", streaming=True)
per_artist: dict[str, list[dict]] = {}
scanned = 0
t0 = time.time()
for row in ds:
scanned += 1
if scanned > MAX_SCAN or len(per_artist) >= N_ARTISTS:
break
creator = row.get("creator") or "unknown"
if len(per_artist.get(creator, [])) >= N_PER_ARTIST:
continue
if creator not in per_artist and len(per_artist) >= N_ARTISTS:
continue
if row.get("nsfw") or not row.get("has_verbal_speech") or row.get("hallucinated"):
continue
if not is_sfw(row.get("transcript", "")):
continue
try:
audio = row["audio"]
y = np.asarray(audio["array"], dtype=np.float32).reshape(-1)
sr = int(audio["sampling_rate"])
except Exception:
continue
seg, st = crop_on_phrase(y, sr)
if seg is None:
continue
flat = spectral_flatness(seg, sr)
mod = speech_modulation(seg, sr)
st["flatness"] = flat
st["modulation"] = mod
if st["snr_db"] < 12 or st["clip_ratio"] > 1e-3 or st["speech_ratio"] < 0.55 or flat > 0.35:
continue
# Do not gate on `modulation`. Measured on clips a listener confirmed
# contain whisper speech versus clips that are pure ASMR noise, the two
# overlap almost exactly (0.239 vs 0.230), because whispering has weak
# syllabic rhythm. It is recorded for diagnostics only. The reliable
# discriminator is the round-trip probe CER: noise-only prompts score
# above 1.0, a usable whisper prompt scores 0.22.
text = asr(seg, sr)
if not (6 <= len(text) <= 70) or repeated_run(text) > 0.3 or not is_sfw(text):
continue
if any(a in text for a in ASR_ARTIFACTS):
continue
# A hallucinated caption over noise tends to be far shorter or longer
# than anyone can actually say in six seconds.
rate = len(text) / (len(seg) / sr)
if not (2.5 <= rate <= 9.0):
continue
idx = len(per_artist.get(creator, []))
tag = hashlib.md5(creator.encode("utf-8")).hexdigest()[:4]
cid = f"{tag}_{idx}"
path = CAND / f"{cid}.wav"
sf.write(str(path), seg, sr)
per_artist.setdefault(creator, []).append({
"cid": cid, "artist": creator, "wav": str(path),
"prompt_text": text, "duration_s": round(len(seg) / sr, 2), **st,
"source_file": row.get("source_file"), "clip_index": row.get("clip_index"),
})
if len(per_artist[creator]) == 1:
log(f"artist {len(per_artist)}: {creator[:40]} first candidate ok")
out = [c for cl in per_artist.values() for c in cl]
(WORK / "candidates.json").write_text(json.dumps(out, ensure_ascii=False, indent=2))
log(f"harvest: {len(per_artist)} artists, {len(out)} candidates, scanned {scanned} "
f"rows in {time.time()-t0:.0f}s")
return out
def hf_ratio(y: np.ndarray, sr: int, cut: int = 8000) -> float:
"""Energy share above `cut`. A 16 kHz source cannot produce it, so a dull
clone shows up here even when CER looks fine."""
spec = np.abs(np.fft.rfft(y)) ** 2
freqs = np.fft.rfftfreq(len(y), 1 / sr)
return float(spec[freqs > cut].sum() / (spec.sum() + 1e-12))
def patch_fp32() -> None:
"""T4 has no bf16 and the repo defaults to it."""
for name in ("ming_tts.py", "modeling_bailingmm.py"):
path = REPO / name
s = path.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")
path.write_text(s)
def probe(cands: list[dict], asr) -> list[dict]:
import torch
sys.path.insert(0, str(REPO))
patch_fp32()
from ming_tts import MingTTS
import tts_tasks
sys.path.insert(0, str(ROOT / "webfm-eval/eval"))
from score import load_t2s, score_row
table = load_t2s()
tts = MingTTS(str(MODEL), device="cuda", text_normalization=False)
mm = tts.model
device = next(mm.parameters()).device
dtype = next(mm.parameters()).dtype
_ = tts_tasks.build_tts_prompt("Chinese")
results = []
for i, c in enumerate(cands):
try:
t0 = time.time()
torch.manual_seed(1234)
lat, spk = tts.prepare_prompt(c["wav"], use_spk_emb=True)
lat = lat.to(device=device, dtype=dtype)
ces, hfs = [], []
for text in PROBE_TEXTS:
wav = tts.synthesize(
task="TTS", text=text, language_id="Chinese",
prompt_wav_path=c["wav"], prompt_text=c["prompt_text"],
use_spk_emb=True, raw_text=True,
max_decode_steps=max(32, min(400, int(len(text) * 3.5))),
)
arr = wav.cpu().numpy().reshape(-1)
ces.append(score_row({"text": text, "hyp_text": asr(arr, 44100)}, table)["cer_norm"])
hfs.append(hf_ratio(arr, 44100))
row = dict(c, cer=float(np.mean(ces)), cer_each=ces,
hf=float(np.mean(hfs)), wall=round(time.time() - t0, 1))
# A prompt whose round trip scores above 0.5 is not a voice, it is
# either a bad transcript or a clip with no speech in it. Both show
# up here as garbled output, and both are unusable downstream.
row["keep"] = bool(row["cer"] < 0.5)
results.append(row)
log(f"[{i+1}/{len(cands)}] {c['cid']} cer={row['cer']:.3f} hf={row['hf']:.4f} "
f"snr={c['snr_db']:.1f} {c['prompt_text'][:16]}")
except Exception:
log(f"{c['cid']} probe failed\n{traceback.format_exc()}")
results.sort(key=lambda r: (r["cer"], -r["hf"]))
(WORK / "probe.json").write_text(json.dumps(results, ensure_ascii=False, indent=2))
return results
def select(results: list[dict]) -> list[dict]:
best: dict[str, dict] = {}
for r in results:
best.setdefault(r["artist"], r)
ranked = [r for r in sorted(best.values(), key=lambda r: r["cer"])
if r.get("keep", True)][:TOP_K]
(WORK / "best.json").write_text(json.dumps(ranked, ensure_ascii=False, indent=2))
log("\n-- best per artist --")
for r in ranked:
log(f" {r['cer']:.3f} hf={r['hf']:.4f} {r['artist'][:34]:<34} "
f"{r['duration_s']}s {r['prompt_text'][:20]}")
return ranked
def main() -> None:
asr = build_asr()
if STAGE in ("harvest", "all"):
cands = harvest(asr)
else:
cands = json.loads((WORK / "candidates.json").read_text())
if STAGE in ("probe", "all"):
select(probe(cands, asr))
if __name__ == "__main__":
main()