Download recipe/scripts/g2p_train.py from gowombat/tiny-voca-da: direct link, hf CLI and curl.
- Browser
- Download file 4.43 kB
-
https://huggingface.co/gowombat/tiny-voca-da/resolve/main/recipe/scripts/g2p_train.py
- Command line
-
hf download hf://gowombat/tiny-voca-da/recipe/scripts/g2p_train.py
-
curl -L -o g2p_train.py https://huggingface.co/gowombat/tiny-voca-da/resolve/main/recipe/scripts/g2p_train.py
4.43 kB
| """Train a Danish G2P (DeepPhonemizer forward transformer) on the packaged CC0 NST lexicon. | |
| Frontend v4 (AGENTS.md): Danish words that the NST lexicon lacks (compounds, new words) go to | |
| this model instead of eSpeak, so they keep NST symbols and stød. The targets are exactly what | |
| the frontend feeds the voice model for an NST word: `parse_sampa(...)` -> (NST phone, stress) | |
| pairs. Each distinct pair is written as one private-use character, because DeepPhonemizer | |
| tokenises phonemes per character; `symbols.json` maps them back. | |
| TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD=1 python scripts/g2p_train.py --out work/g2p-nst-v1 | |
| Single-word entries only; 2% held out (fixed seed) for the phoneme / word error rates. | |
| `--model-type autoreg_transformer` trains DeepPhonemizer's autoregressive variant instead. | |
| """ | |
| import argparse | |
| import json | |
| import random | |
| import unicodedata | |
| from pathlib import Path | |
| import yaml | |
| from dp.preprocess import preprocess | |
| from dp.train import train | |
| from tiny_voca.danish_lexicon import _lexicon | |
| from tiny_voca.danish_nst_inventory import parse_sampa | |
| LETTERS = set("abcdefghijklmnopqrstuvwxyzæøåéèêëüöäàáâóôíîïúûçñ-'") | |
| def dataset(): | |
| entries = _lexicon()[0] | |
| chosen = {} | |
| # Same preference as the runtime casefold lookup: an actual lowercase spelling first. | |
| for key in sorted(entries, key=lambda k: (k != k.casefold(), k)): | |
| word = unicodedata.normalize("NFC", key.casefold()) | |
| if " " in word or word in chosen or not set(word) <= LETTERS or not any(c.isalpha() for c in word): | |
| continue | |
| words = parse_sampa(entries[key][0]) | |
| if len(words) != 1: | |
| continue | |
| chosen[word] = tuple(words[0]) | |
| return chosen | |
| def main(): | |
| p = argparse.ArgumentParser(description=__doc__) | |
| p.add_argument("--out", type=Path, required=True) | |
| p.add_argument("--epochs", type=int, default=40) | |
| p.add_argument("--batch", type=int, default=64) | |
| p.add_argument("--d-model", type=int, default=512) | |
| p.add_argument("--layers", type=int, default=6) | |
| p.add_argument("--val-fraction", type=float, default=0.02) | |
| p.add_argument("--model-type", choices=["transformer", "autoreg_transformer"], default="transformer") | |
| args = p.parse_args() | |
| args.out.mkdir(parents=True, exist_ok=True) | |
| words = dataset() | |
| pairs = sorted({pair for phones in words.values() for pair in phones}) | |
| code = {pair: chr(0xE000 + i) for i, pair in enumerate(pairs)} | |
| (args.out / "symbols.json").write_text(json.dumps( | |
| {"version": "nst-g2p-symbols-v1", "pairs": [[p, s, code[(p, s)]] for p, s in pairs]}, | |
| ensure_ascii=False, indent=0) + "\n", encoding="utf-8") | |
| rows = [("da", w, "".join(code[x] for x in phones)) for w, phones in sorted(words.items())] | |
| random.Random(1234).shuffle(rows) | |
| n_val = int(len(rows) * args.val_fraction) | |
| val, tr = rows[:n_val], rows[n_val:] | |
| (args.out / "validation.jsonl").write_text("".join(json.dumps(r[1:], ensure_ascii=False) + "\n" for r in val), | |
| encoding="utf-8") | |
| print(f"words {len(rows)} train {len(tr)} val {len(val)} phone symbols {len(pairs)}", flush=True) | |
| import dp | |
| autoreg = args.model_type == "autoreg_transformer" | |
| name = "autoreg_config.yaml" if autoreg else "forward_config.yaml" | |
| config = yaml.safe_load((Path(dp.__file__).parent / "configs" / name).read_text()) | |
| config["paths"] = {"checkpoint_dir": str(args.out / "checkpoints"), "data_dir": str(args.out / "datasets")} | |
| pre = config["preprocessing"] | |
| pre.update(languages=["da"], text_symbols=sorted({c for _, w, _ in rows for c in w}), | |
| phoneme_symbols=[code[x] for x in pairs], char_repeats=1 if autoreg else 3, lowercase=True) | |
| config["model"].update(type=args.model_type, d_model=args.d_model, layers=args.layers) | |
| config["training"].update(epochs=args.epochs, batch_size=args.batch, batch_size_val=args.batch, | |
| warmup_steps=4000, generate_steps=5000, validate_steps=5000, | |
| checkpoint_steps=20000) | |
| config_path = args.out / "config.yaml" | |
| config_path.write_text(yaml.safe_dump(config, allow_unicode=True), encoding="utf-8") | |
| preprocess(config_file=str(config_path), train_data=tr, val_data=val, deduplicate_train_data=False) | |
| train(rank=0, num_gpus=1, config_file=str(config_path)) | |
| if __name__ == "__main__": | |
| main() | |