patient-virtuel-dentiste / tts_engine.py
carlosduplar
build-small-hackathon: initial Gradio + Modal app scaffold
b05542b
Raw History Blame
1.21 kB
import os
import httpx
MODAL_ENDPOINT = os.environ.get("MODAL_ENDPOINT_MISTRAL_TTS", "")
MISTRAL_API_KEY = os.environ.get("MISTRAL_API_KEY", "")
MODAL_AUTH_TOKEN = os.environ.get("MODAL_AUTH_TOKEN", "")
VOICE = "french_female"
MODEL = "mistral-tts"
def synthesize(text: str) -> bytes | None:
"""Tier-1: call Mistral API directly from the Space (simplest, free tier)."""
if not MISTRAL_API_KEY:
return _fallback_modal(text)
resp = httpx.post(
"https://api.mistral.ai/v1/audio/speech",
headers={"Authorization": f"Bearer {MISTRAL_API_KEY}"},
json={
"model": MODEL,
"input": text,
"voice": VOICE,
"response_format": "wav",
},
timeout=25,
)
if resp.is_error:
return _fallback_modal(text)
return resp.content
def _fallback_modal(text: str) -> bytes | None:
"""Tier-2: fall back to Modal-hosted Mistral TTS."""
if not MODAL_ENDPOINT:
raise RuntimeError("No TTS endpoint available")
resp = httpx.post(
MODAL_ENDPOINT,
json={"text": text, "token": MODAL_AUTH_TOKEN},
timeout=30,
)
resp.raise_for_status()
return resp.content