freya-tr-eval-rerun / harness /synth_api.py
cloud0day3's picture
Freya-TR-Eval re-run: harness, per-clip transcripts, results (Chatterbox/XTTS pending)
24d88cf verified
Raw History Blame Contribute Delete
4.22 kB
"""Render Freya-TR-Eval through cloud APIs, 3 independent takes per sentence, raw text in.
PDAI_API_KEY=pd_live_... python synth_api.py alania-2 alania-1
GOOGLE_CLOUD_PROJECT=... python synth_api.py gemini-3.8-flash gemini-3.8-flash-lite # needs `gcloud auth`
Alania: POST https://voice.patientdesk.ai/v1/audio/speech, default settings (Alania-2 voice alania2-f1).
Gemini: Vertex AI generateContent (location global), prebuilt voice Kore, the sentence alone as the prompt.
Writes audio/<system>/take<k>/<id>.wav under BENCH_ROOT (default: current directory).
"""
import base64, io, json, os, subprocess, sys, time, urllib.error, urllib.request, wave
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from runner import ITEMS, ROOT # noqa: E402
TAKES = (0, 1, 2)
ALANIA = {"alania-2": {"model": "alania-v2", "voice": "alania2-f1"}, "alania-1": {"model": "alania-v1"}}
GEMINI = ("https://aiplatform.googleapis.com/v1/projects/{p}/locations/global/publishers/google/models/{m}-tts:generateContent")
_tok = {"t": None, "at": 0.0}
def gtoken():
if time.time() - _tok["at"] > 1800:
_tok["t"] = subprocess.run(["gcloud", "auth", "print-access-token"], capture_output=True, text=True).stdout.strip()
_tok["at"] = time.time()
return _tok["t"]
def pcm_to_wav(pcm, rate):
buf = io.BytesIO()
with wave.open(buf, "wb") as w:
w.setnchannels(1); w.setsampwidth(2); w.setframerate(rate); w.writeframes(pcm)
return buf.getvalue()
def alania(system, text):
body = {**ALANIA[system], "input": text, "response_format": "wav"}
req = urllib.request.Request("https://voice.patientdesk.ai/v1/audio/speech", json.dumps(body).encode(),
{"authorization": f"Bearer {os.environ['PDAI_API_KEY']}", "content-type": "application/json"})
return urllib.request.urlopen(req, timeout=180).read()
def gemini(model, text):
body = {"contents": [{"role": "user", "parts": [{"text": text}]}],
"generationConfig": {"responseModalities": ["AUDIO"],
"speechConfig": {"voiceConfig": {"prebuiltVoiceConfig": {"voiceName": "Kore"}}}}}
req = urllib.request.Request(GEMINI.format(p=os.environ["GOOGLE_CLOUD_PROJECT"], m=model), json.dumps(body).encode(),
{"authorization": f"Bearer {gtoken()}", "content-type": "application/json"})
part = json.load(urllib.request.urlopen(req, timeout=120))["candidates"][0]["content"]["parts"][0]["inlineData"]
raw = base64.b64decode(part["data"])
if part["mimeType"].startswith("audio/wav"):
return raw
rate = int(part["mimeType"].split("rate=")[1].split(";")[0]) if "rate=" in part["mimeType"] else 24000
return pcm_to_wav(raw, rate)
def render(job):
system, item, take = job
out = ROOT / "audio" / system / f"take{take}" / f"{item['id']}.wav"
if out.exists() and out.stat().st_size > 2000:
return system, item["id"], take, "cached"
last = ""
for attempt in range(8):
try:
data = alania(system, item["text"]) if system in ALANIA else gemini(system, item["text"])
out.parent.mkdir(parents=True, exist_ok=True)
out.write_bytes(data)
return system, item["id"], take, "ok"
except urllib.error.HTTPError as e:
last = f"HTTP {e.code} {e.read()[:200]!r}"
if e.code in (429, 500, 502, 503, 504):
time.sleep(min(60, 3 * 2 ** attempt))
continue
break
except Exception as e: # network hiccup
last = repr(e)[:200]
time.sleep(3 * (attempt + 1))
return system, item["id"], take, f"FAIL {last}"
if __name__ == "__main__":
jobs = [(s, it, t) for t in TAKES for s in sys.argv[1:] for it in ITEMS]
with ThreadPoolExecutor(int(os.environ.get("CONC", "3"))) as pool:
for n, (system, iid, take, status) in enumerate(pool.map(render, jobs), 1):
if status.startswith("FAIL"):
print(system, iid, take, status, flush=True)
if n % 100 == 0:
print(f"{n}/{len(jobs)}", flush=True)