Files
speaking-practice/backend/openai_asr_client.py
T

67 lines
2.4 KiB
Python

from __future__ import annotations
import json
from pathlib import Path
import uuid
import urllib.error
import urllib.request
from .ai_config import AsrConfig
from .deepseek_client import DeepSeekError
class OpenAIAsrClient:
def __init__(self, config: AsrConfig):
self.config = config
def transcribe(self, audio_path: Path) -> dict[str, object]:
if not self.config.configured:
raise DeepSeekError("未配置 OPENAI_API_KEY,已跳过 ASR。")
if not audio_path.exists():
raise DeepSeekError("音频文件不存在,无法 ASR。")
boundary = f"----speaking-lab-{uuid.uuid4().hex}"
body = self._build_multipart_body(boundary, audio_path)
request = urllib.request.Request(
f"{self.config.base_url}/v1/audio/transcriptions",
data=body,
headers={
"Authorization": f"Bearer {self.config.api_key}",
"Content-Type": f"multipart/form-data; boundary={boundary}",
},
method="POST",
)
try:
with urllib.request.urlopen(request, timeout=self.config.timeout_seconds) as response:
return json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as error:
detail = error.read().decode("utf-8", errors="replace")
raise DeepSeekError(f"OpenAI ASR 请求失败:{error.code} {detail}") from error
except Exception as error:
raise DeepSeekError(f"OpenAI ASR 请求失败:{error}") from error
def _build_multipart_body(self, boundary: str, audio_path: Path) -> bytes:
fields = [
("model", self.config.model),
("response_format", "verbose_json"),
("timestamp_granularities[]", "segment"),
]
chunks: list[bytes] = []
for key, value in fields:
chunks.extend([
f"--{boundary}\r\n".encode("utf-8"),
f'Content-Disposition: form-data; name="{key}"\r\n\r\n'.encode("utf-8"),
f"{value}\r\n".encode("utf-8"),
])
chunks.extend([
f"--{boundary}\r\n".encode("utf-8"),
f'Content-Disposition: form-data; name="file"; filename="{audio_path.name}"\r\n'.encode("utf-8"),
b"Content-Type: audio/wav\r\n\r\n",
audio_path.read_bytes(),
b"\r\n",
f"--{boundary}--\r\n".encode("utf-8"),
])
return b"".join(chunks)