feat: add local whisper subtitle generation
This commit is contained in:
1 parent
5228765473
commit
6a6fd347bd
17 files changed
+1041
-96
No files matched your search
@@ -0,0 +1,66 @@
|
||||
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)
|
||||
Reference in new issue
Block a user