Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import glob
- import json
- import os
- import re
- def load_translated_texts(txt_folder_path, txt_prefix="translate_part"):
- """Reads all translated .txt chunk files and extracts {number: translated_text}."""
- translations = {}
- # Find all text files matching the prefix (e.g., translate_part_1.txt, translate_part_2.txt)
- pattern = os.path.join(txt_folder_path, f"{txt_prefix}_*.txt")
- file_list = sorted(
- glob.glob(pattern),
- key=lambda x: [
- int(c) if c.isdigit() else c for c in re.split(r"(\d+)", x)
- ],
- )
- if not file_list:
- print(
- f"Warning: No files found matching '{pattern}'. Checking current directory instead."
- )
- # Regex to match "123. Translated text goes here..."
- line_pattern = re.compile(r"^(\d+)\.\s*(.*)$")
- for file_path in file_list:
- with open(file_path, "r", encoding="utf-8") as f:
- for line in f:
- line = line.strip()
- if not line:
- continue
- match = line_pattern.match(line)
- if match:
- sub_number = int(match.group(1))
- translated_text = match.group(2).strip()
- translations[sub_number] = translated_text
- return translations
- def recombine_translated_srt(
- json_path="full_subtitles.json",
- txt_folder_path=".",
- txt_prefix="translate_part",
- output_srt_path="translated_output.srt",
- ):
- """Combines translated text chunks back with the JSON metadata to export a final SRT file."""
- # 1. Load original JSON data (with capped timestamps)
- with open(json_path, "r", encoding="utf-8") as f:
- json_data = json.load(f)
- # 2. Parse all translated text chunks into a map
- translations = load_translated_texts(txt_folder_path, txt_prefix)
- print(
- f" Loaded {len(translations)} translated lines from text files."
- )
- srt_blocks = []
- missing_count = 0
- # 3. Match translations with JSON metadata
- for entry in json_data:
- sub_number = entry["number"]
- start_time = entry["start_time"]
- end_time = entry["end_time"]
- # Use translated text if available; fall back to original text if missing
- if sub_number in translations:
- final_text = translations[sub_number]
- else:
- final_text = entry["text"]
- missing_count += 1
- # Format as standard SRT block
- srt_block = f"{sub_number}\n{start_time} --> {end_time}\n{final_text}\n"
- srt_blocks.append(srt_block)
- # 4. Write to finalized .srt file
- with open(output_srt_path, "w", encoding="utf-8") as f:
- f.write("\n".join(srt_blocks))
- if missing_count > 0:
- print(
- f"⚠️ Notice: {missing_count} subtitles were missing from translated text files and used original text."
- )
- print(f" Successfully generated final SRT file -> {output_srt_path}")
- # --- Example Usage ---
- if __name__ == "__main__":
- recombine_translated_srt(
- json_path="full_subtitles.json",
- txt_folder_path=".", # Path where your translated .txt files live
- txt_prefix="translate_part", # Matches "translate_part_1.txt", etc.
- output_srt_path="translated_movie.srt",
- )
Advertisement
Add Comment
Please, Sign In to add comment