File size: 3,287 Bytes
adabee1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/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()