Download recipe/filter/strict.py from KaleComputer/kale-tts-1-tiny: direct link, hf CLI and curl.
- Browser
- Download file 14.1 kB
-
https://huggingface.co/KaleComputer/kale-tts-1-tiny/resolve/main/recipe/filter/strict.py
- Command line
-
hf download hf://KaleComputer/kale-tts-1-tiny/recipe/filter/strict.py
-
curl -L -o strict.py https://huggingface.co/KaleComputer/kale-tts-1-tiny/resolve/main/recipe/filter/strict.py
14.1 kB
| # SPDX-License-Identifier: Apache-2.0 | |
| # Copyright 2026 Kale | |
| """Strict every-sentence-end check (the release path, after filter.py::keepall): the rough-ending measure (filter.py::endings, same | |
| maths: longest run of rough frames = above -30 dB, spectral centroid < 2.5 kHz, no pyin pitch fmin-700 Hz, in the last ~300 ms before | |
| the end) on EVERY sentence end of every kept multi-sentence take. The sentence ends come from forced alignment of the known text | |
| (`align_ctc`: CTC forced alignment on facebook/wav2vec2-large-960h-lv60-self, Apache-2.0, evaluation only; the release's | |
| own pass used torchaudio's WAV2VEC2_ASR_BASE_960H, MIT; the recipe uses the same aligner as recipe/bench), not from pauses: the filter's pause-based | |
| pass never checks a sentence end that runs straight into the next sentence. | |
| Inner end: the end time of the sentence's last word, moved to the first frame <= -35 dB within +0.30 s if there is one (a short pause), | |
| else kept at the word end. Window = 26 frames of 256 @ 22.05 kHz scaled to the take's rate. Pitch floor 70 Hz for male voices | |
| (config/filter.json "male_voices"), 110 Hz otherwise. `align` (Whisper large-v3-turbo word times) is the slower first version of the | |
| aligner, kept for reference; main uses align_ctc (~50x faster). | |
| modal run strict.py::main --which <group> | |
| Reads /data/kept/kept-<group>.jsonl on the volume; writes <root>/work/strict-<group>.jsonl (end_ms, inner_ms per take; final.py | |
| drops a take with any end >= 100 ms) and /data/strict_ends/ on the volume (resume: done takes are skipped).""" | |
| import json | |
| import os | |
| import re | |
| from pathlib import Path | |
| import modal | |
| def _cfg(name, default): | |
| """recipe config: env KALE_TTS_<NAME>_CONFIG, then ../config/<name>.json (modal.json) or ./config/<name>.json, then the copy in the image""" | |
| here = Path(__file__).resolve().parent | |
| for p in (os.environ.get(f"KALE_TTS_{name.upper()}_CONFIG"), here.parent / "config" / f"{name}.json", here / "config" / f"{name}.json", | |
| Path("/root/recipe") / f"{name}.json"): | |
| if p and Path(p).is_file(): | |
| return {**default, **json.loads(Path(p).read_text())} | |
| return default | |
| NAMES = _cfg("modal", {"filter_app": "kale-tts-filter", "data_volume": "kale-tts-data"}) | |
| CFG = _cfg("filter", {"strict_gpus": 4, "endings_cpus": 64, "male_voices": ["m3", "t071", "d13", "x328", "h013f"]}) | |
| app = modal.App(NAMES["filter_app"] + "-strict") | |
| vol = modal.Volume.from_name(NAMES["data_volume"], create_if_missing=False) | |
| def _cfg_files(image, names=("modal", "filter")): | |
| for n in names: | |
| for p in (Path(__file__).resolve().parent.parent / "config" / f"{n}.json", Path(__file__).resolve().parent / "config" / f"{n}.json"): | |
| if p.is_file(): | |
| image = image.add_local_file(str(p), f"/root/recipe/{n}.json") | |
| break | |
| return image | |
| def _p(path): | |
| return path | |
| MALE = set(CFG["male_voices"]) # 70 Hz pitch floor for men, 110 Hz for women | |
| ASR = "openai/whisper-large-v3-turbo" | |
| img_fa = (modal.Image.debian_slim(python_version="3.11").apt_install("libsndfile1") | |
| .pip_install("torch==2.4.1", "torchaudio==2.4.1", "transformers==4.46.3", "soundfile", "numpy<2", "num2words") | |
| .run_commands("python -c \"from transformers import Wav2Vec2ForCTC as M, Wav2Vec2Processor as P; M.from_pretrained('facebook/wav2vec2-large-960h-lv60-self'); P.from_pretrained('facebook/wav2vec2-large-960h-lv60-self')\"")) | |
| img_fa = _cfg_files(img_fa) | |
| img = (modal.Image.debian_slim(python_version="3.11").apt_install("ffmpeg", "libsndfile1") | |
| .pip_install("torch==2.4.1", "torchaudio==2.4.1", "transformers==4.46.3", "accelerate", "soundfile", "librosa==0.10.2", "numpy<2", "scipy", "num2words") | |
| .run_commands(f"python -c \"from transformers import WhisperForConditionalGeneration as W, WhisperProcessor as P; P.from_pretrained('{ASR}'); W.from_pretrained('{ASR}')\"")) | |
| img = _cfg_files(img) | |
| def spoken(word): # filt.py::spoken, unchanged | |
| from num2words import num2words | |
| t = re.sub(r"(\d+),(\d{3})", r"\1\2", word) | |
| t = t.replace("%", " percent ").replace("$", " dollars ").replace("&", " and ") | |
| t = re.sub(r"\d+(\.\d+)?", lambda m: " " + num2words(float(m.group()) if "." in m.group() else int(m.group())) + " ", t) | |
| t = t.lower().replace("-", " ").replace("’", "'") | |
| return [w.strip("'") for w in re.sub(r"[^a-z' ]", " ", t).split() if w.strip("'")] | |
| def _rough(y, sr, e, db, hop, nf, fmin=70): # male pitch floor (filter.py uses 70 for male voices too) | |
| """the rough-ending measure at frame e (filt.py::endings inner loop, unchanged) -> longest rough run in ms""" | |
| import librosa | |
| import numpy as np | |
| a = max(0, e - 26); a0 = max(0, a - 12); e0 = min(len(db), e + 12) | |
| seg = y[a0 * hop: e0 * hop + nf].astype(np.float64) | |
| f0, _, _ = librosa.pyin(seg, fmin=fmin, fmax=700, sr=sr, frame_length=nf, hop_length=hop, fill_na=np.nan) | |
| cen = librosa.feature.spectral_centroid(y=seg.astype(np.float32), sr=sr, n_fft=nf, hop_length=hop)[0] | |
| n = min(len(f0), len(cen), e0 - a0); f0 = f0[:n].copy(); cen = cen[:n]; d = db[a0:a0 + n] | |
| f0[d < -35] = np.nan | |
| rough = ((d > -30) & (cen < 2500) & np.isnan(f0))[a - a0: e - a0] | |
| run = best = 0 | |
| for q in rough: | |
| run = run + 1 if q else 0; best = max(best, run) | |
| return round(best * 11.61) | |
| def align(rows: list): | |
| """Whisper large-v3-turbo word times -> per take the spoken tokens' end times (17:22: the measure itself runs on CPUs)""" | |
| import librosa | |
| import soundfile as sf | |
| import torch | |
| from transformers import WhisperForConditionalGeneration, WhisperProcessor, pipeline | |
| vol.reload() | |
| proc = WhisperProcessor.from_pretrained(ASR) | |
| wm = WhisperForConditionalGeneration.from_pretrained(ASR, torch_dtype=torch.float16).to("cuda").eval() | |
| asr = pipeline("automatic-speech-recognition", model=wm, tokenizer=proc.tokenizer, feature_extractor=proc.feature_extractor, | |
| torch_dtype=torch.float16, device="cuda") | |
| out, live = [], [] | |
| for r in rows: | |
| try: | |
| y, sr = sf.read(_p(r["path"]), dtype="float32") | |
| live.append((r, librosa.resample(y, orig_sr=sr, target_sr=16000))) | |
| except Exception as ex: # noqa: BLE001 | |
| out.append(dict(r, why=repr(ex)[:200])) | |
| for b in range(0, len(live), 8): | |
| part = live[b:b + 8] | |
| res = asr([x[1] for x in part], return_timestamps="word", generate_kwargs=dict(language="en", task="transcribe"), batch_size=8) | |
| for (r, _), h in zip(part, res): | |
| toks = [] | |
| for c in h.get("chunks", []): | |
| for t in spoken(c["text"]): | |
| toks.append(c["timestamp"][1] if c["timestamp"][1] is not None else c["timestamp"][0]) | |
| out.append(dict(r, toks=toks, heard=h.get("text", "").strip()[:300])) | |
| return out | |
| def align_ctc(rows: list): | |
| """CTC forced alignment of the known text (facebook/wav2vec2-large-960h-lv60-self, Apache-2.0, as recipe/bench; LibriSpeech-trained; | |
| evaluation only) -> per take the spoken tokens' end times (s). Same output as `align` (Whisper word times), ~50x faster.""" | |
| import soundfile as sf | |
| import torch | |
| import torchaudio | |
| import torchaudio.functional as F | |
| vol.reload() | |
| from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor | |
| CTC = "facebook/wav2vec2-large-960h-lv60-self" | |
| proc = Wav2Vec2Processor.from_pretrained(CTC) | |
| model = Wav2Vec2ForCTC.from_pretrained(CTC).to("cuda").eval() | |
| idx = proc.tokenizer.get_vocab() | |
| SR = 16000 | |
| out = [] | |
| for r in rows: | |
| try: | |
| y, sr = sf.read(_p(r["path"]), dtype="float32") | |
| w = torch.from_numpy(y).unsqueeze(0) | |
| w = torchaudio.functional.resample(w, sr, SR) | |
| with torch.inference_mode(): | |
| em = model(proc(w[0].numpy(), sampling_rate=SR, return_tensors="pt").input_values.to("cuda")).logits | |
| em = torch.log_softmax(em.float(), dim=-1) | |
| words = [t for x in r["text"].split() for t in spoken(x)] | |
| chars, wend = [], [] | |
| for k, wd in enumerate(words): | |
| if k: | |
| chars.append(idx["|"]) | |
| chars += [idx[c] for c in wd.upper() if c in idx] | |
| wend.append(len(chars) - 1) | |
| tgt = torch.tensor([chars], dtype=torch.int32, device="cuda") | |
| ali, _ = F.forced_align(em, tgt, blank=idx["<pad>"]) | |
| ali = ali[0].cpu().tolist() | |
| # frame of each target token: the last frame emitting it | |
| pos, ti, last = {}, -1, None | |
| for fr, lab in enumerate(ali): | |
| if lab != 0 and (last != lab or fr == 0 or ali[fr - 1] == 0): | |
| ti += 1 | |
| if lab != 0: | |
| pos[ti] = fr | |
| last = lab | |
| ratio = w.shape[1] / em.shape[1] / SR | |
| toks = [round((pos.get(e, 0) + 1) * ratio, 3) for e in wend] | |
| out.append(dict(r, toks=toks, aligner="wav2vec2-large-960h-lv60-self ctc")) | |
| except Exception as ex: # noqa: BLE001 | |
| out.append(dict(r, why=repr(ex)[:200])) | |
| return out | |
| img_cpu = _cfg_files(modal.Image.debian_slim(python_version="3.11").apt_install("libsndfile1").pip_install("librosa==0.10.2", "soundfile", "numpy<2", "num2words")) | |
| def check(rows: list): | |
| """the rough-ending measure on the final end and on every inner sentence end (Whisper word end -> first frame <= -35 dB within 0.30 s)""" | |
| import librosa | |
| import numpy as np | |
| import soundfile as sf | |
| vol.reload() | |
| HOP = 256 | |
| out = [] | |
| for r in rows: | |
| if "why" in r: | |
| out.append(dict(clip=r["clip"], set=r["set"], why=r["why"])); continue | |
| try: | |
| y, sr = sf.read(_p(r["path"]), dtype="float32") | |
| sents = [s for s in re.split(r"(?<=[.!?])\s+", r["text"].strip()) if s] | |
| counts = [sum(len(spoken(w)) for w in s.split()) for s in sents] | |
| toks = r["toks"] | |
| hop = int(round(HOP * sr / 22050)); nf = 4 * hop | |
| rms = librosa.feature.rms(y=y, frame_length=nf, hop_length=hop)[0] | |
| db = 20 * np.log10(rms / max(rms.max(), 1e-9) + 1e-9) | |
| live_f = np.where(db > -35)[0] | |
| final = int(live_f[-1]) + 1 | |
| ok_align = len(toks) == sum(counts) | |
| ends, info, cum = [], [], 0 | |
| for n in counts[:-1]: | |
| cum += n | |
| if not ok_align: | |
| break | |
| t = float(toks[cum - 1]) | |
| f = int(round(t * sr / hop)) | |
| e = f | |
| for g in range(f, min(len(db), f + int(round(0.30 * sr / hop)))): | |
| if db[g] <= -35: | |
| e = g | |
| break | |
| ends.append(e) | |
| info.append(dict(t=round(t, 3), pause=bool(e != f))) | |
| fm = 70 if (r["set"] in MALE or r["clip"].split("_")[0] in MALE) else 110 | |
| inner = [_rough(y, sr, e, db, hop, nf, fm) for e in ends] | |
| out.append(dict(clip=r["clip"], set=r["set"], sentences=len(sents), aligned=ok_align, n_tok=len(toks), n_text=sum(counts), | |
| end_ms=_rough(y, sr, final, db, hop, nf, fm), inner_ms=inner, inner_info=info, heard=r.get("heard"))) | |
| except Exception as ex: # noqa: BLE001 | |
| out.append(dict(clip=r["clip"], set=r["set"], why=repr(ex)[:200])) | |
| d = Path("/data/strict_ends") | |
| d.mkdir(parents=True, exist_ok=True) | |
| (d / f"{rows[0]['set']}-{rows[0]['clip']}.jsonl").write_text("".join(json.dumps(x) + "\n" for x in out)) | |
| vol.commit() | |
| return out | |
| def rows_for(which: list): | |
| """every kept multi-sentence take (/data/kept/kept-<group>.jsonl); singles' final end is already checked by filter.py's endings""" | |
| vol.reload() | |
| multi = lambda t: len([s for s in re.split(r"(?<=[.!?])\s+", t.strip()) if s]) > 1 | |
| out, done = [], set() | |
| for w in which: | |
| kept = [json.loads(l) for l in Path(f"/data/kept/kept-{w}.jsonl").read_text().splitlines() if l.strip()] | |
| out += [dict(clip=k["clip"], path=f"/data/{k['path']}", text=k["text"], set=w, seconds=k["seconds"]) for k in kept if multi(k["text"])] | |
| for f in Path("/data/strict_ends").glob(f"{w}-*.jsonl") if Path("/data/strict_ends").exists() else []: | |
| done |= {json.loads(l)["clip"] for l in f.read_text().splitlines() if l.strip()} | |
| return [r for r in out if r["clip"] not in done] | |
| def main(which: str, per_call: int = 400): | |
| rows = rows_for.remote(which.split(",")) | |
| print(len(rows), "takes to check (not yet measured)", flush=True) | |
| root = Path(os.environ.get("KALE_TTS_ROOT", ".")) # folder holding work/ | |
| aligned = [] | |
| for part in align_ctc.map([rows[i:i + per_call] for i in range(0, len(rows), per_call)], order_outputs=False, return_exceptions=True): | |
| if isinstance(part, Exception): | |
| print("ALIGN FAILED", repr(part)[:300], flush=True) | |
| continue | |
| aligned += part | |
| print("aligned", len(aligned), flush=True) | |
| res = [] | |
| for part in check.map([aligned[i:i + 40] for i in range(0, len(aligned), 40)], order_outputs=False, return_exceptions=True): | |
| if isinstance(part, Exception): | |
| print("CHECK FAILED", repr(part)[:300], flush=True) | |
| continue | |
| res += part | |
| print("checked", len(res), flush=True) | |
| (root / f"work/strict-{which}.jsonl").write_text("".join(json.dumps(x) + "\n" for x in res)) | |
| print("DONE", len(res), flush=True) | |