File size: 1,629 Bytes
5925b98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Pre-render the featured phrases (English -> Kalenjin -> Cheps WAV) and write
a phrasebook.json + audio/featured_*.wav bundle so they play back INSTANTLY in
the app (no live Modal call on the hot demo path). Run locally before deploy:

    INFERENCE_TOKEN=... python prerender.py
"""

import hashlib
import json
import os

import requests

TRANSLATE_URL = "https://tonykipkemboi--kalenjin-cascade-api-textcascade-translate.modal.run"
TTS_URL = "https://tonykipkemboi--kalenjin-tts-serve-kalenjintts-fastapi-app.modal.run/synthesize"
TOKEN = os.environ["INFERENCE_TOKEN"]

FEATURED = [
    "Thank you", "Good morning", "How are you?", "I love you",
    "Water", "Milk", "My child", "Come and eat",
]

HERE = os.path.dirname(os.path.abspath(__file__))
AUDIO = os.path.join(HERE, "audio")
os.makedirs(AUDIO, exist_ok=True)

book = {}
for phrase in FEATURED:
    t = requests.post(TRANSLATE_URL, json={"text": phrase}, timeout=70).json()
    kal, sw = t.get("kalenjin", "").strip(), t.get("swahili", "").strip()
    wav = requests.post(
        TTS_URL, json={"text": kal},
        headers={"Authorization": f"Bearer {TOKEN}"}, timeout=150,
    ).content
    key = hashlib.sha256(phrase.encode()).hexdigest()[:12]
    fname = f"featured_{key}.wav"
    with open(os.path.join(AUDIO, fname), "wb") as f:
        f.write(wav)
    book[phrase] = {"kalenjin": kal, "swahili": sw, "wav": f"audio/{fname}"}
    print(f"  {phrase!r:22} -> {kal!r:28} ({len(wav)} bytes)")

with open(os.path.join(HERE, "phrasebook.json"), "w") as f:
    json.dump(book, f, ensure_ascii=False, indent=2)
print(f"wrote phrasebook.json ({len(book)} phrases)")