|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import httpx |
| 4 | +import structlog |
| 5 | + |
| 6 | +from ai_server.voice.tts.base import TtsError, TtsProvider, TtsResult |
| 7 | +from ai_server.voice.tts.gemini import _parse_rate, pcm_to_wav |
| 8 | + |
| 9 | +log = structlog.get_logger(__name__) |
| 10 | + |
| 11 | + |
| 12 | +class GatewayTtsProvider(TtsProvider): |
| 13 | + """충남대 Mindlogic 게이트웨이 TTS (OpenAI 호환 /audio/speech). |
| 14 | +
|
| 15 | + 게이트웨이가 Gemini TTS 로 라우팅하며 raw PCM(L16, mono)을 바디로 직접 반환한다 |
| 16 | + (네이티브 Gemini 의 base64 JSON 과 다름). WAV 로 감싸 audio/wav 로 저장한다. |
| 17 | + GEMINI_API_KEY(직접) 대신 LLM_API_KEY(게이트웨이)를 써서 직접 키의 429 부하를 던다. |
| 18 | + """ |
| 19 | + |
| 20 | + def __init__( |
| 21 | + self, |
| 22 | + *, |
| 23 | + api_key: str, |
| 24 | + base_url: str, |
| 25 | + model: str, |
| 26 | + voice: str, |
| 27 | + timeout_sec: float, |
| 28 | + client: httpx.AsyncClient | None = None, |
| 29 | + ) -> None: |
| 30 | + self._api_key = api_key |
| 31 | + self._base_url = base_url.rstrip("/") |
| 32 | + self.model_name = model |
| 33 | + self._voice = voice |
| 34 | + self._timeout = timeout_sec |
| 35 | + self._client = client |
| 36 | + |
| 37 | + async def synthesize(self, text: str, *, voice: str) -> TtsResult: |
| 38 | + # consumer 가 넘기는 voice 는 OpenAI 용("alloy") 이므로 Gemini 전용 voice 를 쓴다. |
| 39 | + url = f"{self._base_url}/audio/speech" |
| 40 | + body = {"model": self.model_name, "input": text, "voice": self._voice} |
| 41 | + headers = {"Authorization": f"Bearer {self._api_key}"} |
| 42 | + try: |
| 43 | + if self._client is not None: |
| 44 | + resp = await self._client.post(url, headers=headers, json=body) |
| 45 | + else: |
| 46 | + async with httpx.AsyncClient(timeout=self._timeout) as client: |
| 47 | + resp = await client.post(url, headers=headers, json=body) |
| 48 | + except httpx.HTTPError as exc: |
| 49 | + raise TtsError("TTS_HTTP_ERROR", str(exc)) from exc |
| 50 | + if resp.status_code != 200: |
| 51 | + raise TtsError( |
| 52 | + "TTS_API_ERROR", |
| 53 | + f"gateway tts status {resp.status_code}: {resp.text[:200]}", |
| 54 | + ) |
| 55 | + audio = resp.content |
| 56 | + if not audio: |
| 57 | + raise TtsError("TTS_EMPTY_AUDIO", "gateway tts empty audio") |
| 58 | + |
| 59 | + content_type = resp.headers.get("content-type", "").lower() |
| 60 | + # 게이트웨이는 raw PCM(L16/24kHz) 을 반환 → WAV 로 감싼다. |
| 61 | + # 혹시 이미 컨테이너(wav/mpeg)면 그대로 전달. |
| 62 | + if ( |
| 63 | + "pcm" in content_type |
| 64 | + or "l16" in content_type |
| 65 | + or "octet-stream" in content_type |
| 66 | + ): |
| 67 | + rate = _parse_rate(content_type) |
| 68 | + wav = pcm_to_wav(audio, sample_rate=rate) |
| 69 | + duration = round(len(audio) / float(rate * 2), 2) # mono 16-bit |
| 70 | + return TtsResult( |
| 71 | + audio_bytes=wav, duration_sec=duration, content_type="audio/wav" |
| 72 | + ) |
| 73 | + return TtsResult( |
| 74 | + audio_bytes=audio, |
| 75 | + duration_sec=None, |
| 76 | + content_type=content_type.split(";")[0] or "audio/mpeg", |
| 77 | + ) |
0 commit comments