mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-03 11:32:59 +08:00
fix(voice): strip MediaRecorder codec params from STT uploads (#948)
* fix(voice): strip MediaRecorder codec params from STT uploads Chrome sends audio/webm;codecs=opus; OpenAI-compatible transcription APIs reject that as an unknown format. Fixes #945 * refactor(voice): normalize the STT MIME once, at the wire boundary The codec-parameter strip was applied at four layers: the recorder hook, the route, the `transcribe_audio` facade, and `_post_multipart`. Only the last of those decides what actually goes on the wire, and `openai_compat` is the sole registered STT adapter, so the two middle copies were pure duplication — and they made the route's contract ambiguous about who owns the value. Keep the client-side strip (it sets the Blob type, which is what the browser puts in the multipart part) and the adapter strip; drop the route and facade copies along with the now-unused facade re-export. The adapter-level test already pins the wire contract; the route test now asserts what the route actually promises — verbatim forwarding. --------- Co-authored-by: ZQR1101 <278034003+ZQR1101@users.noreply.github.com> Co-authored-by: Frank <bingxizhao@novix.science>
This commit is contained in:
@@ -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.language
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
|
||||
@@ -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_type
|
||||
return "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:
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
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.asyncio
|
||||
async 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.asyncio
|
||||
async 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"
|
||||
|
||||
@@ -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 = [];
|
||||
|
||||
@@ -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";
|
||||
}
|
||||
@@ -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");
|
||||
});
|
||||
Reference in New Issue
Block a user