Files
subtitle_translator/main.py
2025-12-14 19:00:23 +03:00

73 lines
2.2 KiB
Python

# [DEF:main:Module]
# @PURPOSE: CLI Entry point.
# @RELATION: CALLS -> translation_engine
import sys
import re
from pathlib import Path
from translation_engine import SubtitleOrchestrator
from domain_models import SubtitleLine
# [DEF:parse_srt:Function]
# @PURPOSE: Extract raw text and structure from SRT file.
def parse_srt(file_path: str) -> list[SubtitleLine]:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# Regex to capture standard SRT blocks
pattern = re.compile(r'(\d+)\n(\d{2}:\d{2}:\d{2},\d{3} --> \d{2}:\d{2}:\d{2},\d{3})\n((?:(?!\r?\n\r?\n).)*)', re.DOTALL)
matches = pattern.findall(content)
lines = []
for idx, times, text in matches:
start, end = times.split(' --> ')
# Clean text
clean_text = text.replace('\n', ' ').strip()
lines.append(SubtitleLine(
index=int(idx),
start_time=start,
end_time=end,
original_text=clean_text
))
return lines
# [/DEF:parse_srt]
# [DEF:save_srt:Function]
def save_srt(lines: list[SubtitleLine], path: str):
with open(path, 'w', encoding='utf-8') as f:
for line in lines:
text = line.translated_text if line.translated_text else line.original_text
f.write(f"{line.index}\n{line.start_time} --> {line.end_time}\n{text}\n\n")
# [/DEF:save_srt]
if __name__ == "__main__":
# [STATE:Entry]
if len(sys.argv) < 2:
print("Usage: python main.py <subs.srt>")
sys.exit(1)
input_file = sys.argv[1]
output_file = str(Path(input_file).with_stem(Path(input_file).stem + "_ru"))
engine = SubtitleOrchestrator()
# 1. Load Data
subs = parse_srt(input_file)
full_text = " ".join([s.original_text for s in subs])
# 2. Pass 1: Analyze
print("--- PASS 1: Analyzing Context ---")
context = engine.pass_one_analysis(full_text)
print(f"Detected Genre: {context.genre}")
print(f"Characters found: {len(context.characters)}")
# 3. Pass 2: Translate
print("--- PASS 2: Translating ---")
translated_subs = engine.pass_two_translation(subs)
# 4. Save
save_srt(translated_subs, output_file)
print(f"Saved to {output_file}")
# [STATE:Exit]
# [/DEF:main]