from __future__ import annotations from .subtitle_tools import build_vtt, clean_english_subtitle, shift_cues TRANSLATION_SYSTEM_PROMPT = """ 你是英语学习产品的字幕翻译助手。输入是按顺序排列的英文字幕。 请只返回 JSON,格式为 {"translations":[{"index":1,"zh":"中文翻译"}]}。 要求: 1. 只翻译英文文本,不要改写原文含义。 2. 不要修改时间轴,不要生成任何 start/end/time 字段。 3. 不要增删字幕条数,每个 index 必须返回一条中文。 4. 中文自然,适合英语学习;不要解释。 """.strip() 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(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(english_cues): raise ValueError("AI 返回的翻译条数和英文字幕条数不一致。") zh_cues = [] 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(english_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": bool(timestamp_offset_seconds), "timestamp_offset_seconds": round(timestamp_offset_seconds, 3), "timestamp_note": "首句校准只计算整体偏移,AI 不逐句修改时间轴。", }, }