File size: 13,775 Bytes
c1cc38d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
753f159
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1cc38d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
753f159
c1cc38d
753f159
c1cc38d
 
753f159
 
 
 
 
 
c1cc38d
 
 
 
753f159
 
 
 
 
 
 
c1cc38d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
753f159
 
 
 
c1cc38d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
753f159
 
c1cc38d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
"""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()