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
+133
-45
@@ -2,6 +2,7 @@ from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import json
|
||||
import re
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
@@ -20,47 +21,34 @@ class DeepSeekClient:
|
||||
|
||||
def chat_json(self, system_prompt: str, user_payload: dict[str, object]) -> dict[str, object]:
|
||||
if not self.config.api_key:
|
||||
raise DeepSeekError("未配置 DEEPSEEK_API_KEY。")
|
||||
raise DeepSeekError("未配置 AI_API_KEY。")
|
||||
if self.config.protocol == "anthropic":
|
||||
return self._anthropic_chat_json(system_prompt, user_payload)
|
||||
return self._openai_chat_json(system_prompt, user_payload)
|
||||
|
||||
body = json.dumps({
|
||||
def audio_json(self, system_prompt: str, audio_path: Path, user_text: str) -> dict[str, object]:
|
||||
if not self.config.api_key:
|
||||
raise DeepSeekError("未配置 AI_API_KEY。")
|
||||
if self.config.protocol == "anthropic":
|
||||
return self._anthropic_audio_json(system_prompt, audio_path, user_text)
|
||||
return self._openai_audio_json(system_prompt, audio_path, user_text)
|
||||
|
||||
def _openai_chat_json(self, system_prompt: str, user_payload: dict[str, object]) -> dict[str, object]:
|
||||
body = {
|
||||
"model": self.config.model,
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": json.dumps(user_payload, ensure_ascii=False)},
|
||||
],
|
||||
"response_format": {"type": "json_object"},
|
||||
}).encode("utf-8")
|
||||
request = urllib.request.Request(
|
||||
f"{self.config.base_url}/chat/completions",
|
||||
data=body,
|
||||
headers={
|
||||
"Authorization": f"Bearer {self.config.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
method="POST",
|
||||
)
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=self.timeout_seconds) as response:
|
||||
payload = json.loads(response.read().decode("utf-8"))
|
||||
except urllib.error.HTTPError as error:
|
||||
detail = error.read().decode("utf-8", errors="replace")
|
||||
raise DeepSeekError(f"DeepSeek 请求失败:{error.code} {detail}") from error
|
||||
except Exception as error:
|
||||
raise DeepSeekError(f"DeepSeek 请求失败:{error}") from error
|
||||
|
||||
}
|
||||
payload = self._post_json("/chat/completions", body, self._openai_headers(), "AI 请求失败")
|
||||
content = payload.get("choices", [{}])[0].get("message", {}).get("content", "")
|
||||
try:
|
||||
return json.loads(content)
|
||||
except json.JSONDecodeError as error:
|
||||
raise DeepSeekError("DeepSeek 返回内容不是有效 JSON。") from error
|
||||
|
||||
def audio_json(self, system_prompt: str, audio_path: Path, user_text: str) -> dict[str, object]:
|
||||
if not self.config.api_key:
|
||||
raise DeepSeekError("未配置 AI_API_KEY。")
|
||||
return self._parse_json_text(content, "AI 返回内容不是有效 JSON。")
|
||||
|
||||
def _openai_audio_json(self, system_prompt: str, audio_path: Path, user_text: str) -> dict[str, object]:
|
||||
audio_data = base64.b64encode(audio_path.read_bytes()).decode("ascii")
|
||||
body = json.dumps({
|
||||
body = {
|
||||
"model": self.config.audio_model,
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
@@ -79,28 +67,128 @@ class DeepSeekClient:
|
||||
},
|
||||
],
|
||||
"response_format": {"type": "json_object"},
|
||||
}).encode("utf-8")
|
||||
}
|
||||
payload = self._post_json("/chat/completions", body, self._openai_headers(), "音频识别请求失败")
|
||||
content = payload.get("choices", [{}])[0].get("message", {}).get("content", "")
|
||||
return self._parse_json_text(content, "音频识别返回内容不是有效 JSON。")
|
||||
|
||||
def _anthropic_chat_json(self, system_prompt: str, user_payload: dict[str, object]) -> dict[str, object]:
|
||||
body = {
|
||||
"model": self.config.model,
|
||||
"max_tokens": 4096,
|
||||
"system": system_prompt,
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": (
|
||||
"Return only one valid JSON object. Do not use markdown fences or extra text.\n"
|
||||
f"{json.dumps(user_payload, ensure_ascii=False)}"
|
||||
),
|
||||
}
|
||||
],
|
||||
}
|
||||
],
|
||||
}
|
||||
payload = self._post_json("/v1/messages", body, self._anthropic_headers(), "Anthropic 请求失败")
|
||||
return self._parse_json_text(self._extract_anthropic_text(payload), "Anthropic 返回内容不是有效 JSON。")
|
||||
|
||||
def _anthropic_audio_json(self, system_prompt: str, audio_path: Path, user_text: str) -> dict[str, object]:
|
||||
audio_data = base64.b64encode(audio_path.read_bytes()).decode("ascii")
|
||||
body = {
|
||||
"model": self.config.audio_model,
|
||||
"max_tokens": 1024,
|
||||
"system": system_prompt,
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": user_text},
|
||||
{
|
||||
"type": "input_audio",
|
||||
"source": {
|
||||
"type": "base64",
|
||||
"media_type": "audio/wav",
|
||||
"data": audio_data,
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
],
|
||||
}
|
||||
payload = self._post_json("/v1/messages", body, self._anthropic_headers(), "Anthropic 音频识别请求失败")
|
||||
return self._parse_json_text(self._extract_anthropic_text(payload), "Anthropic 音频识别返回内容不是有效 JSON。")
|
||||
|
||||
def _post_json(
|
||||
self,
|
||||
path: str,
|
||||
body: dict[str, object],
|
||||
headers: dict[str, str],
|
||||
error_prefix: str,
|
||||
) -> dict[str, object]:
|
||||
request = urllib.request.Request(
|
||||
f"{self.config.base_url}/chat/completions",
|
||||
data=body,
|
||||
headers={
|
||||
"Authorization": f"Bearer {self.config.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
f"{self.config.base_url}{path}",
|
||||
data=json.dumps(body).encode("utf-8"),
|
||||
headers=headers,
|
||||
method="POST",
|
||||
)
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=self.timeout_seconds) as response:
|
||||
payload = json.loads(response.read().decode("utf-8"))
|
||||
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"Qwen 音频识别请求失败:{error.code} {detail}") from error
|
||||
raise DeepSeekError(f"{error_prefix}:{error.code} {detail}") from error
|
||||
except Exception as error:
|
||||
raise DeepSeekError(f"Qwen 音频识别请求失败:{error}") from error
|
||||
raise DeepSeekError(f"{error_prefix}:{error}") from error
|
||||
|
||||
content = payload.get("choices", [{}])[0].get("message", {}).get("content", "")
|
||||
def _openai_headers(self) -> dict[str, str]:
|
||||
return {
|
||||
"Authorization": f"Bearer {self.config.api_key}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
def _anthropic_headers(self) -> dict[str, str]:
|
||||
return {
|
||||
"x-api-key": self.config.api_key,
|
||||
"anthropic-version": "2023-06-01",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
def _extract_anthropic_text(self, payload: dict[str, object]) -> str:
|
||||
blocks = payload.get("content", [])
|
||||
if not isinstance(blocks, list):
|
||||
return ""
|
||||
texts = [
|
||||
str(block.get("text", ""))
|
||||
for block in blocks
|
||||
if isinstance(block, dict) and block.get("type") == "text"
|
||||
]
|
||||
return "\n".join(texts).strip()
|
||||
|
||||
def _parse_json_text(self, content: str, error_message: str) -> dict[str, object]:
|
||||
json_text = self._extract_json_text(content)
|
||||
try:
|
||||
return json.loads(content)
|
||||
return json.loads(json_text)
|
||||
except json.JSONDecodeError as error:
|
||||
raise DeepSeekError("Qwen 音频识别返回内容不是有效 JSON。") from error
|
||||
raise DeepSeekError(error_message) from error
|
||||
|
||||
def _extract_json_text(self, content: str) -> str:
|
||||
text = str(content or "").strip()
|
||||
if not text:
|
||||
return text
|
||||
|
||||
fenced = re.search(r"```(?:json)?\s*(\{.*?\})\s*```", text, re.IGNORECASE | re.DOTALL)
|
||||
if fenced:
|
||||
return fenced.group(1).strip()
|
||||
|
||||
start = text.find("{")
|
||||
if start < 0:
|
||||
return text
|
||||
decoder = json.JSONDecoder()
|
||||
try:
|
||||
_, end = decoder.raw_decode(text[start:])
|
||||
except json.JSONDecodeError:
|
||||
return text
|
||||
return text[start:start + end].strip()
|
||||
Reference in new issue
Block a user