DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
fix(voice): strip MediaRecorder codec params from STT uploads (#948)
ZQR1101ac25a5c86870
diff --git a/deeptutor/services/voice/adapters/openai_compat.py b/deeptutor/services/voice/adapters/openai_compat.pyindex db97971a8..1ceecca2b 100644--- a/deeptutor/services/voice/adapters/openai_compat.py+++ b/deeptutor/services/voice/adapters/openai_compat.py@@ -25,6 +25,7 @@ from deeptutor.services.voice.base import (VoiceProviderHTTPError,build_auth_headers,join_audio_path,+ normalize_stt_content_type,)from deeptutor.services.voice.config import STT_BASE64_JSON, STTConfig, TTSConfig@@ -329,7 +330,9 @@ class OpenAICompatSTTAdapter(BaseSTTAdapter):content_type: str,config: STTConfig,) -> httpx.Response:- files = {"file": (filename, audio, content_type or "application/octet-stream")}+ files = {+ "file": (filename, audio, normalize_stt_content_type(content_type)),+ }data: dict[str, str] = {"model": config.model, "response_format": "json"}if config.language:data["language"] = config.languagediff --git a/deeptutor/services/voice/base.py b/deeptutor/services/voice/base.pyindex 214941f55..1d934ebec 100644--- a/deeptutor/services/voice/base.py+++ b/deeptutor/services/voice/base.py@@ -72,6 +72,18 @@ def build_auth_headers(auth_style: str, api_key: str) -> dict[str, str]:return {"Authorization": f"Bearer {api_key}"}+def normalize_stt_content_type(content_type: str | None) -> str:+ """Strip MIME parameters that STT APIs reject.++ Chrome's ``MediaRecorder.mimeType`` is typically ``audio/webm;codecs=opus``.+ OpenAI-compatible transcription endpoints treat the codec parameter as an+ unknown format and return 400 (``Unsupported file format: ...``). Keep the+ type/subtype only.+ """+ media_type = (content_type or "").split(";", 1)[0].strip()+ return media_type or "application/octet-stream"++def join_audio_path(base_url: str, suffix: str) -> str:"""Append an OpenAI audio path to a configured base URL.@@ -140,5 +152,6 @@ __all__ = ["BaseSTTAdapter","build_auth_headers","join_audio_path",+ "normalize_stt_content_type","strip_markdown_for_speech",]diff --git a/tests/api/test_voice_routes.py b/tests/api/test_voice_routes.pyindex 288b0cc59..b6cd3d82e 100644--- a/tests/api/test_voice_routes.py+++ b/tests/api/test_voice_routes.py@@ -90,6 +90,7 @@ def test_stt_returns_text(client: TestClient, monkeypatch: pytest.MonkeyPatch) -async def fake_transcribe(audio: bytes, *, filename: str, content_type: str, language=None):captured["bytes"] = len(audio)captured["filename"] = filename+ captured["content_type"] = content_typereturn "hello world"monkeypatch.setattr(voice_router, "transcribe_audio", fake_transcribe)@@ -101,6 +102,31 @@ def test_stt_returns_text(client: TestClient, monkeypatch: pytest.MonkeyPatch) -assert resp.json() == {"text": "hello world"}assert captured["filename"] == "clip.webm"assert captured["bytes"] == 10+ assert captured["content_type"] == "audio/webm"+++def test_stt_forwards_the_browser_reported_mime_verbatim(+ client: TestClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The route reports what the client sent; the adapter owns wire shaping.++ Stripping the codec parameter happens once, at the boundary that puts the+ value on the wire (``OpenAICompatSTTAdapter._post_multipart``), so the route+ must not normalize it a second time.+ """+ captured: dict[str, Any] = {}++ async def fake_transcribe(audio: bytes, *, filename: str, content_type: str, language=None):+ captured["content_type"] = content_type+ return "hello"++ monkeypatch.setattr(voice_router, "transcribe_audio", fake_transcribe)+ resp = client.post(+ "/api/v1/voice/stt",+ files={"file": ("recording.webm", b"audiobytes", "audio/webm;codecs=opus")},+ )+ assert resp.status_code == 200+ assert captured["content_type"] == "audio/webm;codecs=opus"def test_stt_rejects_empty_upload(client: TestClient) -> None:diff --git a/tests/services/test_voice.py b/tests/services/test_voice.pyindex e56de99a3..df3fad7e8 100644--- a/tests/services/test_voice.py+++ b/tests/services/test_voice.py@@ -27,6 +27,7 @@ from deeptutor.services.voice.adapters.openai_compat import (from deeptutor.services.voice.base import (build_auth_headers,join_audio_path,+ normalize_stt_content_type,strip_markdown_for_speech,)from deeptutor.services.voice.config import STTConfig, TTSConfig@@ -72,6 +73,14 @@ def test_join_audio_path_appends_and_preserves_full_url() -> None:assert join_audio_path(full, "audio/speech") == full+def test_normalize_stt_content_type_strips_codec_parameters() -> None:+ assert normalize_stt_content_type("audio/webm;codecs=opus") == "audio/webm"+ assert normalize_stt_content_type(" audio/ogg; codecs=opus ") == "audio/ogg"+ assert normalize_stt_content_type("audio/wav") == "audio/wav"+ assert normalize_stt_content_type("") == "application/octet-stream"+ assert normalize_stt_content_type(None) == "application/octet-stream"++def test_auth_headers_styles() -> None:assert build_auth_headers("bearer", "k") == {"Authorization": "Bearer k"}assert build_auth_headers("api_key_header", "k") == {"api-key": "k"}@@ -232,9 +241,25 @@ async def test_stt_adapter_multipart(monkeypatch: pytest.MonkeyPatch) -> None:assert text == "hello world"assert captured["url"] == "https://api.openai.com/v1/audio/transcriptions"assert captured["files"]["file"][0] == "a.wav"+ assert captured["files"]["file"][2] == "audio/wav"assert captured["data"]["model"] == "whisper-1"+async def test_stt_adapter_strips_codec_parameters(monkeypatch: pytest.MonkeyPatch) -> None:+ resp = httpx.Response(200, json={"text": "hello world"})+ captured = _capture_post(monkeypatch, resp)+ config = STTConfig(model="whisper-1", base_url="https://api.openai.com/v1", api_key="sk")+ text = await OpenAICompatSTTAdapter().transcribe(+ b"audiobytes",+ config,+ filename="recording.webm",+ content_type="audio/webm;codecs=opus",+ )+ assert text == "hello world"+ assert captured["files"]["file"][2] == "audio/webm"++@pytest.mark.asyncioasync def test_stt_adapter_openrouter_base64(monkeypatch: pytest.MonkeyPatch) -> None:resp = httpx.Response(200, json={"text": "from base64"})@@ -348,6 +373,12 @@ async def test_synthesize_speech_facade_strips_markdown(monkeypatch: pytest.Monk@pytest.mark.asyncioasync def test_transcribe_audio_facade(monkeypatch: pytest.MonkeyPatch) -> None:resp = httpx.Response(200, json={"text": "transcribed"})- _capture_post(monkeypatch, resp)- text = await transcribe_audio(b"bytes", catalog=_voice_catalog(), filename="x.webm")+ captured = _capture_post(monkeypatch, resp)+ text = await transcribe_audio(+ b"bytes",+ catalog=_voice_catalog(),+ filename="x.webm",+ content_type="audio/webm;codecs=opus",+ )assert text == "transcribed"+ assert captured["json"]["input_audio"]["format"] == "webm"diff --git a/web/hooks/useVoiceRecorder.ts b/web/hooks/useVoiceRecorder.tsindex 7c76a573e..8d3979fb4 100644--- a/web/hooks/useVoiceRecorder.ts+++ b/web/hooks/useVoiceRecorder.ts@@ -3,6 +3,7 @@import { useCallback, useEffect, useRef, useState } from "react";import { apiFetch, apiUrl } from "@/lib/api";+import { stripAudioMimeParameters } from "@/lib/voice-mime";export type RecorderState = "idle" | "recording" | "transcribing";@@ -50,7 +51,7 @@ export function useVoiceRecorder(onTranscript: (text: string) => void) {if (event.data && event.data.size > 0) chunksRef.current.push(event.data);};recorder.onstop = async () => {- const mimeType = recorder.mimeType || "audio/webm";+ const mimeType = stripAudioMimeParameters(recorder.mimeType);releaseStream();const blob = new Blob(chunksRef.current, { type: mimeType });chunksRef.current = [];diff --git a/web/lib/voice-mime.ts b/web/lib/voice-mime.tsnew file mode 100644index 000000000..8b22815b3--- /dev/null+++ b/web/lib/voice-mime.ts@@ -0,0 +1,10 @@+/**+ * MediaRecorder reports ``audio/webm;codecs=opus``. OpenAI-compatible STT+ * endpoints treat the codec parameter as an unknown format and return 400.+ */+export function stripAudioMimeParameters(+ mimeType: string | undefined | null,+): string {+ const mediaType = (mimeType || "").split(";", 1)[0].trim();+ return mediaType || "audio/webm";+}diff --git a/web/tests/voice-mime.test.ts b/web/tests/voice-mime.test.tsnew file mode 100644index 000000000..a7c183345--- /dev/null+++ b/web/tests/voice-mime.test.ts@@ -0,0 +1,21 @@+import test from "node:test";+import assert from "node:assert/strict";++import { stripAudioMimeParameters } from "../lib/voice-mime";++test("stripAudioMimeParameters drops MediaRecorder codec parameters", () => {+ assert.equal(+ stripAudioMimeParameters("audio/webm;codecs=opus"),+ "audio/webm",+ );+ assert.equal(+ stripAudioMimeParameters("audio/ogg; codecs=opus"),+ "audio/ogg",+ );+});++test("stripAudioMimeParameters keeps a clean type and falls back", () => {+ assert.equal(stripAudioMimeParameters("audio/wav"), "audio/wav");+ assert.equal(stripAudioMimeParameters(""), "audio/webm");+ assert.equal(stripAudioMimeParameters(undefined), "audio/webm");+});