-
Notifications
You must be signed in to change notification settings - Fork 0
feat(tts): Phase 10C — TTS generation via OpenRouter /audio/speech #22
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
bd075d5
feat(tts): Phase 10C — TTS generation via OpenRouter /audio/speech
Krasimir-Hristov f12a6bf
fix(audio): address code-review findings from Phase 10C
Krasimir-Hristov 01fb080
fix(audio): redact user_id from generate_tts logger.info (PII)
Krasimir-Hristov 4149a68
fix(audio): validate TTS response bytes; redact user_id from upload_a…
Krasimir-Hristov File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| """Pydantic schemas for the audio feature (Phase 10C).""" | ||
|
|
||
| from pydantic import BaseModel, Field | ||
|
|
||
|
|
||
| class AudioGenerateResult(BaseModel): | ||
| """Result returned after generating and uploading a TTS audio file.""" | ||
|
|
||
| signed_url: str | ||
| filename: str | ||
| text_preview: str = Field(..., min_length=1, max_length=1024) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,154 @@ | ||
| """TTS generation + Supabase Storage upload service (Phase 10C). | ||
|
|
||
| Uses OpenRouter's /audio/speech endpoint (openai/gpt-4o-mini-tts-2025-12-15). | ||
| The existing openrouter_api_key is reused — no separate OpenAI key needed. | ||
|
|
||
| Public API | ||
| ---------- | ||
| generate_tts(text, user_id) -> tuple[bytes, str] | ||
| Call OpenRouter TTS endpoint, return (mp3_bytes, storage_filename). | ||
|
|
||
| upload_audio(audio_bytes, filename) -> str | ||
| Upload mp3 bytes to Supabase Storage and return a signed URL (1 week). | ||
| """ | ||
|
|
||
| import logging | ||
| from uuid import uuid4 | ||
|
|
||
| import httpx | ||
|
|
||
| from app.core.config import settings | ||
| from app.core.privacy import mask_pii | ||
| from app.db.supabase import get_supabase_client | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| # OpenAI TTS hard limit — truncate with a warning rather than failing. | ||
| _MAX_TTS_CHARS = 4096 | ||
|
|
||
| # Signed URL expiry: 7 days in seconds. | ||
| _SIGNED_URL_TTL = 7 * 24 * 60 * 60 # 604 800 s | ||
|
|
||
|
|
||
| async def generate_tts(text: str, user_id: str) -> tuple[bytes, str]: | ||
| """Call OpenRouter TTS endpoint and return (mp3_bytes, storage_filename). | ||
|
|
||
| Args: | ||
| text: The text to synthesize. Truncated to 4 096 chars if longer. | ||
| user_id: Authenticated user UUID — used to scope the storage path. | ||
|
|
||
| Returns: | ||
| A tuple of (raw mp3 bytes, storage filename scoped to user_id). | ||
|
|
||
| Raises: | ||
| RuntimeError: If the OpenRouter API call fails or the response is malformed. | ||
| """ | ||
| if len(text) > _MAX_TTS_CHARS: | ||
| logger.warning( | ||
| "[generate_tts] text length %d exceeds limit %d — truncating", | ||
| len(text), | ||
| _MAX_TTS_CHARS, | ||
| ) | ||
| text = text[:_MAX_TTS_CHARS] | ||
|
|
||
| if not text.strip(): | ||
| raise RuntimeError("Cannot generate TTS for empty text.") | ||
|
|
||
| # Mask PII before forwarding text to the external TTS provider. | ||
| masked_text = await mask_pii(text) | ||
|
|
||
| # OpenRouter /audio/speech endpoint — returns raw MP3 bytes (not JSON). | ||
| payload = { | ||
| "model": settings.tts_model, | ||
| "input": masked_text, | ||
| "voice": settings.tts_voice, | ||
| "response_format": "mp3", | ||
| } | ||
| headers = { | ||
| "Authorization": f"Bearer {settings.openrouter_api_key}", | ||
| "Content-Type": "application/json", | ||
| } | ||
|
|
||
| tts_url = f"{settings.openrouter_base_url}/audio/speech" | ||
| try: | ||
| async with httpx.AsyncClient(timeout=120.0) as client: | ||
| response = await client.post(tts_url, json=payload, headers=headers) | ||
| response.raise_for_status() | ||
| except httpx.HTTPStatusError as exc: | ||
| logger.error( | ||
| "[generate_tts] OpenRouter returned %d url=%s", | ||
| exc.response.status_code, | ||
| tts_url, | ||
| ) | ||
| raise RuntimeError( | ||
| f"TTS API request failed with status {exc.response.status_code}." | ||
| ) from exc | ||
| except httpx.RequestError as exc: | ||
| logger.error("[generate_tts] request error url=%s: %s", tts_url, exc) | ||
| raise RuntimeError("TTS API request failed due to a network error.") from exc | ||
|
|
||
| audio_bytes = response.content | ||
|
|
||
| # Validate the response is non-empty and looks like an MP3 before uploading. | ||
| content_type = response.headers.get("content-type", "") | ||
| mp3_magic = audio_bytes[:3] if len(audio_bytes) >= 3 else b"" | ||
| is_mp3_magic = mp3_magic == b"ID3" or (len(audio_bytes) >= 2 and audio_bytes[0] == 0xFF and (audio_bytes[1] & 0xE0) == 0xE0) | ||
| if not audio_bytes or (not content_type.startswith("audio/") and not is_mp3_magic): | ||
| logger.error( | ||
| "[generate_tts] unexpected TTS response status=%d content-type=%s bytes=%d", | ||
| response.status_code, | ||
| content_type, | ||
| len(audio_bytes), | ||
| ) | ||
| raise RuntimeError("TTS API returned an invalid or empty audio response.") | ||
|
|
||
| file_uuid = uuid4() | ||
| filename = f"{user_id}/{file_uuid}.mp3" | ||
| logger.info( | ||
| "[generate_tts] synthesized %d bytes uuid=%s", len(audio_bytes), file_uuid | ||
| ) | ||
| return audio_bytes, filename | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
|
|
||
| async def upload_audio(audio_bytes: bytes, filename: str) -> str: | ||
| """Upload mp3 bytes to Supabase Storage and return a signed URL (1 week). | ||
|
|
||
| Args: | ||
| audio_bytes: Raw MP3 bytes to upload. | ||
| filename: Storage path in the form ``{user_id}/{uuid}.mp3``. | ||
|
|
||
| Returns: | ||
| A signed URL valid for 7 days. | ||
|
|
||
| Raises: | ||
| RuntimeError: If the Supabase Storage upload or URL generation fails. | ||
| """ | ||
| client = await get_supabase_client() | ||
| bucket = settings.audio_bucket | ||
|
|
||
| # Use only the basename (UUID part) in logs — never the full path (contains user_id). | ||
| safe_log_name = filename.split("/")[-1] if "/" in filename else filename | ||
|
|
||
| try: | ||
| await client.storage.from_(bucket).upload( | ||
| path=filename, | ||
| file=audio_bytes, | ||
| file_options={"content-type": "audio/mpeg"}, | ||
| ) | ||
| except Exception as exc: | ||
| logger.exception("[upload_audio] Storage upload failed uuid=%s", safe_log_name) | ||
| raise RuntimeError("Failed to upload audio to storage.") from exc | ||
|
|
||
| try: | ||
| result = await client.storage.from_(bucket).create_signed_url( | ||
| filename, _SIGNED_URL_TTL | ||
| ) | ||
| signed_url: str = result["signedURL"] | ||
| except Exception as exc: | ||
| logger.exception( | ||
| "[upload_audio] Failed to create signed URL uuid=%s", safe_log_name | ||
| ) | ||
| raise RuntimeError("Audio uploaded but could not generate a signed URL.") from exc | ||
|
|
||
| logger.info("[upload_audio] signed URL created uuid=%s", safe_log_name) | ||
| return signed_url | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.