50 lines
1.9 KiB
Python
50 lines
1.9 KiB
Python
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,
|
|
},
|
|
}
|