122 lines
4.5 KiB
Python
122 lines
4.5 KiB
Python
from __future__ import annotations
|
|
|
|
from .subtitle_tools import SubtitleCue, build_vtt, clean_english_subtitle
|
|
|
|
|
|
TRANSLATION_SYSTEM_PROMPT = """
|
|
你是英语学习产品的字幕处理助手。输入是按顺序排列的英文字幕。
|
|
请只返回 JSON,格式为 {"translations":[{"index":1,"zh":"中文翻译"}]}。
|
|
要求:
|
|
1. 只翻译英文文本,不要改写原文含义。
|
|
2. 不要修改时间轴,不要生成任何 start/end/time 字段。
|
|
3. 不要增删字幕条数,每个输入 index 必须返回且只返回一条中文。
|
|
4. translations 可以乱序,但 index 必须和输入完全一致。
|
|
5. 中文自然,适合英语学习;不要解释。
|
|
""".strip()
|
|
|
|
|
|
def process_subtitles_with_ai(
|
|
english_content: str,
|
|
client,
|
|
batch_size: int = 0,
|
|
) -> dict[str, object]:
|
|
cleaned = clean_english_subtitle(english_content)
|
|
if not cleaned.cues:
|
|
raise ValueError("英文字幕为空,无法处理。")
|
|
english_cues = cleaned.cues
|
|
|
|
translations = translate_cues(english_cues, client, batch_size)
|
|
|
|
zh_cues = []
|
|
for index, cue in enumerate(english_cues, 1):
|
|
translation = translations[index]
|
|
zh_text = str(translation.get("zh", "")).strip()
|
|
if not zh_text:
|
|
raise ValueError(f"AI 返回了空翻译:index {index}")
|
|
zh_cues.append({"start": cue.start, "end": cue.end, "text": zh_text})
|
|
|
|
translation_batches = count_batches(len(english_cues), batch_size)
|
|
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),
|
|
"translation_batches": translation_batches,
|
|
},
|
|
}
|
|
|
|
|
|
def translate_cues(
|
|
cues: list[SubtitleCue],
|
|
client,
|
|
batch_size: int,
|
|
) -> dict[int, dict[str, object]]:
|
|
translations: dict[int, dict[str, object]] = {}
|
|
indexed_cues = list(enumerate(cues, 1))
|
|
effective_batch_size = int(batch_size or 0)
|
|
batches = (
|
|
[indexed_cues]
|
|
if effective_batch_size <= 0 or effective_batch_size >= len(indexed_cues)
|
|
else [indexed_cues[start:start + effective_batch_size] for start in range(0, len(indexed_cues), effective_batch_size)]
|
|
)
|
|
|
|
for batch in batches:
|
|
expected_indexes = {index for index, _cue in batch}
|
|
collect_translations(batch, expected_indexes, translations, client)
|
|
missing = sorted(expected_indexes - translations.keys())
|
|
if missing:
|
|
missing_batch = [(index, cue) for index, cue in batch if index in missing]
|
|
collect_translations(missing_batch, set(missing), translations, client)
|
|
missing = sorted(expected_indexes - translations.keys())
|
|
if missing:
|
|
for index, cue in [(index, cue) for index, cue in batch if index in missing]:
|
|
collect_translations([(index, cue)], {index}, translations, client)
|
|
missing = sorted(expected_indexes - translations.keys())
|
|
if missing:
|
|
raise ValueError(f"AI 返回的翻译条数和英文字幕条数不一致,缺少 index:{missing[:10]}")
|
|
|
|
return translations
|
|
|
|
|
|
def collect_translations(
|
|
batch: list[tuple[int, SubtitleCue]],
|
|
expected_indexes: set[int],
|
|
translations: dict[int, dict[str, object]],
|
|
client,
|
|
) -> None:
|
|
if not batch:
|
|
return
|
|
payload = {
|
|
"cues": [
|
|
{"index": index, "text": cue.text}
|
|
for index, cue in batch
|
|
]
|
|
}
|
|
response = client.chat_json(TRANSLATION_SYSTEM_PROMPT, payload)
|
|
batch_translations = response.get("translations")
|
|
if not isinstance(batch_translations, list):
|
|
raise ValueError("AI 返回结果缺少 translations。")
|
|
|
|
for item in batch_translations:
|
|
if not isinstance(item, dict):
|
|
continue
|
|
try:
|
|
item_index = int(item.get("index"))
|
|
except (TypeError, ValueError):
|
|
continue
|
|
if item_index in expected_indexes:
|
|
translations[item_index] = item
|
|
|
|
|
|
def count_batches(cue_count: int, batch_size: int) -> int:
|
|
effective_batch_size = int(batch_size or 0)
|
|
if cue_count <= 0:
|
|
return 0
|
|
if effective_batch_size <= 0 or effective_batch_size >= cue_count:
|
|
return 1
|
|
return (cue_count + effective_batch_size - 1) // effective_batch_size
|