feat: align subtitles from first 10 seconds audio

This commit is contained in:
TTlaji committed 2026-06-03 15:10:49 +08:00
1 parent 93e06ca40a
commit 5228765473
11 files changed
+248 -22

No files matched your search

+4 -3
View File
@@ -1,3 +1,4 @@
DEEPSEEK_API_KEY=
DEEPSEEK_BASE_URL=https://coding.simgreek.com/v1
DEEPSEEK_MODEL=deepseek-chat
AI_API_KEY=
AI_BASE_URL=https://coding.simgreek.com/v1
AI_TEXT_MODEL=qwen-plus
AI_AUDIO_MODEL=qwen-omni-turbo
+1
View File
@@ -223,6 +223,7 @@ async function processAiSubtitles() {
els.aiReport.textContent = [
`处理完成:删除重复 ${report.duplicate_count || 0} 条`,
`删除空白 ${report.empty_count || 0} 条`,
report.timestamp_calibrated ? `首句校准 ${Number(report.timestamp_offset_seconds || 0).toFixed(2)} 秒` : (report.alignment_note || "首句未自动校准"),
`生成中文 ${report.translation_count || 0} 条`,
].join(",") + "。";
}
+9 -4
View File
@@ -14,6 +14,7 @@ class DeepSeekConfig:
api_key: str
base_url: str
model: str
audio_model: str
def read_env_file(path: Path = ENV_PATH) -> dict[str, str]:
@@ -36,10 +37,14 @@ def get_config_value(key: str, default: str = "") -> str:
def load_deepseek_config() -> DeepSeekConfig:
api_key = get_config_value("AI_API_KEY") or get_config_value("DEEPSEEK_API_KEY")
base_url = get_config_value("AI_BASE_URL") or get_config_value("DEEPSEEK_BASE_URL", "https://api.deepseek.com")
model = get_config_value("AI_TEXT_MODEL") or get_config_value("DEEPSEEK_MODEL", "deepseek-chat")
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"),
api_key=api_key,
base_url=base_url.rstrip("/"),
model=model,
audio_model=get_config_value("AI_AUDIO_MODEL") or model,
)
@@ -50,7 +55,7 @@ def get_ai_status() -> dict[str, object]:
"configured": False,
"provider": "deepseek",
"model": config.model,
"message": "未配置 DEEPSEEK_API_KEY,请在 .env 或环境变量中填写。",
"message": "未配置 AI_API_KEY,请在 .env 中填写。旧配置 DEEPSEEK_API_KEY 也兼容。",
}
return {
"configured": True,
+52
View File
@@ -1,8 +1,10 @@
from __future__ import annotations
import base64
import json
import urllib.error
import urllib.request
from pathlib import Path
from .ai_config import DeepSeekConfig
@@ -52,3 +54,53 @@ class DeepSeekClient:
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。")
audio_data = base64.b64encode(audio_path.read_bytes()).decode("ascii")
body = json.dumps({
"model": self.config.audio_model,
"messages": [
{"role": "system", "content": system_prompt},
{
"role": "user",
"content": [
{"type": "text", "text": user_text},
{
"type": "input_audio",
"input_audio": {
"data": f"data:audio/wav;base64,{audio_data}",
"format": "wav",
},
},
],
},
],
"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"Qwen 音频识别请求失败:{error.code} {detail}") from error
except Exception as error:
raise DeepSeekError(f"Qwen 音频识别请求失败:{error}") from error
content = payload.get("choices", [{}])[0].get("message", {}).get("content", "")
try:
return json.loads(content)
except json.JSONDecodeError as error:
raise DeepSeekError("Qwen 音频识别返回内容不是有效 JSON。") from error
+17 -1
View File
@@ -20,7 +20,9 @@ from .db import (
upsert_video_subtitle,
)
from .deepseek_client import DeepSeekClient, DeepSeekError
from .subtitle_alignment import align_first_sentence
from .subtitle_ai import process_subtitles_with_ai
from .subtitle_tools import clean_english_subtitle
PROJECT_DIR = Path(__file__).resolve().parent.parent
@@ -384,10 +386,24 @@ def api_process_video_subtitles(video_id: int) -> dict[str, object]:
raise HTTPException(status_code=400, detail="请先上传英文字幕。")
try:
client = DeepSeekClient(load_deepseek_config())
timestamp_offset_seconds = 0.0
alignment_note = "未执行首句校准。"
cleaned_for_alignment = clean_english_subtitle(str(english_subtitle["content"]))
video_path = upload_url_to_path(str(video.get("videoUrl") or ""))
if video_path and cleaned_for_alignment.cues:
alignment = align_first_sentence(video_path, cleaned_for_alignment.cues[0], client)
timestamp_offset_seconds = alignment.offset_seconds if alignment.applied else 0.0
alignment_note = alignment.note
elif not video_path:
alignment_note = "当前视频不是本地上传文件,已跳过自动首句校准。"
result = process_subtitles_with_ai(
str(english_subtitle["content"]),
DeepSeekClient(load_deepseek_config()),
client,
timestamp_offset_seconds=timestamp_offset_seconds,
)
result["report"]["alignment_note"] = alignment_note
except (DeepSeekError, ValueError) as error:
raise HTTPException(status_code=400, detail=str(error)) from error
+10 -8
View File
@@ -1,6 +1,6 @@
from __future__ import annotations
from .subtitle_tools import build_vtt, clean_english_subtitle
from .subtitle_tools import build_vtt, clean_english_subtitle, shift_cues
TRANSLATION_SYSTEM_PROMPT = """
@@ -14,33 +14,34 @@ TRANSLATION_SYSTEM_PROMPT = """
""".strip()
def process_subtitles_with_ai(english_content: str, client) -> dict[str, object]:
def process_subtitles_with_ai(english_content: str, client, timestamp_offset_seconds: float = 0.0) -> dict[str, object]:
cleaned = clean_english_subtitle(english_content)
if not cleaned.cues:
raise ValueError("英文字幕为空,无法处理。")
english_cues = shift_cues(cleaned.cues, timestamp_offset_seconds) if timestamp_offset_seconds else cleaned.cues
payload = {
"cues": [
{"index": index, "text": cue.text}
for index, cue in enumerate(cleaned.cues, 1)
for index, cue in enumerate(english_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):
if len(translations) != len(english_cues):
raise ValueError("AI 返回的翻译条数和英文字幕条数不一致。")
zh_cues = []
for cue, translation in zip(cleaned.cues, translations):
for cue, translation in zip(english_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_en_content": build_vtt(english_cues),
"subtitle_zh_content": build_vtt(zh_cues),
"report": {
"original_count": cleaned.original_count,
@@ -48,7 +49,8 @@ def process_subtitles_with_ai(english_content: str, client) -> dict[str, object]
"duplicate_count": cleaned.duplicate_count,
"empty_count": cleaned.empty_count,
"translation_count": len(zh_cues),
"timestamp_calibrated": False,
"timestamp_note": "AI 仅翻译文本,中文字幕时间轴从英文字幕原样复制。",
"timestamp_calibrated": bool(timestamp_offset_seconds),
"timestamp_offset_seconds": round(timestamp_offset_seconds, 3),
"timestamp_note": "首句校准只计算整体偏移,AI 不逐句修改时间轴。",
},
}
+80
View File
@@ -0,0 +1,80 @@
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
import subprocess
import tempfile
from .subtitle_tools import SubtitleCue, parse_timestamp
FIRST_SENTENCE_ALIGNMENT_PROMPT = """
你是字幕首句时间校准助手。你只需要分析这段音频的前 10 秒。
请找出给定英文字幕第一句在音频中真正开始说话的时间,单位是秒。
只返回 JSON:{"first_sentence_start":1.23,"matched_text":"...","confidence":0.95}
不要返回解释,不要校准后续句子。
""".strip()
@dataclass
class AlignmentResult:
applied: bool
offset_seconds: float
first_sentence_start: float | None
confidence: float
note: str
def align_first_sentence(video_path: Path, first_cue: SubtitleCue, client) -> AlignmentResult:
if not video_path.exists():
return AlignmentResult(False, 0.0, None, 0.0, "视频文件不存在,已跳过自动首句校准。")
with tempfile.TemporaryDirectory() as temp_dir:
audio_path = Path(temp_dir) / "first10.wav"
try:
extract_first_audio(video_path, audio_path)
response = client.audio_json(
FIRST_SENTENCE_ALIGNMENT_PROMPT,
audio_path,
f"第一句英文字幕:{first_cue.text}\n请只判断这句开始说话的秒数。",
)
except Exception as error:
return AlignmentResult(False, 0.0, None, 0.0, f"首句自动校准失败,已跳过:{error}")
first_sentence_start = parse_alignment_second(response.get("first_sentence_start"))
confidence = parse_alignment_second(response.get("confidence"))
if first_sentence_start is None:
return AlignmentResult(False, 0.0, None, confidence or 0.0, "AI 没有返回有效的首句开始时间,已跳过自动校准。")
offset = first_sentence_start - parse_timestamp(first_cue.start)
if abs(offset) > 5:
return AlignmentResult(False, 0.0, first_sentence_start, confidence or 0.0, f"检测到偏移 {offset:.2f} 秒,超过 5 秒安全阈值,已跳过自动校准。")
return AlignmentResult(True, offset, first_sentence_start, confidence or 0.0, f"首句自动校准成功,整体平移 {offset:.2f} 秒。")
def extract_first_audio(video_path: Path, audio_path: Path) -> None:
command = [
"ffmpeg",
"-y",
"-i",
str(video_path),
"-ss",
"0",
"-t",
"10",
"-vn",
"-ac",
"1",
"-ar",
"16000",
str(audio_path),
]
subprocess.run(command, check=True, capture_output=True)
def parse_alignment_second(value) -> float | None:
try:
return float(value)
except (TypeError, ValueError):
return None
+37
View File
@@ -102,3 +102,40 @@ def build_vtt(cues: list[SubtitleCue] | list[dict[str, str]]) -> str:
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"
def parse_timestamp(value: str) -> float:
clean = str(value).replace(",", ".").split()[0]
parts = clean.split(":")
try:
numbers = [float(part) for part in parts]
except ValueError:
return 0.0
if len(numbers) == 3:
return numbers[0] * 3600 + numbers[1] * 60 + numbers[2]
if len(numbers) == 2:
return numbers[0] * 60 + numbers[1]
return numbers[0] if numbers else 0.0
def format_timestamp(seconds: float) -> str:
total_milliseconds = max(0, round((seconds or 0) * 1000))
hours = total_milliseconds // 3_600_000
minutes = (total_milliseconds % 3_600_000) // 60_000
whole_seconds = (total_milliseconds % 60_000) // 1000
milliseconds = total_milliseconds % 1000
return f"{hours:02d}:{minutes:02d}:{whole_seconds:02d}.{milliseconds:03d}"
def shift_cues(cues: list[SubtitleCue] | list[dict[str, str]], offset_seconds: float) -> list[SubtitleCue]:
shifted: list[SubtitleCue] = []
for cue in cues:
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"]
shifted.append(SubtitleCue(
format_timestamp(parse_timestamp(start) + offset_seconds),
format_timestamp(parse_timestamp(end) + offset_seconds),
text,
))
return shifted
+17 -1
View File
@@ -13,7 +13,7 @@ def test_ai_status_reports_missing_key(monkeypatch):
status = get_ai_status()
assert status["configured"] is False
assert "DEEPSEEK_API_KEY" in status["message"]
assert "AI_API_KEY" in status["message"]
def test_load_deepseek_config_uses_defaults(monkeypatch):
@@ -28,6 +28,20 @@ def test_load_deepseek_config_uses_defaults(monkeypatch):
assert config.model == "deepseek-chat"
def test_load_deepseek_config_accepts_generic_ai_names(monkeypatch):
monkeypatch.setenv("AI_API_KEY", "generic-key")
monkeypatch.setenv("AI_BASE_URL", "https://coding.simgreek.com/v1")
monkeypatch.setenv("AI_TEXT_MODEL", "qwen-plus")
monkeypatch.setenv("AI_AUDIO_MODEL", "qwen-omni-turbo")
config = load_deepseek_config()
assert config.api_key == "generic-key"
assert config.base_url == "https://coding.simgreek.com/v1"
assert config.model == "qwen-plus"
assert config.audio_model == "qwen-omni-turbo"
class EnvPatch:
def __init__(self):
self.originals = {}
@@ -65,6 +79,8 @@ if __name__ == "__main__":
test_ai_status_reports_missing_key(patch)
patch.restore()
test_load_deepseek_config_uses_defaults(patch)
patch.restore()
test_load_deepseek_config_accepts_generic_ai_names(patch)
finally:
patch.restore()
ai_config.read_env_file = original_read_env_file
+5 -4
View File
@@ -33,16 +33,17 @@ My first job as an investor was when I was 24 years old,
My first job as an investor was when I was 24 years old,
"""
result = process_subtitles_with_ai(raw, FakeClient())
result = process_subtitles_with_ai(raw, FakeClient(), timestamp_offset_seconds=0.2)
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
assert "00:00:00.872 --> 00:00:04.959" in result["subtitle_en_content"]
assert "00:00:00.872 --> 00:00:04.959" in result["subtitle_zh_content"]
assert "00:00:01.072 --> 00:00:05.159" in result["subtitle_en_content"]
assert "00:00:01.072 --> 00:00:05.159" in result["subtitle_zh_content"]
assert "timestamp_calibrated" in result["report"]
assert result["report"]["timestamp_calibrated"] is False
assert result["report"]["timestamp_calibrated"] is True
assert result["report"]["timestamp_offset_seconds"] == 0.2
if __name__ == "__main__":
+16 -1
View File
@@ -3,7 +3,7 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from backend.subtitle_tools import build_vtt, clean_english_subtitle
from backend.subtitle_tools import build_vtt, clean_english_subtitle, shift_cues
def test_clean_english_subtitle_removes_empty_and_duplicate_cues():
@@ -43,6 +43,21 @@ def test_build_vtt_outputs_numbered_blocks():
assert result == "WEBVTT\n\n1\n00:00:00.872 --> 00:00:04.959\nMy first job as an investor\n"
def test_shift_cues_moves_time_without_touching_text():
shifted = shift_cues([
{
"start": "00:00:00.200",
"end": "00:00:01.200",
"text": "First line",
}
], -0.5)
assert shifted[0].start == "00:00:00.000"
assert shifted[0].end == "00:00:00.700"
assert shifted[0].text == "First line"
if __name__ == "__main__":
test_clean_english_subtitle_removes_empty_and_duplicate_cues()
test_build_vtt_outputs_numbered_blocks()
test_shift_cues_moves_time_without_touching_text()