refactor(transcription): share JSON request retries

This commit is contained in:
chengyongru authored and chengyongru committed 2026-10-14 14:35:08 +08:00
1 parent bdb6c369d0
commit 47f600afc6
2 files changed
+53 -97

No files matched your search

+24 -97
View File
@@ -11,7 +11,8 @@ import base64
import json import json
import mimetypes import mimetypes
import os import os
from collections.abc import Callable from collections.abc import Awaitable, Callable
from functools import partial
from pathlib import Path from pathlib import Path
from typing import Any, cast from typing import Any, cast
@@ -111,20 +112,13 @@ _RETRYABLE_EXCEPTIONS = (
async def _request_json_with_retry( async def _request_json_with_retry(
client: httpx.AsyncClient, request: Callable[[], Awaitable[httpx.Response]],
method: str,
url: str,
*, *,
provider_label: str, provider_label: str,
**kwargs: Any,
) -> dict[str, Any] | None: ) -> dict[str, Any] | None:
for attempt in range(_MAX_RETRIES + 1): for attempt in range(_MAX_RETRIES + 1):
try: try:
request = getattr(client, method.lower(), None) response = await request()
if request is None:
response = await client.request(method, url, **kwargs)
else:
response = await request(url, **kwargs)
except _RETRYABLE_EXCEPTIONS as e: except _RETRYABLE_EXCEPTIONS as e:
if attempt < _MAX_RETRIES: if attempt < _MAX_RETRIES:
logger.warning( logger.warning(
@@ -436,76 +430,11 @@ async def _post_with_retry(
extract_text: Callable[[dict[str, Any]], str], extract_text: Callable[[dict[str, Any]], str],
) -> str: ) -> str:
async with httpx.AsyncClient() as client: async with httpx.AsyncClient() as client:
for attempt in range(_MAX_RETRIES + 1): payload = await _request_json_with_retry(
try: lambda: client.post(**build_request()),
response = await client.post(**build_request()) provider_label=provider_label,
except _RETRYABLE_EXCEPTIONS as e: )
if attempt < _MAX_RETRIES: return extract_text(payload) if payload is not None else ""
logger.warning(
"{} transcription transient error (attempt {}/{}): {}",
provider_label,
attempt + 1,
_MAX_RETRIES + 1,
e,
)
await asyncio.sleep(_BACKOFF_S[attempt])
continue
logger.exception(
"{} transcription error after {} attempts: {}",
provider_label,
_MAX_RETRIES + 1,
e,
)
return ""
except Exception as e:
logger.exception("{} transcription error: {}", provider_label, e)
return ""
if response.status_code in _RETRYABLE_STATUS and attempt < _MAX_RETRIES:
logger.warning(
"{} transcription transient HTTP {} (attempt {}/{})",
provider_label,
response.status_code,
attempt + 1,
_MAX_RETRIES + 1,
)
await asyncio.sleep(_BACKOFF_S[attempt])
continue
try:
response.raise_for_status()
except httpx.HTTPStatusError:
body = response.text.strip().replace("\n", " ")[:500]
logger.error(
"{} transcription HTTP {}{}{}",
provider_label,
response.status_code,
f" {response.reason_phrase}" if response.reason_phrase else "",
f": {body}" if body else "",
)
return ""
except Exception as e:
logger.exception("{} transcription error: {}", provider_label, e)
return ""
try:
payload = response.json()
except Exception as e:
logger.exception(
"{} transcription error: malformed response body: {}",
provider_label,
e,
)
return ""
if not isinstance(payload, dict):
logger.error(
"{} transcription error: unexpected response shape: {!r}",
provider_label,
type(payload).__name__,
)
return ""
return extract_text(cast(dict[str, Any], payload))
return ""
def _text_from_transcription_payload(payload: dict[str, Any]) -> str: def _text_from_transcription_payload(payload: dict[str, Any]) -> str:
@@ -560,13 +489,14 @@ class AssemblyAITranscriptionProvider:
headers = {"Authorization": self.api_key} headers = {"Authorization": self.api_key}
async with httpx.AsyncClient() as client: async with httpx.AsyncClient() as client:
upload = await _request_json_with_retry( upload = await _request_json_with_retry(
client, partial(
"POST", client.post,
self.upload_url, self.upload_url,
headers={**headers, "Content-Type": "application/octet-stream"},
content=data,
timeout=60.0,
),
provider_label="AssemblyAI", provider_label="AssemblyAI",
headers={**headers, "Content-Type": "application/octet-stream"},
content=data,
timeout=60.0,
) )
upload_url = upload.get("upload_url") if upload else None upload_url = upload.get("upload_url") if upload else None
if not isinstance(upload_url, str) or not upload_url: if not isinstance(upload_url, str) or not upload_url:
@@ -581,13 +511,14 @@ class AssemblyAITranscriptionProvider:
body["language_code"] = self.language body["language_code"] = self.language
transcript = await _request_json_with_retry( transcript = await _request_json_with_retry(
client, partial(
"POST", client.post,
self.transcript_url, self.transcript_url,
headers=headers,
json=body,
timeout=30.0,
),
provider_label="AssemblyAI", provider_label="AssemblyAI",
headers=headers,
json=body,
timeout=30.0,
) )
transcript_id = transcript.get("id") if transcript else None transcript_id = transcript.get("id") if transcript else None
if not isinstance(transcript_id, str) or not transcript_id: if not isinstance(transcript_id, str) or not transcript_id:
@@ -597,12 +528,8 @@ class AssemblyAITranscriptionProvider:
poll_url = f"{self.transcript_url.rstrip('/')}/{transcript_id}" poll_url = f"{self.transcript_url.rstrip('/')}/{transcript_id}"
for attempt in range(_ASSEMBLYAI_POLL_ATTEMPTS): for attempt in range(_ASSEMBLYAI_POLL_ATTEMPTS):
payload = await _request_json_with_retry( payload = await _request_json_with_retry(
client, partial(client.get, poll_url, headers=headers, timeout=30.0),
"GET",
poll_url,
provider_label="AssemblyAI", provider_label="AssemblyAI",
headers=headers,
timeout=30.0,
) )
if not payload: if not payload:
return "" return ""
+29
View File
@@ -879,6 +879,35 @@ async def test_assemblyai_uploads_creates_and_polls(audio_file: Path) -> None:
assert get.await_args.args == ("https://assembly.example/v2/transcript/tr_123",) assert get.await_args.args == ("https://assembly.example/v2/transcript/tr_123",)
@pytest.mark.asyncio
async def test_assemblyai_retries_transient_upload_and_poll_errors(audio_file: Path) -> None:
provider = AssemblyAITranscriptionProvider(api_key="aai-test")
post = AsyncMock(side_effect=[
_json_response(503, {}, url=provider.upload_url),
_json_response(200, {"upload_url": "https://cdn.example/audio"}, url=provider.upload_url),
_json_response(200, {"id": "tr_retry"}, url=provider.transcript_url),
])
poll_url = f"{provider.transcript_url}/tr_retry"
get = AsyncMock(side_effect=[
httpx.ReadError("connection lost"),
_json_response(200, {"status": "completed", "text": "recovered"}, method="GET", url=poll_url),
])
sleep = AsyncMock()
with patch("httpx.AsyncClient.post", post), patch("httpx.AsyncClient.get", get), patch(
"asyncio.sleep", sleep
):
assert await provider.transcribe(audio_file) == "recovered"
assert post.await_count == 3
assert get.await_count == 2
for upload_call in post.await_args_list[:2]:
assert upload_call.args == (provider.upload_url,)
assert upload_call.kwargs["content"] == audio_file.read_bytes()
assert get.await_args.args == (poll_url,)
assert [call.args for call in sleep.await_args_list] == [(1.0,), (1.0,)]
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_assemblyai_polls_until_completed(audio_file: Path) -> None: async def test_assemblyai_polls_until_completed(audio_file: Path) -> None:
provider = AssemblyAITranscriptionProvider(api_key="aai-test") provider = AssemblyAITranscriptionProvider(api_key="aai-test")