Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from datetime import datetime, timedelta
- import json
- import math
- import re
- TIMESTAMP_FORMAT = "%H:%M:%S,%f"
- def parse_timestamp(ts_str):
- """Converts an SRT timestamp string to a datetime object."""
- return datetime.strptime(ts_str, TIMESTAMP_FORMAT)
- def format_timestamp(dt):
- """Converts a datetime object back into an SRT timestamp string (HH:MM:SS,mmm)."""
- return dt.strftime("%H:%M:%S,") + f"{dt.microsecond // 1000:03d}"
- def parse_and_split_srt(
- srt_file_path,
- json_output_path="subtitles.json",
- chunk_size=200,
- txt_prefix="translate_part",
- max_duration_sec=8.0,
- ):
- """1. Parses SRT into JSON (number, start_time, end_time, text)
- 2. Adjusts start_time to be AT MOST max_duration_sec before end_time
- 3. Generates chunked TXT files for translation
- """
- with open(srt_file_path, "r", encoding="utf-8") as f:
- content = f.read()
- pattern = re.compile(
- r"(\d+)\s*\n" # 1. Number
- r"(\d{2}:\d{2}:\d{2},\d{3})\s*-->\s*(\d{2}:\d{2}:\d{2},\d{3})\s*\n" # 2 & 3. Start & End time
- r"([\s\S]*?)" # 4. Text content
- r"(?=\n\s*\n|\Z)" # Double newline or EOF
- )
- json_data = []
- txt_entries = []
- for match in pattern.finditer(content):
- sub_number = int(match.group(1))
- start_time_str = match.group(2)
- end_time_str = match.group(3)
- raw_text = match.group(4).strip()
- start_dt = parse_timestamp(start_time_str)
- end_dt = parse_timestamp(end_time_str)
- # If subtitle duration > max_duration_sec, pull start_time up closer to end_time
- duration = (end_dt - start_dt).total_seconds()
- if duration > max_duration_sec:
- start_dt = end_dt - timedelta(seconds=max_duration_sec)
- start_time_str = format_timestamp(start_dt)
- # 1. Add adjusted timestamps to JSON
- json_data.append(
- {
- "number": sub_number,
- "start_time": start_time_str,
- "end_time": end_time_str,
- "text": raw_text,
- }
- )
- # 2. Add formatted string to TXT list
- single_line_text = " ".join(raw_text.splitlines())
- txt_entries.append(f"{sub_number}. {single_line_text}")
- # --- Save JSON ---
- with open(json_output_path, "w", encoding="utf-8") as f:
- json.dump(json_data, f, indent=4, ensure_ascii=False)
- print(
- f"Saved JSON (start_time capped to max {max_duration_sec}s before end_time) -> {json_output_path}"
- )
- # --- Save TXT Chunks ---
- total_chunks = math.ceil(len(txt_entries) / chunk_size)
- txt_files_created = []
- for i in range(total_chunks):
- chunk = txt_entries[i * chunk_size : (i + 1) * chunk_size]
- filename = f"{txt_prefix}_{i + 1}.txt"
- with open(filename, "w", encoding="utf-8") as f:
- f.write("\n".join(chunk))
- txt_files_created.append(filename)
- print(
- f"Created {len(txt_files_created)} text chunks -> {', '.join(txt_files_created)}"
- )
- return json_data, txt_files_created
- # --- Example Usage ---
- if __name__ == "__main__":
- parse_and_split_srt(
- srt_file_path="example.srt",
- json_output_path="full_subtitles.json",
- chunk_size=200,
- txt_prefix="translate_part",
- max_duration_sec=8.0,
- )
Advertisement
Add Comment
Please, Sign In to add comment