feat: add DeepSeek subtitle AI workflow

This commit is contained in:
TTlaji committed 2026-06-03 00:57:59 +08:00
1 parent bcebeaef82
commit 72072c884c
15 files changed
+710

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
from __future__ import annotations
from dataclasses import dataclass
import os
from pathlib import Path
PROJECT_DIR = Path(__file__).resolve().parent.parent
ENV_PATH = PROJECT_DIR / ".env"
@dataclass(frozen=True)
class DeepSeekConfig:
api_key: str
base_url: str
model: str
def read_env_file(path: Path = ENV_PATH) -> dict[str, str]:
if not path.exists():
return {}
values: dict[str, str] = {}
for raw_line in path.read_text(encoding="utf-8").splitlines():
line = raw_line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, value = line.split("=", 1)
values[key.strip()] = value.strip().strip('"').strip("'")
return values
def get_config_value(key: str, default: str = "") -> str:
env_values = read_env_file()
return os.getenv(key, env_values.get(key, default)).strip()
def load_deepseek_config() -> DeepSeekConfig:
return DeepSeekConfig(
api_key=get_config_value("DEEPSEEK_API_KEY"),
base_url=get_config_value("DEEPSEEK_BASE_URL", "https://api.deepseek.com").rstrip("/"),
model=get_config_value("DEEPSEEK_MODEL", "deepseek-chat"),
)
def get_ai_status() -> dict[str, object]:
config = load_deepseek_config()
if not config.api_key:
return {
"configured": False,
"provider": "deepseek",
"model": config.model,
"message": "未配置 DEEPSEEK_API_KEY,请在 .env 或环境变量中填写。",
}
return {
"configured": True,
"provider": "deepseek",
"model": config.model,
"message": "DeepSeek API 已配置。",
}
+34
View File
@@ -382,6 +382,40 @@ def update_video(
}
def upsert_video_subtitle(
video_id: int,
*,
language_code: str,
language_name: str,
format: str,
file_path: str,
content: str,
) -> None:
with get_connection() as connection:
connection.execute(
"""
INSERT INTO subtitles (
video_id, language_code, language_name, format, file_path, content
)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(video_id, language_code) DO UPDATE SET
language_name = excluded.language_name,
format = excluded.format,
file_path = excluded.file_path,
content = excluded.content,
updated_at = CURRENT_TIMESTAMP
""",
(
video_id,
language_code,
repair_mojibake_text(language_name),
format,
file_path,
repair_mojibake_text(content),
),
)
def table_names() -> list[str]:
with get_connection() as connection:
rows = connection.execute(
+54
View File
@@ -0,0 +1,54 @@
from __future__ import annotations
import json
import urllib.error
import urllib.request
from .ai_config import DeepSeekConfig
class DeepSeekError(RuntimeError):
pass
class DeepSeekClient:
def __init__(self, config: DeepSeekConfig, timeout_seconds: int = 60):
self.config = config
self.timeout_seconds = timeout_seconds
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。")
body = json.dumps({
"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
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
+71
View File
@@ -6,6 +6,7 @@ from fastapi import FastAPI, File, Form, HTTPException, UploadFile
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from .ai_config import get_ai_status, load_deepseek_config
from .db import (
DATABASE_PATH,
create_video,
@@ -16,7 +17,10 @@ from .db import (
table_names,
get_video,
update_video,
upsert_video_subtitle,
)
from .deepseek_client import DeepSeekClient, DeepSeekError
from .subtitle_ai import process_subtitles_with_ai
PROJECT_DIR = Path(__file__).resolve().parent.parent
@@ -348,6 +352,73 @@ def api_delete_video(video_id: int) -> dict[str, object]:
}
@app.get("/api/ai/status")
def api_ai_status() -> dict[str, object]:
return get_ai_status()
@app.post("/api/ai/test")
def api_ai_test() -> dict[str, object]:
status = get_ai_status()
if not status["configured"]:
raise HTTPException(status_code=400, detail=status["message"])
return {"ok": True, "message": "DeepSeek API 配置已读取,处理字幕时会正式调用。"}
@app.post("/api/videos/{video_id}/ai/subtitles")
def api_process_video_subtitles(video_id: int) -> dict[str, object]:
status = get_ai_status()
if not status["configured"]:
raise HTTPException(status_code=400, detail=status["message"])
video = get_video(video_id)
if video is None:
raise HTTPException(status_code=404, detail="视频不存在")
subtitles = video.get("subtitles", {})
if not isinstance(subtitles, dict):
raise HTTPException(status_code=400, detail="字幕数据异常。")
english_subtitle = subtitles.get("en", {})
if not isinstance(english_subtitle, dict) or not english_subtitle.get("content"):
raise HTTPException(status_code=400, detail="请先上传英文字幕。")
try:
result = process_subtitles_with_ai(
str(english_subtitle["content"]),
DeepSeekClient(load_deepseek_config()),
)
except (DeepSeekError, ValueError) as error:
raise HTTPException(status_code=400, detail=str(error)) from error
upsert_video_subtitle(
video_id,
language_code="en",
language_name="English",
format="vtt",
file_path=str(english_subtitle.get("filePath") or ""),
content=str(result["subtitle_en_content"]),
)
chinese_subtitle = subtitles.get("zh", {})
chinese_file_path = ""
if isinstance(chinese_subtitle, dict):
chinese_file_path = str(chinese_subtitle.get("filePath") or "")
upsert_video_subtitle(
video_id,
language_code="zh",
language_name="中文",
format="vtt",
file_path=chinese_file_path,
content=str(result["subtitle_zh_content"]),
)
return {
"video": get_video(video_id),
"report": result["report"],
}
@app.get("/")
def read_index() -> FileResponse:
return FileResponse(PROJECT_DIR / "index.html")
+49
View File
@@ -0,0 +1,49 @@
from __future__ import annotations
from .subtitle_tools import build_vtt, clean_english_subtitle
TRANSLATION_SYSTEM_PROMPT = """
你是英语学习产品的字幕翻译助手。输入是按顺序排列的英文字幕。
请只返回 JSON,格式为 {"translations":[{"index":1,"zh":"中文翻译"}]}。
要求:中文自然,适合英语学习;不要增删字幕条数;不要解释。
""".strip()
def process_subtitles_with_ai(english_content: str, client) -> dict[str, object]:
cleaned = clean_english_subtitle(english_content)
if not cleaned.cues:
raise ValueError("英文字幕为空,无法处理。")
payload = {
"cues": [
{"index": index, "text": cue.text}
for index, cue in enumerate(cleaned.cues, 1)
]
}
response = client.chat_json(TRANSLATION_SYSTEM_PROMPT, payload)
translations = response.get("translations")
if not isinstance(translations, list):
raise ValueError("AI 返回结果缺少 translations。")
if len(translations) != len(cleaned.cues):
raise ValueError("AI 返回的翻译条数和英文字幕条数不一致。")
zh_cues = []
for cue, translation in zip(cleaned.cues, translations):
zh_text = str(translation.get("zh", "")).strip()
if not zh_text:
raise ValueError("AI 返回了空翻译。")
zh_cues.append({"start": cue.start, "end": cue.end, "text": zh_text})
return {
"subtitle_en_content": build_vtt(cleaned.cues),
"subtitle_zh_content": build_vtt(zh_cues),
"report": {
"original_count": cleaned.original_count,
"cleaned_count": cleaned.cleaned_count,
"duplicate_count": cleaned.duplicate_count,
"empty_count": cleaned.empty_count,
"translation_count": len(zh_cues),
"timestamp_calibrated": False,
},
}
+104
View File
@@ -0,0 +1,104 @@
from __future__ import annotations
from dataclasses import dataclass
import re
TIME_RE = re.compile(
r"(?P<start>\d{1,2}:\d{2}:\d{2}[\.,]\d{3})\s*-->\s*"
r"(?P<end>\d{1,2}:\d{2}:\d{2}[\.,]\d{3})"
)
@dataclass
class SubtitleCue:
start: str
end: str
text: str
@dataclass
class CleanSubtitleResult:
cues: list[SubtitleCue]
original_count: int
cleaned_count: int
duplicate_count: int
empty_count: int
def normalize_time(value: str) -> str:
return value.replace(",", ".")
def has_visible_text(rows: list[str]) -> bool:
text = "".join(rows).replace("&nbsp;", "").replace("\u00a0", "").strip()
return bool(text)
def parse_subtitle(content: str) -> list[SubtitleCue]:
cues: list[SubtitleCue] = []
current_time: tuple[str, str] | None = None
text_rows: list[str] = []
def flush() -> None:
nonlocal current_time, text_rows
if current_time and text_rows:
cues.append(SubtitleCue(current_time[0], current_time[1], "\n".join(text_rows).strip()))
current_time = None
text_rows = []
for raw_line in str(content or "").replace("\r", "").replace("\ufeff", "").split("\n"):
row = raw_line.strip()
if not row:
flush()
continue
if row.upper().startswith("WEBVTT") or row.isdigit():
continue
match = TIME_RE.search(row)
if match:
flush()
current_time = (normalize_time(match.group("start")), normalize_time(match.group("end")))
continue
if current_time:
text_rows.append(row)
flush()
return cues
def clean_english_subtitle(content: str) -> CleanSubtitleResult:
parsed = parse_subtitle(content)
cleaned: list[SubtitleCue] = []
seen: set[tuple[str, str, str]] = set()
duplicate_count = 0
empty_count = 0
for cue in parsed:
rows = cue.text.splitlines()
if not has_visible_text(rows):
empty_count += 1
continue
key = (cue.start, cue.end, cue.text.strip())
if key in seen:
duplicate_count += 1
continue
seen.add(key)
cleaned.append(cue)
return CleanSubtitleResult(
cues=cleaned,
original_count=len(parsed),
cleaned_count=len(cleaned),
duplicate_count=duplicate_count,
empty_count=empty_count,
)
def build_vtt(cues: list[SubtitleCue] | list[dict[str, str]]) -> str:
blocks: list[str] = []
for index, cue in enumerate(cues, 1):
start = cue.start if isinstance(cue, SubtitleCue) else cue["start"]
end = cue.end if isinstance(cue, SubtitleCue) else cue["end"]
text = cue.text if isinstance(cue, SubtitleCue) else cue["text"]
blocks.append(f"{index}\n{start} --> {end}\n{text.strip()}")
return "WEBVTT\n\n" + "\n\n".join(blocks).strip() + "\n"