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

+3
View File
@@ -0,0 +1,3 @@
DEEPSEEK_API_KEY=
DEEPSEEK_BASE_URL=https://api.deepseek.com
DEEPSEEK_MODEL=deepseek-chat
+1
View File
@@ -5,3 +5,4 @@ __pycache__/
*.pyc
*.lnk
ui-redesign-smoke.png
.env
+11
View File
@@ -47,6 +47,17 @@
<span>中文字幕 .srt/.vtt</span>
<input id="adminSubtitleZh" type="file" accept=".srt,.vtt,text/vtt,text/plain">
</label>
<section class="admin-ai-panel">
<div>
<h3>AI 字幕处理</h3>
<p id="aiSubtitleStatus">正在读取 AI 配置...</p>
</div>
<div class="admin-ai-actions">
<button id="testAiBtn" class="secondary-action" type="button">检查 AI 配置</button>
<button id="processAiSubtitlesBtn" type="button" disabled>AI 修复并翻译字幕</button>
</div>
<p id="aiSubtitleReport" class="admin-ai-report" hidden></p>
</section>
<div id="adminSubtitleEditor" class="admin-subtitle-editor" hidden></div>
<button id="adminSubmitBtn" type="submit">添加到视频库</button>
</form>
+68
View File
@@ -18,6 +18,10 @@ const els = {
subtitleEn: IS_BROWSER ? document.querySelector("#adminSubtitleEn") : null,
subtitleZh: IS_BROWSER ? document.querySelector("#adminSubtitleZh") : null,
subtitleEditor: IS_BROWSER ? document.querySelector("#adminSubtitleEditor") : null,
aiStatus: IS_BROWSER ? document.querySelector("#aiSubtitleStatus") : null,
aiReport: IS_BROWSER ? document.querySelector("#aiSubtitleReport") : null,
testAiBtn: IS_BROWSER ? document.querySelector("#testAiBtn") : null,
processAiSubtitlesBtn: IS_BROWSER ? document.querySelector("#processAiSubtitlesBtn") : null,
refreshBtn: IS_BROWSER ? document.querySelector("#refreshVideosBtn") : null,
message: IS_BROWSER ? document.querySelector("#adminMessage") : null,
videoList: IS_BROWSER ? document.querySelector("#adminVideoList") : null,
@@ -82,7 +86,10 @@ function initializeAdmin() {
els.form.addEventListener("submit", addVideo);
els.refreshBtn.addEventListener("click", loadVideos);
els.cancelEditBtn.addEventListener("click", resetFormMode);
els.testAiBtn?.addEventListener("click", testAiConnection);
els.processAiSubtitlesBtn?.addEventListener("click", processAiSubtitles);
bindFileInputs();
loadAiStatus();
loadVideos();
}
@@ -142,6 +149,64 @@ function clearMessage() {
els.message.classList.remove("error");
}
async function loadAiStatus() {
if (!els.aiStatus) return;
try {
const status = await apiRequest("/api/ai/status");
els.aiStatus.textContent = status.message || "AI 状态未知。";
if (els.processAiSubtitlesBtn) {
els.processAiSubtitlesBtn.disabled = !status.configured || !editingVideo;
}
} catch (error) {
els.aiStatus.textContent = error.message || "AI 状态读取失败。";
if (els.processAiSubtitlesBtn) els.processAiSubtitlesBtn.disabled = true;
}
}
async function testAiConnection() {
try {
const result = await apiRequest("/api/ai/test", { method: "POST" });
showMessage(result.message || "AI 配置正常。");
await loadAiStatus();
} catch (error) {
showMessage(error.message || "AI 配置检查失败。", true);
}
}
async function processAiSubtitles() {
if (!editingVideo) {
showMessage("请先选择一个素材。", true);
return;
}
const button = els.processAiSubtitlesBtn;
if (!button) return;
button.disabled = true;
button.textContent = "AI 处理中...";
try {
const result = await apiRequest(`/api/videos/${editingVideo.id}/ai/subtitles`, { method: "POST" });
const report = result.report || {};
if (els.aiReport) {
els.aiReport.hidden = false;
els.aiReport.textContent = [
`处理完成:删除重复 ${report.duplicate_count || 0} 条`,
`删除空白 ${report.empty_count || 0} 条`,
`生成中文 ${report.translation_count || 0} 条`,
].join(",") + "。";
}
await loadVideos();
const updated = videos.find((video) => String(video.id) === String(editingVideo.id));
if (updated) startEditingVideo(updated);
showMessage("AI 字幕处理完成。");
} catch (error) {
showMessage(error.message || "AI 字幕处理失败。", true);
} finally {
button.textContent = "AI 修复并翻译字幕";
await loadAiStatus();
}
}
async function loadVideos() {
clearMessage();
els.videoList.innerHTML = `<div class="empty-state">正在加载素材...</div>`;
@@ -232,6 +297,7 @@ function startEditingVideo(video) {
resetFileInputs();
renderSubtitleEditor();
renderVideos();
loadAiStatus();
}
function resetFormMode() {
@@ -243,8 +309,10 @@ function resetFormMode() {
els.form.dataset.mode = "add";
els.form.reset();
resetFileInputs();
if (els.aiReport) els.aiReport.hidden = true;
renderSubtitleEditor();
renderVideos();
loadAiStatus();
}
async function addVideo(event) {
+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"
+35
View File
@@ -719,6 +719,41 @@ video {
gap: 12px;
}
.admin-ai-panel {
display: grid;
gap: 10px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 8px;
background: var(--panel-soft);
}
.admin-ai-panel h3,
.admin-ai-panel p {
margin: 0;
}
.admin-ai-panel h3 {
font-size: 14px;
}
.admin-ai-panel p {
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.admin-ai-actions {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
.admin-ai-report {
color: var(--muted);
font-size: 13px;
}
.admin-subtitle-section {
display: grid;
gap: 8px;
+70
View File
@@ -0,0 +1,70 @@
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from backend import ai_config
from backend.ai_config import get_ai_status, load_deepseek_config
def test_ai_status_reports_missing_key(monkeypatch):
monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False)
status = get_ai_status()
assert status["configured"] is False
assert "DEEPSEEK_API_KEY" in status["message"]
def test_load_deepseek_config_uses_defaults(monkeypatch):
monkeypatch.setenv("DEEPSEEK_API_KEY", "test-key")
monkeypatch.delenv("DEEPSEEK_BASE_URL", raising=False)
monkeypatch.delenv("DEEPSEEK_MODEL", raising=False)
config = load_deepseek_config()
assert config.api_key == "test-key"
assert config.base_url == "https://api.deepseek.com"
assert config.model == "deepseek-chat"
class EnvPatch:
def __init__(self):
self.originals = {}
def setenv(self, key, value):
import os
self.originals.setdefault(key, os.environ.get(key))
os.environ[key] = value
def delenv(self, key, raising=True):
import os
self.originals.setdefault(key, os.environ.get(key))
if key in os.environ:
del os.environ[key]
elif raising:
raise KeyError(key)
def restore(self):
import os
for key, value in self.originals.items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
if __name__ == "__main__":
patch = EnvPatch()
original_read_env_file = ai_config.read_env_file
ai_config.read_env_file = lambda path=ai_config.ENV_PATH: {}
try:
test_ai_status_reports_missing_key(patch)
patch.restore()
test_load_deepseek_config_uses_defaults(patch)
finally:
patch.restore()
ai_config.read_env_file = original_read_env_file
+65
View File
@@ -0,0 +1,65 @@
import sys
from pathlib import Path
from fastapi import HTTPException
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from backend import ai_config, main
class EnvPatch:
def __init__(self):
self.originals = {}
def delenv(self, key, raising=True):
import os
self.originals.setdefault(key, os.environ.get(key))
if key in os.environ:
del os.environ[key]
elif raising:
raise KeyError(key)
def restore(self):
import os
for key, value in self.originals.items():
if value is None:
os.environ.pop(key, None)
else:
os.environ[key] = value
def test_ai_status_route_reports_missing_key(monkeypatch):
monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False)
status = main.api_ai_status()
assert status["configured"] is False
assert "DEEPSEEK_API_KEY" in status["message"]
def test_ai_test_route_rejects_missing_key(monkeypatch):
monkeypatch.delenv("DEEPSEEK_API_KEY", raising=False)
try:
main.api_ai_test()
except HTTPException as error:
assert error.status_code == 400
assert "DEEPSEEK_API_KEY" in error.detail
else:
raise AssertionError("api_ai_test should reject missing DeepSeek API key")
if __name__ == "__main__":
patch = EnvPatch()
original_read_env_file = ai_config.read_env_file
ai_config.read_env_file = lambda path=ai_config.ENV_PATH: {}
try:
test_ai_status_route_reports_missing_key(patch)
patch.restore()
test_ai_test_route_rejects_missing_key(patch)
finally:
patch.restore()
ai_config.read_env_file = original_read_env_file
+37
View File
@@ -0,0 +1,37 @@
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from backend.subtitle_ai import process_subtitles_with_ai
class FakeClient:
def chat_json(self, system_prompt, user_payload):
return {
"translations": [
{"index": 1, "zh": "我第一次做投资人是在 24 岁。"}
]
}
def test_process_subtitles_with_ai_returns_clean_en_and_zh_vtt():
raw = """WEBVTT
00:00:00.872 --> 00:00:04.959
My first job as an investor was when I was 24 years old,
00:00:00.872 --> 00:00:04.959
My first job as an investor was when I was 24 years old,
"""
result = process_subtitles_with_ai(raw, FakeClient())
assert "My first job as an investor" in result["subtitle_en_content"]
assert "我第一次做投资人是在 24 岁。" in result["subtitle_zh_content"]
assert result["report"]["duplicate_count"] == 1
assert result["report"]["translation_count"] == 1
if __name__ == "__main__":
test_process_subtitles_with_ai_returns_clean_en_and_zh_vtt()
+48
View File
@@ -0,0 +1,48 @@
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from backend.subtitle_tools import build_vtt, clean_english_subtitle
def test_clean_english_subtitle_removes_empty_and_duplicate_cues():
raw = """WEBVTT
00:00:00.000 --> 00:00:00.001
&nbsp;
00:00:00.872 --> 00:00:04.959
My first job as an investor
was when I was 24 years old,
00:00:00.872 --> 00:00:04.959
My first job as an investor
was when I was 24 years old,
"""
result = clean_english_subtitle(raw)
assert result.original_count == 3
assert result.cleaned_count == 1
assert result.duplicate_count == 1
assert result.empty_count == 1
assert result.cues[0].start == "00:00:00.872"
assert result.cues[0].end == "00:00:04.959"
assert result.cues[0].text == "My first job as an investor\nwas when I was 24 years old,"
def test_build_vtt_outputs_numbered_blocks():
result = build_vtt([
{
"start": "00:00:00.872",
"end": "00:00:04.959",
"text": "My first job as an investor",
}
])
assert result == "WEBVTT\n\n1\n00:00:00.872 --> 00:00:04.959\nMy first job as an investor\n"
if __name__ == "__main__":
test_clean_english_subtitle_removes_empty_and_duplicate_cues()
test_build_vtt_outputs_numbered_blocks()