# Демо «симлиша»: голоса Piper читают случайную тарабарщину из слогов. Запуск: venv/bin/python gen/simlish.py <каталог piper>
import json, random, sys, wave
from pathlib import Path
from piper import PiperVoice, SynthesisConfig

root = Path(sys.argv[1])
out = root / 'out'
out.mkdir(exist_ok=True)
rng = random.Random(7)
words_dict = set(w.strip().lower() for w in open('/usr/share/dict/words'))

ONSETS = ['b', 'd', 'f', 'g', 'h', 'k', 'l', 'm', 'n', 'p', 'r', 's', 't', 'v', 'w', 'z', 'sh', 'ch', 'fr', 'gl', 'pl', 'bl', 'sn', 'tr', 'dr', 'kw']
VOWELS = ['a', 'e', 'i', 'o', 'oo', 'ee', 'ay', 'ah', 'oh', 'oy', 'ow', 'u']
CODAS = ['', '', '', '', 'n', 'm', 'b', 'sh', 'l', 'k', 'p', 'z']

def word() -> str:
    while True:
        n = rng.choices([1, 2, 3], [3, 5, 2])[0]
        w = ''.join(rng.choice(ONSETS) + rng.choice(VOWELS) + (rng.choice(CODAS) if i == n - 1 else '') for i in range(n))
        if w not in words_dict and len(w) <= 10:
            return w

def phrase() -> str:
    n = rng.randint(3, 6)
    ws = [word() for _ in range(n)]
    if n >= 5 and rng.random() < 0.5:
        ws[rng.randint(1, n - 3)] += ','
    end = rng.choices(['.', '?', '!'], [4, 3, 2])[0]
    s = ' '.join(ws) + end
    return s[0].upper() + s[1:]

VOICES = [
    ('en_US-ljspeech-high', 'ж'), ('en_US-norman-medium', 'м'), ('en_US-kristin-medium', 'ж'),
    ('en_US-john-medium', 'м'), ('en_GB-cori-high', 'ж'), ('en_US-bryce-medium', 'м'),
]
meta = []
for name, sex in VOICES:
    voice = PiperVoice.load(str(root / 'voices' / f'{name}.onnx'))
    for i in range(4):
        text = phrase()
        cfg = SynthesisConfig(length_scale=rng.uniform(0.85, 1.0), noise_scale=0.8, noise_w_scale=0.9)
        path = out / f'{name}-{i + 1}.wav'
        with wave.open(str(path), 'wb') as wf:
            voice.synthesize_wav(text, wf, syn_config=cfg)
        meta.append({'file': path.stem, 'voice': name, 'sex': sex, 'text': text})
        print(path.stem, text)
json.dump(meta, open(out / 'meta.json', 'w'), ensure_ascii=False, indent=1)
