From e709f36ea61c4a5d2692e7c05fa18af2642949a6 Mon Sep 17 00:00:00 2001 From: hiyaa-atFonada Date: Fri, 13 Nov 2026 14:36:58 +0530 Subject: [PATCH 1/2] feat: add FonadaLabs speech-to-text provider --- CHANGELOG.md | 8 + docs/providers/README.md | 2 + docs/providers/fonadalabs.md | 24 +++ src/esperanto/__init__.py | 6 +- src/esperanto/factory.py | 1 + src/esperanto/model_discovery.py | 6 + src/esperanto/providers/stt/AGENTS.md | 1 + src/esperanto/providers/stt/fonadalabs.py | 250 ++++++++++++++++++++++ tests/providers/stt/test_fonadalabs.py | 178 +++++++++++++++ 9 files changed, 475 insertions(+), 1 deletion(-) create mode 100644 docs/providers/fonadalabs.md create mode 100644 src/esperanto/providers/stt/fonadalabs.py create mode 100644 tests/providers/stt/test_fonadalabs.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 5604a195..0864898c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- FonadaLabs honors longer Retry-After cooldowns and logs generated request IDs, status and elapsed time without exposing request content. + +- FonadaLabs waits 60 seconds and retries once on HTTP 429; timeouts and other failures are not automatically retried. + +- Native FonadaLabs Kapture V3 speech-to-text with customer API keys, explicit language mapping, a 25 MB upload guard and no automatic request retries. + ## [2.28.0] - 2026-10-03 ### Added diff --git a/docs/providers/README.md b/docs/providers/README.md index 79e1e25e..a252a10a 100644 --- a/docs/providers/README.md +++ b/docs/providers/README.md @@ -31,6 +31,7 @@ Welcome to the Esperanto provider guide. This page helps you choose the right AI | [Voyage](./voyage.md) | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | | [Cohere](./cohere.md) | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | | [ElevenLabs](./elevenlabs.md) | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | +| [FonadaLabs](./fonadalabs.md) | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | *⚠️ OpenAI-Compatible: JSON mode support depends on the specific endpoint implementation @@ -342,6 +343,7 @@ Require API keys, pay-per-use: - [Voyage](./voyage.md) - [Cohere](./cohere.md) - [ElevenLabs](./elevenlabs.md) +- [FonadaLabs](./fonadalabs.md) ### Cloud Enterprise Providers diff --git a/docs/providers/fonadalabs.md b/docs/providers/fonadalabs.md new file mode 100644 index 00000000..0b85d093 --- /dev/null +++ b/docs/providers/fonadalabs.md @@ -0,0 +1,24 @@ +# FonadaLabs + +Native Kapture V3 speech-to-text over `POST https://api.fonada.ai/v3/asr/transcribe`. Audio is processed in Fonada's cloud using customer-owned credits. + +```python +import os +from esperanto import AIFactory + +model = AIFactory.create_speech_to_text( + "fonadalabs", "kapture-v3", {"api_key": os.environ["FONADALABS_API_KEY"]} +) +result = await model.atranscribe("lecture.mp3", language="hi") +print(result.text) +``` + +`FONADALABS_API_KEY` is also the environment fallback. `language` maps to multipart `language_id`; config `language` and then `FONADALABS_LANGUAGE` are fallbacks, defaulting to English (`en`). The endpoint does not promise automatic language detection. Both synchronous and asynchronous methods accept paths or binary streams. Prompt guidance is unsupported and raises ValueError. + +Kapture V3 supports `en`, `bn`, `gu`, `hi`, `kn`, `ml`, `mr`, `or`, `pa`, `ta` and `te`. Send the code for the recording language. An unsupported code is rejected by Fonada before transcription. + +Uploads must be nonempty and at most 25,000,000 bytes. Extract video audio and split larger recordings in the calling application's media layer. HTTP 429 waits 60 seconds and retries the same chunk once; a second failure stops. Other HTTP failures, including 502/503/504, and transport errors are not automatically retried: a timeout or gateway response may follow a successful billed request. Errors identify invalid keys, denied access, exhausted credits, upload limits, invalid audio/language and rate limits without echoing response bodies or secrets. + +The response maps actual `text`, `transcript` or `transcription` fields, including the `result` envelope, to `TranscriptionResponse.text`. Timings, usage, duration and speaker labels remain absent. Model discovery returns `kapture-v3` statically and does not validate a key or consume credits. + +An optional `base_url` accepts either `https://api.fonada.ai/v3/asr` or the complete `/v3/asr/transcribe` endpoint, with or without a trailing slash. The provider appends the transcription path only once. diff --git a/src/esperanto/__init__.py b/src/esperanto/__init__.py index 351747e2..8ef16d03 100644 --- a/src/esperanto/__init__.py +++ b/src/esperanto/__init__.py @@ -219,4 +219,8 @@ "CohereLanguageModel", "CohereEmbeddingModel", "CohereRerankerModel", -] \ No newline at end of file +] +try: + from esperanto.providers.stt.fonadalabs import FonadaLabsSpeechToTextModel +except ImportError: + FonadaLabsSpeechToTextModel = None # type: ignore[assignment,misc] diff --git a/src/esperanto/factory.py b/src/esperanto/factory.py index 0c1ecc10..8ca539e9 100644 --- a/src/esperanto/factory.py +++ b/src/esperanto/factory.py @@ -48,6 +48,7 @@ class AIFactory: "cohere": "esperanto.providers.embedding.cohere:CohereEmbeddingModel", }, "speech_to_text": { + "fonadalabs": "esperanto.providers.stt.fonadalabs:FonadaLabsSpeechToTextModel", "openai": "esperanto.providers.stt.openai:OpenAISpeechToTextModel", "groq": "esperanto.providers.stt.groq:GroqSpeechToTextModel", "elevenlabs": "esperanto.providers.stt.elevenlabs:ElevenLabsSpeechToTextModel", diff --git a/src/esperanto/model_discovery.py b/src/esperanto/model_discovery.py index 3758e710..bf1e1613 100644 --- a/src/esperanto/model_discovery.py +++ b/src/esperanto/model_discovery.py @@ -1225,8 +1225,14 @@ def get_cohere_models( raise RuntimeError(f"Failed to fetch Cohere models: {e}") +def get_fonadalabs_models(api_key: Optional[str] = None, **kwargs) -> List[Model]: + """Static catalog; discovery does not validate credentials or bill audio.""" + return [Model(id="kapture-v3", owned_by="FonadaLabs", type="speech_to_text")] + + # Provider registry mapping provider names to discovery functions PROVIDER_MODELS_REGISTRY: Dict[str, Callable[..., List[Model]]] = { + "fonadalabs": get_fonadalabs_models, "openai": get_openai_models, "openai-compatible": get_openai_compatible_models, "anthropic": get_anthropic_models, diff --git a/src/esperanto/providers/stt/AGENTS.md b/src/esperanto/providers/stt/AGENTS.md index 081cd6c5..126e47a8 100644 --- a/src/esperanto/providers/stt/AGENTS.md +++ b/src/esperanto/providers/stt/AGENTS.md @@ -12,6 +12,7 @@ Speech-to-text (STT) provider implementations for audio transcription. - **`elevenlabs.py`**: ElevenLabs speech recognition - **`openai_compatible.py`**: Generic OpenAI-compatible STT API - **`mistral.py`**: Mistral transcription API +- **`fonadalabs.py`**: Native Kapture V3 REST API; 25 MB uploads, language_id, plain text, no retries - **`deepgram.py`**: Deepgram transcription API - **`openrouter.py`**: OpenRouter transcription API diff --git a/src/esperanto/providers/stt/fonadalabs.py b/src/esperanto/providers/stt/fonadalabs.py new file mode 100644 index 00000000..a0553281 --- /dev/null +++ b/src/esperanto/providers/stt/fonadalabs.py @@ -0,0 +1,250 @@ +"""FonadaLabs Kapture V3 transcription over the native REST API.""" + +import asyncio +import logging +import os +import time +from dataclasses import dataclass +from datetime import datetime, timezone +from email.utils import parsedate_to_datetime +from pathlib import Path +from typing import BinaryIO, List, Optional, Union +from uuid import uuid4 + +import httpx + +from esperanto.common_types import TranscriptionResponse +from esperanto.providers.stt.base import ( + Model, + SpeechToTextModel, + _guess_audio_content_type, +) + +logger = logging.getLogger(__name__) + +MAX_UPLOAD_BYTES = 25_000_000 + + +class FonadaLabsAPIError(RuntimeError): + """Sanitized provider failure carrying a machine-readable HTTP status.""" + + def __init__(self, status_code: int, message: str): + self.status_code = status_code + super().__init__(message) + + +@dataclass +class FonadaLabsSpeechToTextModel(SpeechToTextModel): + """Plain-text ASR with one delayed retry for explicit HTTP 429 responses.""" + + def __post_init__(self) -> None: + super().__post_init__() + self.api_key = self.api_key or os.getenv("FONADALABS_API_KEY") + if not self.api_key: + raise ValueError("Set FONADALABS_API_KEY or provide api_key in config.") + if self.get_model_name() != "kapture-v3": + raise ValueError("FonadaLabs supports the kapture-v3 model.") + self.base_url = (self.base_url or "https://api.fonada.ai/v3/asr").rstrip("/") + # Configuration forms may contain the documented full endpoint. + # Keep a single /transcribe suffix when constructing requests. + if self.base_url.endswith("/transcribe"): + self.base_url = self.base_url.removesuffix("/transcribe") + self._create_http_clients() + + @property + def provider(self) -> str: + return "fonadalabs" + + def _get_default_model(self) -> str: + return "kapture-v3" + + def _get_models(self) -> List[Model]: + return [Model(id="kapture-v3", owned_by="FonadaLabs", type="speech_to_text")] + + def _prepare( + self, + audio_file: Union[str, BinaryIO], + language: Optional[str], + prompt: Optional[str], + ): + if prompt: + raise ValueError("FonadaLabs does not support transcription prompts.") + language_id = ( + language + or self._config.get("language") + or os.getenv("FONADALABS_LANGUAGE", "en") + ) + if not isinstance(language_id, str) or not language_id.strip(): + raise ValueError("A non-empty FonadaLabs language code is required.") + if isinstance(audio_file, str): + filename = Path(audio_file).name + with open(audio_file, "rb") as stream: + data = stream.read(MAX_UPLOAD_BYTES + 1) + else: + filename = Path(str(getattr(audio_file, "name", "audio.wav"))).name + data = audio_file.read(MAX_UPLOAD_BYTES + 1) + if not data or len(data) > MAX_UPLOAD_BYTES: + raise ValueError( + "FonadaLabs requires non-empty audio up to 25 MB; split larger recordings." + ) + return {"file": (filename, data, _guess_audio_content_type(filename))}, { + "language_id": language_id.strip() + } + + @staticmethod + def _rate_limit_delay(response: httpx.Response) -> float: + """Wait at least one minute and honor a longer server cooldown.""" + value = response.headers.get("retry-after", "").strip() + try: + seconds = float(int(value)) + except ValueError: + try: + deadline = parsedate_to_datetime(value) + if deadline.tzinfo is None: + deadline = deadline.replace(tzinfo=timezone.utc) + seconds = (deadline - datetime.now(timezone.utc)).total_seconds() + except (ValueError, TypeError, OverflowError): + seconds = 60 + # Do not occupy a worker indefinitely for a long quota suspension. + if seconds > 3600: + raise FonadaLabsAPIError( + 429, + "FonadaLabs requests a cooldown longer than one hour. Retry later after checking account limits.", + ) + return max(60, seconds) + + def _response(self, response: httpx.Response) -> TranscriptionResponse: + if not response.is_success: + messages = { + 401: "Invalid API key", + 403: "Access denied", + 402: "Credits exhausted", + 413: "Audio exceeds 25 MB", + 422: "Unsupported audio or language", + 429: "Rate or credit limit reached", + } + message = messages.get(response.status_code, "Transcription request failed") + logger.warning( + "FonadaLabs transcription failed: HTTP %s (%s)", + response.status_code, + message, + ) + raise FonadaLabsAPIError( + response.status_code, + f"FonadaLabs HTTP {response.status_code}: {message}. Check request status before retrying.", + ) + try: + payload = response.json() + if isinstance(payload, dict) and isinstance(payload.get("result"), dict): + payload = payload["result"] + if not isinstance(payload, dict): + raise ValueError("Expected object") + text = next( + ( + payload[key] + for key in ("text", "transcript", "transcription") + if isinstance(payload.get(key), str) + ), + None, + ) + if text is None: + raise ValueError("Missing text") + except (ValueError, TypeError): + raise RuntimeError( + "FonadaLabs returned an unrecognized transcription response." + ) from None + return TranscriptionResponse( + text=text, model=self.get_model_name(), provider=self.provider + ) + + def _post(self, files, data): + request_id = uuid4().hex + started = time.monotonic() + response = self.client.post( + f"{self.base_url}/transcribe", + headers={ + "Authorization": f"Bearer {self.api_key}", + "X-Request-ID": request_id, + }, + files=files, + data=data, + ) + logger.info( + "FonadaLabs ASR request_id=%s status=%s elapsed_seconds=%.2f", + request_id, + response.status_code, + time.monotonic() - started, + ) + return response + + async def _apost(self, files, data): + request_id = uuid4().hex + started = time.monotonic() + response = await self.async_client.post( + f"{self.base_url}/transcribe", + headers={ + "Authorization": f"Bearer {self.api_key}", + "X-Request-ID": request_id, + }, + files=files, + data=data, + ) + logger.info( + "FonadaLabs ASR request_id=%s status=%s elapsed_seconds=%.2f", + request_id, + response.status_code, + time.monotonic() - started, + ) + return response + + def transcribe( + self, + audio_file: Union[str, BinaryIO], + language: Optional[str] = None, + prompt: Optional[str] = None, + ) -> TranscriptionResponse: + files, data = self._prepare(audio_file, language, prompt) + try: + response = self._post(files, data) + if response.status_code == 429: + delay = self._rate_limit_delay(response) + logger.warning( + "FonadaLabs rate limit: waiting %s seconds before one retry", delay + ) + time.sleep(delay) + response = self._post(files, data) + except httpx.HTTPError as error: + logger.warning( + "FonadaLabs transcription transport failure: %s", type(error).__name__ + ) + raise RuntimeError( + "FonadaLabs connection or timeout error; request may already be billed. Check before retrying." + ) from None + return self._response(response) + + async def atranscribe( + self, + audio_file: Union[str, BinaryIO], + language: Optional[str] = None, + prompt: Optional[str] = None, + ) -> TranscriptionResponse: + files, data = await asyncio.to_thread( + self._prepare, audio_file, language, prompt + ) + try: + response = await self._apost(files, data) + if response.status_code == 429: + delay = self._rate_limit_delay(response) + logger.warning( + "FonadaLabs rate limit: waiting %s seconds before one retry", delay + ) + await asyncio.sleep(delay) + response = await self._apost(files, data) + except httpx.HTTPError as error: + logger.warning( + "FonadaLabs transcription transport failure: %s", type(error).__name__ + ) + raise RuntimeError( + "FonadaLabs connection or timeout error; request may already be billed. Check before retrying." + ) from None + return self._response(response) diff --git a/tests/providers/stt/test_fonadalabs.py b/tests/providers/stt/test_fonadalabs.py new file mode 100644 index 00000000..3767b648 --- /dev/null +++ b/tests/providers/stt/test_fonadalabs.py @@ -0,0 +1,178 @@ +"""Native REST contract tests, with no paid requests.""" + +from io import BytesIO + +import httpx +import pytest + +from esperanto import AIFactory +from esperanto.providers.stt.fonadalabs import MAX_UPLOAD_BYTES + + +@pytest.fixture +def model(): + return AIFactory.create_speech_to_text( + "fonadalabs", "kapture-v3", {"api_key": "test-only"} + ) + + +@pytest.mark.asyncio +async def test_native_request_and_response(model): + calls = [] + + async def handler(request): + calls.append(request) + assert str(request.url) == "https://api.fonada.ai/v3/asr/transcribe" + assert request.headers["authorization"] == "Bearer test-only" + body = await request.aread() + assert b'name="language_id"\r\n\r\nhi' in body + assert b'name="file"' in body + return httpx.Response(200, json={"result": {"transcript": "lecture text"}}) + + await model.async_client.aclose() + async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client: + model.async_client = client + result = await model.atranscribe(BytesIO(b"audio"), language="hi") + model.client.close() + assert result.text == "lecture text" + assert result.segments is None + assert result.duration is None + assert result.provider == "fonadalabs" + assert len(calls) == 1 + + +@pytest.mark.parametrize("status", [401, 402, 403, 413, 422, 429, 500, 502]) +def test_errors_are_sanitized_without_retries(model, status, monkeypatch): + waits = [] + monkeypatch.setattr("esperanto.providers.stt.fonadalabs.time.sleep", waits.append) + calls = [] + + def handler(request): + calls.append(request) + return httpx.Response(status, text="sensitive upstream contents") + + model.client.close() + with httpx.Client(transport=httpx.MockTransport(handler)) as client: + model.client = client + with pytest.raises(RuntimeError, match=f"HTTP {status}") as error: + model.transcribe(BytesIO(b"audio"), language="en") + assert "sensitive" not in str(error.value) + assert len(calls) == (2 if status == 429 else 1) + assert waits == ([60] if status == 429 else []) + + +@pytest.mark.asyncio +async def test_timeout_is_not_retried(model): + calls = [] + + async def handler(request): + calls.append(request) + raise httpx.ReadTimeout("private details") + + await model.async_client.aclose() + async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client: + model.async_client = client + with pytest.raises(RuntimeError, match="already be billed"): + await model.atranscribe(BytesIO(b"audio")) + model.client.close() + assert len(calls) == 1 + + +def test_size_and_prompt_validation(model): + for data in (b"", b"a" * (MAX_UPLOAD_BYTES + 1)): + with pytest.raises(ValueError, match="25 MB"): + model.transcribe(BytesIO(data)) + with pytest.raises(ValueError, match="prompts"): + model.transcribe(BytesIO(b"audio"), prompt="unsupported") + model.client.close() + + +def test_static_discovery(): + assert AIFactory.get_provider_models("fonadalabs")[0].id == "kapture-v3" + + +@pytest.mark.parametrize( + "base_url", + [ + "https://api.fonada.ai/v3/asr", + "https://api.fonada.ai/v3/asr/", + "https://api.fonada.ai/v3/asr/transcribe", + "https://api.fonada.ai/v3/asr/transcribe/", + ], +) +@pytest.mark.asyncio +async def test_full_endpoint_and_base_url(base_url): + model = AIFactory.create_speech_to_text( + "fonadalabs", + "kapture-v3", + { + "api_key": "test-only", + "base_url": base_url, + }, + ) + + def handler(request): + assert str(request.url) == "https://api.fonada.ai/v3/asr/transcribe" + return httpx.Response(200, json={"text": "ok"}) + + model.client.close() + await model.async_client.aclose() + with httpx.Client(transport=httpx.MockTransport(handler)) as client: + model.client = client + assert model.transcribe(BytesIO(b"test")).text == "ok" + async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client: + model.async_client = client + assert (await model.atranscribe(BytesIO(b"test"))).text == "ok" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("second_status", [200, 429, 502]) +async def test_rate_limit_waits_one_minute_then_retries_once( + model, monkeypatch, second_status +): + from unittest.mock import AsyncMock + + wait = AsyncMock() + monkeypatch.setattr("esperanto.providers.stt.fonadalabs.asyncio.sleep", wait) + calls = [] + + async def handler(request): + calls.append(await request.aread()) + status = 429 if len(calls) == 1 else second_status + return httpx.Response(status, json={"text": "resumed"}) + + await model.async_client.aclose() + async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client: + model.async_client = client + if second_status == 200: + assert (await model.atranscribe(BytesIO(b"same audio"))).text == "resumed" + else: + with pytest.raises(RuntimeError, match=f"HTTP {second_status}"): + await model.atranscribe(BytesIO(b"same audio")) + model.client.close() + wait.assert_awaited_once_with(60) + assert len(calls) == 2 + assert all(b"same audio" in body for body in calls) + + +@pytest.mark.parametrize( + "value,expected", [("120", 120), ("5", 60), ("invalid", 60), ("-2", 60)] +) +def test_retry_after_numeric_and_invalid(model, value, expected): + response = httpx.Response(429, headers={"Retry-After": value}) + assert model._rate_limit_delay(response) == expected + model.client.close() + + +def test_retry_after_date_and_long_suspension(model): + from datetime import datetime, timedelta, timezone + from email.utils import format_datetime + + deadline = datetime.now(timezone.utc) + timedelta(seconds=180) + delay = model._rate_limit_delay( + httpx.Response(429, headers={"Retry-After": format_datetime(deadline)}) + ) + assert 178 <= delay <= 180 + with pytest.raises(RuntimeError, match="longer than one hour"): + model._rate_limit_delay(httpx.Response(429, headers={"Retry-After": "7200"})) + model.client.close() From d956354f25aa8135100ec7e1a355cd59206c63ea Mon Sep 17 00:00:00 2001 From: hiyaa-atFonada Date: Fri, 13 Nov 2026 15:34:27 +0530 Subject: [PATCH 2/2] fix: harden FonadaLabs provider integration --- CHANGELOG.md | 6 +++--- docs/providers/fonadalabs.md | 2 +- src/esperanto/__init__.py | 10 ++++++---- src/esperanto/model_discovery.py | 3 ++- src/esperanto/providers/stt/AGENTS.md | 2 +- src/esperanto/providers/stt/fonadalabs.py | 11 ++++++++--- tests/providers/stt/test_fonadalabs.py | 10 ++++++++++ 7 files changed, 31 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0864898c..cc930720 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,11 +9,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added -- FonadaLabs honors longer Retry-After cooldowns and logs generated request IDs, status and elapsed time without exposing request content. +- FonadaLabs honors Retry-After cooldowns up to one hour and logs generated request IDs, status and elapsed time without exposing request content. -- FonadaLabs waits 60 seconds and retries once on HTTP 429; timeouts and other failures are not automatically retried. +- FonadaLabs waits at least 60 seconds (or the Retry-After cooldown, up to one hour) and retries once on HTTP 429; timeouts and other failures are not automatically retried. -- Native FonadaLabs Kapture V3 speech-to-text with customer API keys, explicit language mapping, a 25 MB upload guard and no automatic request retries. +- Native FonadaLabs Kapture V3 speech-to-text with customer API keys, explicit language mapping, a 25 MB upload guard and no automatic retries other than one HTTP 429 retry. ## [2.28.0] - 2026-10-03 diff --git a/docs/providers/fonadalabs.md b/docs/providers/fonadalabs.md index 0b85d093..1f052b54 100644 --- a/docs/providers/fonadalabs.md +++ b/docs/providers/fonadalabs.md @@ -17,7 +17,7 @@ print(result.text) Kapture V3 supports `en`, `bn`, `gu`, `hi`, `kn`, `ml`, `mr`, `or`, `pa`, `ta` and `te`. Send the code for the recording language. An unsupported code is rejected by Fonada before transcription. -Uploads must be nonempty and at most 25,000,000 bytes. Extract video audio and split larger recordings in the calling application's media layer. HTTP 429 waits 60 seconds and retries the same chunk once; a second failure stops. Other HTTP failures, including 502/503/504, and transport errors are not automatically retried: a timeout or gateway response may follow a successful billed request. Errors identify invalid keys, denied access, exhausted credits, upload limits, invalid audio/language and rate limits without echoing response bodies or secrets. +Uploads must be nonempty and at most 25,000,000 bytes. Extract video audio and split larger recordings in the calling application's media layer. HTTP 429 waits at least 60 seconds and honors a longer `Retry-After` cooldown up to one hour, then retries the same chunk once. A cooldown longer than one hour fails immediately without retrying. Other HTTP failures, including 502/503/504, and transport errors are not automatically retried: a timeout or gateway response may follow a successful billed request. Errors identify invalid keys, denied access, exhausted credits, upload limits, invalid audio/language and rate limits without echoing response bodies or secrets. The response maps actual `text`, `transcript` or `transcription` fields, including the `result` envelope, to `TranscriptionResponse.text`. Timings, usage, duration and speaker labels remain absent. Model discovery returns `kapture-v3` statically and does not validate a key or consume credits. diff --git a/src/esperanto/__init__.py b/src/esperanto/__init__.py index 8ef16d03..ed639365 100644 --- a/src/esperanto/__init__.py +++ b/src/esperanto/__init__.py @@ -124,6 +124,11 @@ except ImportError: MistralSpeechToTextModel = None # type: ignore[assignment,misc] +try: + from esperanto.providers.stt.fonadalabs import FonadaLabsSpeechToTextModel +except ImportError: + FonadaLabsSpeechToTextModel = None # type: ignore[assignment,misc] + try: from esperanto.providers.tts.deepgram import DeepgramTextToSpeechModel except ImportError: @@ -211,6 +216,7 @@ "VertexTextToSpeechModel", "MistralTextToSpeechModel", "MistralSpeechToTextModel", + "FonadaLabsSpeechToTextModel", "DeepgramTextToSpeechModel", "DeepgramSpeechToTextModel", "OpenRouterTextToSpeechModel", @@ -220,7 +226,3 @@ "CohereEmbeddingModel", "CohereRerankerModel", ] -try: - from esperanto.providers.stt.fonadalabs import FonadaLabsSpeechToTextModel -except ImportError: - FonadaLabsSpeechToTextModel = None # type: ignore[assignment,misc] diff --git a/src/esperanto/model_discovery.py b/src/esperanto/model_discovery.py index bf1e1613..d3754cd8 100644 --- a/src/esperanto/model_discovery.py +++ b/src/esperanto/model_discovery.py @@ -11,6 +11,7 @@ import httpx from esperanto.common_types import Model +from esperanto.providers.stt.fonadalabs import FONADALABS_MODELS from esperanto.utils import ModelCache # Global cache instance for model discovery @@ -1227,7 +1228,7 @@ def get_cohere_models( def get_fonadalabs_models(api_key: Optional[str] = None, **kwargs) -> List[Model]: """Static catalog; discovery does not validate credentials or bill audio.""" - return [Model(id="kapture-v3", owned_by="FonadaLabs", type="speech_to_text")] + return list(FONADALABS_MODELS) # Provider registry mapping provider names to discovery functions diff --git a/src/esperanto/providers/stt/AGENTS.md b/src/esperanto/providers/stt/AGENTS.md index 126e47a8..5bc7bcd5 100644 --- a/src/esperanto/providers/stt/AGENTS.md +++ b/src/esperanto/providers/stt/AGENTS.md @@ -12,7 +12,7 @@ Speech-to-text (STT) provider implementations for audio transcription. - **`elevenlabs.py`**: ElevenLabs speech recognition - **`openai_compatible.py`**: Generic OpenAI-compatible STT API - **`mistral.py`**: Mistral transcription API -- **`fonadalabs.py`**: Native Kapture V3 REST API; 25 MB uploads, language_id, plain text, no retries +- **`fonadalabs.py`**: Native Kapture V3 REST API; 25 MB uploads, language_id, plain text, one HTTP 429 retry only - **`deepgram.py`**: Deepgram transcription API - **`openrouter.py`**: OpenRouter transcription API diff --git a/src/esperanto/providers/stt/fonadalabs.py b/src/esperanto/providers/stt/fonadalabs.py index a0553281..8fb92fa1 100644 --- a/src/esperanto/providers/stt/fonadalabs.py +++ b/src/esperanto/providers/stt/fonadalabs.py @@ -23,6 +23,9 @@ logger = logging.getLogger(__name__) MAX_UPLOAD_BYTES = 25_000_000 +FONADALABS_MODELS = [ + Model(id="kapture-v3", owned_by="FonadaLabs", type="speech_to_text") +] class FonadaLabsAPIError(RuntimeError): @@ -59,7 +62,7 @@ def _get_default_model(self) -> str: return "kapture-v3" def _get_models(self) -> List[Model]: - return [Model(id="kapture-v3", owned_by="FonadaLabs", type="speech_to_text")] + return list(FONADALABS_MODELS) def _prepare( self, @@ -72,7 +75,8 @@ def _prepare( language_id = ( language or self._config.get("language") - or os.getenv("FONADALABS_LANGUAGE", "en") + or os.getenv("FONADALABS_LANGUAGE") + or "en" ) if not isinstance(language_id, str) or not language_id.strip(): raise ValueError("A non-empty FonadaLabs language code is required.") @@ -81,7 +85,8 @@ def _prepare( with open(audio_file, "rb") as stream: data = stream.read(MAX_UPLOAD_BYTES + 1) else: - filename = Path(str(getattr(audio_file, "name", "audio.wav"))).name + stream_name = getattr(audio_file, "name", None) + filename = Path(stream_name).name if isinstance(stream_name, str) and stream_name else "audio.wav" data = audio_file.read(MAX_UPLOAD_BYTES + 1) if not data or len(data) > MAX_UPLOAD_BYTES: raise ValueError( diff --git a/tests/providers/stt/test_fonadalabs.py b/tests/providers/stt/test_fonadalabs.py index 3767b648..685fe172 100644 --- a/tests/providers/stt/test_fonadalabs.py +++ b/tests/providers/stt/test_fonadalabs.py @@ -87,6 +87,16 @@ def test_size_and_prompt_validation(model): model.client.close() +def test_empty_language_environment_and_stream_without_name_use_defaults(model, monkeypatch): + monkeypatch.setenv("FONADALABS_LANGUAGE", "") + stream = BytesIO(b"audio") + stream.name = None + files, data = model._prepare(stream, language=None, prompt=None) + assert data["language_id"] == "en" + assert files["file"][0] == "audio.wav" + model.client.close() + + def test_static_discovery(): assert AIFactory.get_provider_models("fonadalabs")[0].id == "kapture-v3"