LuaNovaV1 / scripts /build_dataset.py
oProfM's picture
Lua Nova V1 trained on oProfM/LuaNovaDataset: weights, ONNX, eval, code
d4101a0 verified
Raw History Blame Contribute Delete
8.63 kB
import io
import json
import os
import sys
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
import soundfile as sf
from scipy.signal import resample_poly
RELEASED_SRC = r"C:\dev\AjudaEstudos\released\lua-nova-v1\src"
if RELEASED_SRC not in sys.path:
sys.path.insert(0, RELEASED_SRC)
from lua_nova_v1.text.phonemizer import phonemize # noqa: E402
DATASET_DIR = r"C:\dev\AjudaEstudos\experiments\lua-nova-v1\hf_dataset\data"
OUT_DIR = r"C:\dev\AjudaEstudos\experiments\lua-nova-v1\data\source"
TIMINGS_PATH = r"C:\dev\AjudaEstudos\experiments\lua-nova-v1\timings.json"
TARGET_SR = 24000
HOP = 256
MIN_SAMPLES = 32 * HOP
def _process_row(item: tuple) -> tuple:
uid, text, norm_text, flac_bytes, dur, utmos, cer, lp = item
try:
ph = phonemize(text)
unk_count = len(ph.unknown)
except Exception:
return ("phonemize", uid)
wav, sr = sf.read(io.BytesIO(flac_bytes), dtype="float32")
if wav.ndim > 1:
wav = np.mean(wav, axis=-1).astype(np.float32)
if sr == 48000:
wav24 = resample_poly(wav, 1, 2).astype(np.float32)
elif sr == TARGET_SR:
wav24 = wav.astype(np.float32)
else:
return ("audio", uid)
if not np.all(np.isfinite(wav24)) or len(wav24) < MIN_SAMPLES:
return ("audio", uid)
peak = float(np.max(np.abs(wav24)))
if peak < 1e-4:
return ("audio", uid)
if peak > 0.99:
wav24 = (wav24 * (0.99 / peak)).astype(np.float32)
rms = float(np.sqrt(np.mean(wav24 ** 2)))
if rms < 1e-4:
return ("audio", uid)
buf = io.BytesIO()
sf.write(buf, wav24, TARGET_SR, format="WAV", subtype="PCM_16")
wav_bytes = buf.getvalue()
return ("ok", unk_count, (uid, text, norm_text, wav_bytes, float(len(wav24) / TARGET_SR), utmos, cer, lp))
def main() -> None:
t0 = time.perf_counter()
os.makedirs(OUT_DIR, exist_ok=True)
test_wav_dir = os.path.join(OUT_DIR, "test_wavs")
os.makedirs(test_wav_dir, exist_ok=True)
shards = sorted(f for f in os.listdir(DATASET_DIR) if f.endswith(".parquet"))
candidates = []
seen_texts = set()
seen_ids = set()
rejected = {"low_utmos": 0, "cer": 0, "lang": 0, "duration": 0, "dup": 0, "phonemize": 0, "audio": 0}
unknown_phones_total = 0
for shard in shards:
table = pq.read_table(
os.path.join(DATASET_DIR, shard),
columns=["id", "text", "normalized_text", "audio", "duration", "utmos", "cer", "lang_prob_pt", "low_utmos"],
)
d = table.to_pydict()
for i in range(len(d["id"])):
uid = str(d["id"][i]).strip()
text = (d["text"][i] or "").strip()
norm_text = (d["normalized_text"][i] or "").strip()
dur = float(d["duration"][i])
utmos = float(d["utmos"][i])
cer = float(d["cer"][i])
lp = float(d["lang_prob_pt"][i])
lu = bool(d["low_utmos"][i])
if lu:
rejected["low_utmos"] += 1
continue
if cer > 0.08:
rejected["cer"] += 1
continue
if lp < 0.8:
rejected["lang"] += 1
continue
if not (0.6 <= dur <= 20.0):
rejected["duration"] += 1
continue
key = text.casefold()
if not uid or not text or key in seen_texts or uid in seen_ids:
rejected["dup"] += 1
continue
seen_texts.add(key)
seen_ids.add(uid)
candidates.append((uid, text, norm_text, d["audio"][i]["bytes"], dur, utmos, cer, lp))
print(f"Filter complete: {len(candidates)} candidates, rejected={rejected}", flush=True)
t_res = time.perf_counter()
processed = []
workers = max(1, min(12, os.cpu_count() or 4))
done_cnt = 0
with ProcessPoolExecutor(max_workers=workers) as pool:
futures = [pool.submit(_process_row, item) for item in candidates]
for fut in as_completed(futures):
done_cnt += 1
res = fut.result()
if res[0] == "ok":
unknown_phones_total += res[1]
processed.append(res[2])
else:
rejected[res[0]] += 1
if done_cnt % 2000 == 0 or done_cnt == len(candidates):
print(
f"Processed {done_cnt}/{len(candidates)} in {time.perf_counter() - t_res:.1f}s "
f"(ok={len(processed)}, unk_phones={unknown_phones_total})",
flush=True,
)
processed.sort(key=lambda r: r[0])
# Deterministic duration-stratified split: 64 validation, 64 test, remainder train
by_dur = sorted(processed, key=lambda r: (r[4], r[0]))
val_idx = set(np.linspace(2, len(by_dur) - 3, 64, dtype=int).tolist())
rem_after_val = [row for idx, row in enumerate(by_dur) if idx not in val_idx]
test_idx = set(np.linspace(2, len(rem_after_val) - 3, 64, dtype=int).tolist())
val_rows = [by_dur[idx] for idx in sorted(val_idx)]
test_rows = [rem_after_val[idx] for idx in sorted(test_idx)]
train_rows = [row for idx, row in enumerate(rem_after_val) if idx not in test_idx]
t_sets = {
"train": {r[1].casefold() for r in train_rows},
"validation": {r[1].casefold() for r in val_rows},
"test": {r[1].casefold() for r in test_rows},
}
assert len(t_sets["train"] & t_sets["validation"]) == 0
assert len(t_sets["train"] & t_sets["test"]) == 0
assert len(t_sets["validation"] & t_sets["test"]) == 0
audio_type = pa.struct([("bytes", pa.binary()), ("path", pa.string())])
schema = pa.schema([
("id", pa.string()),
("text", pa.string()),
("normalized_text", pa.string()),
("voice_id", pa.string()),
("duration_24k", pa.float32()),
("utmos", pa.float32()),
("cer", pa.float32()),
("audio", audio_type),
])
summary = {"splits": {}, "rejected": rejected, "unknown_phones_total": unknown_phones_total}
for split_name, rows in [("train", train_rows), ("validation", val_rows), ("test", test_rows)]:
out_path = os.path.join(OUT_DIR, f"{split_name}.parquet")
tbl = pa.table(
{
"id": [r[0] for r in rows],
"text": [r[1] for r in rows],
"normalized_text": [r[2] for r in rows],
"voice_id": ["F1"] * len(rows),
"duration_24k": [np.float32(r[4]) for r in rows],
"utmos": [np.float32(r[5]) for r in rows],
"cer": [np.float32(r[6]) for r in rows],
"audio": [{"bytes": r[3], "path": f"{r[0]}.wav"} for r in rows],
},
schema=schema,
)
pq.write_table(tbl, out_path, compression="zstd")
tot_s = sum(r[4] for r in rows)
summary["splits"][split_name] = {
"count": len(rows),
"duration_sec": round(tot_s, 2),
"duration_hours": round(tot_s / 3600.0, 4),
"mean_utmos": round(float(np.mean([r[5] for r in rows])), 3),
"mean_cer": round(float(np.mean([r[6] for r in rows])), 5),
}
print(
f"Wrote {split_name}.parquet: {len(rows)} rows, {tot_s/3600:.3f}h, utmos={summary['splits'][split_name]['mean_utmos']}",
flush=True,
)
test_meta = []
for r in test_rows:
wav_path = os.path.join(test_wav_dir, f"{r[0]}.wav")
with open(wav_path, "wb") as fh:
fh.write(r[3])
test_meta.append(
{"id": r[0], "text": r[1], "duration_24k": round(r[4], 3), "utmos": round(r[5], 3), "cer": round(r[6], 4)}
)
with open(os.path.join(OUT_DIR, "test_metadata.json"), "w", encoding="utf-8") as fh:
json.dump(test_meta, fh, indent=2, ensure_ascii=False)
elapsed = round(time.perf_counter() - t0, 2)
summary["duration_sec"] = elapsed
with open(os.path.join(OUT_DIR, "build_summary.json"), "w", encoding="utf-8") as fh:
json.dump(summary, fh, indent=2, ensure_ascii=False)
if os.path.exists(TIMINGS_PATH):
with open(TIMINGS_PATH, "r", encoding="utf-8") as fh:
tdata = json.load(fh)
else:
tdata = {"stages": []}
tdata["dataset_build"] = summary
with open(TIMINGS_PATH, "w", encoding="utf-8") as fh:
json.dump(tdata, fh, indent=2, ensure_ascii=False)
print(f"build_dataset finished cleanly in {elapsed}s", flush=True)
if __name__ == "__main__":
main()