pingo-ptbr / training /prepare.py
itxtoledo's picture
Add pingo-ptbr: 0.87 MB pt-BR TTS (MLX + ONNX + web demo)
27d8618 verified
Raw History Blame Contribute Delete
4.81 kB
"""Data preparation: 24 kHz -> 16 kHz, Opus features, phonemes and durations in 10 ms frames.
For each clip writes `<out>/<split>/<id>.npz` with:
features (T,20) float32, tokens (L,) int16, stress (L,) int8, durations (L,) int16, voice int8
and one line in `<out>/<split>.jsonl` (accepted) or `<split>.rejected.jsonl` (rejected, with the reason).
Resumes where it stopped (skips ids already written).
Uses the front end (dizione-ptbr) and the CTC aligner (wav2vec2 phoneme) of tiny-voca-ptbr only as
annotation tools; none of their weights enter the final model.
Uso: python code/pingo_ptbr/prepare.py --split validation --limit 40 --out data/prep --device mps
"""
import argparse, io, json, sys, time, types
from pathlib import Path
import numpy as np
import pyarrow.parquet as pq
import soundfile as sf
from scipy.signal import resample_poly
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(Path(__file__).resolve().parent))
import features as F # noqa: E402
from tiny_voca.align import AlignmentSettings, PhoneRecognizer, align_utterance # noqa: E402
from tiny_voca.text import NothingToPronounce, phonemize # noqa: E402
DATA = ROOT / "data" / "speech" / "data" # hf download semfence/ptbr-synthetic-speech --repo-type dataset --local-dir data/speech
VOICES = {"F_s4": 0, "M_sm4": 1}
CONFIG = types.SimpleNamespace(hop=F.HOP, sample_rate=16000)
# 10 ms frames (tiny-voca used 10.67 ms): ~21 ms energy window, ~75 ms minimum pause
SETTINGS = AlignmentSettings(energy_window=341, min_pause_frames=8)
def parquet_files(split):
return sorted(DATA.glob(f"{split}-*.parquet"))
def rows(split, limit=None, voice=None):
n = 0
for path in parquet_files(split):
for batch in pq.ParquetFile(path).iter_batches(batch_size=64):
for r in batch.to_pylist():
if voice and r["voice_id"] != voice:
continue
yield r
n += 1
if limit and n >= limit:
return
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--split", required=True, choices=["train", "validation", "test"])
ap.add_argument("--out", default=str(ROOT / "data" / "prep"))
ap.add_argument("--limit", type=int)
ap.add_argument("--voice", choices=list(VOICES))
ap.add_argument("--device", default="cpu")
ap.add_argument("--max-wer", type=float, default=0.15, help="drop clips with a higher normalized_wer")
a = ap.parse_args()
out = Path(a.out); (out / a.split).mkdir(parents=True, exist_ok=True)
ok_path, bad_path = out / f"{a.split}.jsonl", out / f"{a.split}.rejected.jsonl"
done = {json.loads(l)["id"] for l in ok_path.read_text().splitlines()} if ok_path.exists() else set()
done |= {json.loads(l)["id"] for l in bad_path.read_text().splitlines()} if bad_path.exists() else set()
recognizer = PhoneRecognizer(device=a.device)
ok, bad = ok_path.open("a"), bad_path.open("a")
t0, n_ok, n_bad = time.time(), 0, 0
for r in rows(a.split, a.limit, a.voice):
if r["id"] in done:
continue
try:
if r["normalized_wer"] is not None and r["normalized_wer"] > a.max_wer:
raise ValueError(f"wer {r['normalized_wer']:.2f}")
audio, sr = sf.read(io.BytesIO(r["audio"]["bytes"]), dtype="float32")
if sr != 24000:
raise ValueError(f"sample rate {sr}")
w = resample_poly(audio, 2, 3).astype(np.float32)
feats = F.extract(w)
frames = len(feats)
wave = w[: frames * F.HOP]
ph = phonemize(r["text"])
voiced = feats[:, 19] > 0
durations, qc = align_utterance(recognizer, ph, wave, voiced, CONFIG, SETTINGS)
np.savez_compressed(
out / a.split / f"{r['id']}.npz", features=feats,
tokens=np.asarray(ph.ids, np.int16), stress=np.asarray(ph.stress, np.int8),
durations=np.asarray(durations, np.int16), voice=np.int8(VOICES[r["voice_id"]]))
ok.write(json.dumps({"id": r["id"], "text_id": r["text_id"], "voice": r["voice_id"], "text": r["text"],
"frames": frames, "tokens": len(ph.ids), "qc": qc}, ensure_ascii=False) + "\n")
ok.flush(); n_ok += 1
except (ValueError, NothingToPronounce) as e:
bad.write(json.dumps({"id": r["id"], "reason": str(e)[:200]}, ensure_ascii=False) + "\n"); bad.flush(); n_bad += 1
if (n_ok + n_bad) % 20 == 0:
print(f"{n_ok} ok, {n_bad} recusados, {(n_ok + n_bad) / (time.time() - t0):.1f} clipes/s", flush=True)
print(f"fim: {n_ok} ok, {n_bad} recusados em {time.time() - t0:.0f} s")
if __name__ == "__main__":
main()