Download speak.py from gowombat/tiny-voca-da: direct link, hf CLI and curl.
- Browser
- Download file 3.29 kB
-
https://huggingface.co/gowombat/tiny-voca-da/resolve/main/speak.py
- Command line
-
hf download hf://gowombat/tiny-voca-da/speak.py
-
curl -L -o speak.py https://huggingface.co/gowombat/tiny-voca-da/resolve/main/speak.py
3.29 kB
| #!/usr/bin/env python3 | |
| """Danish text -> WAV with the tiny-voca-da ONNX model (CPU, onnxruntime). | |
| Needs the Danish tiny-voca frontend the model was trained with (frontend v4; see README.md, | |
| "Run it"). The script refuses to run with any other frontend, because the phoneme IDs would not | |
| match. | |
| python speak.py "Hej, jeg hedder Mic. Hvordan går det?" --output hej.wav | |
| """ | |
| import argparse | |
| import json | |
| import re | |
| from pathlib import Path | |
| import numpy as np | |
| import onnxruntime as ort | |
| import soundfile as sf | |
| from tiny_voca.languages import profile_for | |
| from tiny_voca.text import frontend_fingerprint, phonemize | |
| HERE = Path(__file__).resolve().parent | |
| def sentences(text): | |
| """Split long input at sentence ends; the model reads one sentence-sized chunk at a time.""" | |
| parts = [p.strip() for p in re.split(r"(?<=[.!?…])\s+", text.strip()) if p.strip()] | |
| return parts or [text] | |
| def main(): | |
| p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| p.add_argument("text") | |
| p.add_argument("--model", type=Path, default=HERE / "onnx" / "model-int8.onnx", | |
| help="onnx/model-int8.onnx (9 MB, default) or onnx/model.onnx (28 MB, fp32)") | |
| p.add_argument("--output", type=Path, default=Path("tiny-voca-da.wav")) | |
| p.add_argument("--speed", type=float, default=1.0, help="above 1 is faster") | |
| p.add_argument("--pause", type=float, default=0.25, help="seconds of silence between sentences") | |
| p.add_argument("--threads", type=int, default=2) | |
| a = p.parse_args() | |
| meta = json.loads(a.model.with_suffix(".json").read_text()) | |
| profile = profile_for("da") | |
| if meta.get("frontend_fingerprint") != frontend_fingerprint(profile): | |
| raise SystemExit("The installed Danish frontend is not the one this model was trained with (frontend v4).") | |
| options = ort.SessionOptions() | |
| options.intra_op_num_threads = a.threads | |
| session = ort.InferenceSession(str(a.model), sess_options=options, providers=["CPUExecutionProvider"]) | |
| rate = meta["sample_rate"] | |
| chunks = [] | |
| for sentence in sentences(a.text): | |
| phones = phonemize(sentence, profile) | |
| if phones.unknown: | |
| raise SystemExit(f"Unknown symbols {phones.unknown} in: {sentence}") | |
| if len(phones) > meta["max_tokens"]: | |
| raise SystemExit(f"Sentence too long ({len(phones)} > {meta['max_tokens']} tokens), split it: {sentence}") | |
| audio, _ = session.run(None, { | |
| "tokens": np.asarray([phones.ids], dtype=np.int64), | |
| "stress": np.asarray([phones.stress], dtype=np.int64), | |
| "voice": np.asarray([0], dtype=np.int64), | |
| "speed": np.asarray([a.speed], dtype=np.float32), | |
| "pitch_shift": np.asarray([0.0], dtype=np.float32), | |
| "pitch_range": np.asarray([1.0], dtype=np.float32), | |
| }) | |
| if chunks: | |
| chunks.append(np.zeros(int(a.pause * rate), dtype=np.float32)) | |
| chunks.append(audio[0].astype(np.float32)) | |
| wave = np.concatenate(chunks) | |
| wave *= min(1.0, 0.99 / max(float(np.abs(wave).max()), 1e-9)) # uniform gain only, never clips | |
| sf.write(a.output, wave, rate, subtype="PCM_16") | |
| print(f"wrote {a.output} ({len(wave) / rate:.2f} s)") | |
| if __name__ == "__main__": | |
| main() | |