Guest User

splitSRT

a guest
Aug 8th, 2026
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.51 KB | Source Code | 0 0
  1. from datetime import datetime, timedelta
  2. import json
  3. import math
  4. import re
  5.  
  6. TIMESTAMP_FORMAT = "%H:%M:%S,%f"
  7.  
  8.  
  9. def parse_timestamp(ts_str):
  10. """Converts an SRT timestamp string to a datetime object."""
  11. return datetime.strptime(ts_str, TIMESTAMP_FORMAT)
  12.  
  13.  
  14. def format_timestamp(dt):
  15. """Converts a datetime object back into an SRT timestamp string (HH:MM:SS,mmm)."""
  16. return dt.strftime("%H:%M:%S,") + f"{dt.microsecond // 1000:03d}"
  17.  
  18.  
  19. def parse_and_split_srt(
  20. srt_file_path,
  21. json_output_path="subtitles.json",
  22. chunk_size=200,
  23. txt_prefix="translate_part",
  24. max_duration_sec=8.0,
  25. ):
  26. """1. Parses SRT into JSON (number, start_time, end_time, text)
  27. 2. Adjusts start_time to be AT MOST max_duration_sec before end_time
  28. 3. Generates chunked TXT files for translation
  29. """
  30. with open(srt_file_path, "r", encoding="utf-8") as f:
  31. content = f.read()
  32.  
  33. pattern = re.compile(
  34. r"(\d+)\s*\n" # 1. Number
  35. 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
  36. r"([\s\S]*?)" # 4. Text content
  37. r"(?=\n\s*\n|\Z)" # Double newline or EOF
  38. )
  39.  
  40. json_data = []
  41. txt_entries = []
  42.  
  43. for match in pattern.finditer(content):
  44. sub_number = int(match.group(1))
  45. start_time_str = match.group(2)
  46. end_time_str = match.group(3)
  47. raw_text = match.group(4).strip()
  48.  
  49. start_dt = parse_timestamp(start_time_str)
  50. end_dt = parse_timestamp(end_time_str)
  51.  
  52. # If subtitle duration > max_duration_sec, pull start_time up closer to end_time
  53. duration = (end_dt - start_dt).total_seconds()
  54. if duration > max_duration_sec:
  55. start_dt = end_dt - timedelta(seconds=max_duration_sec)
  56. start_time_str = format_timestamp(start_dt)
  57.  
  58. # 1. Add adjusted timestamps to JSON
  59. json_data.append(
  60. {
  61. "number": sub_number,
  62. "start_time": start_time_str,
  63. "end_time": end_time_str,
  64. "text": raw_text,
  65. }
  66. )
  67.  
  68. # 2. Add formatted string to TXT list
  69. single_line_text = " ".join(raw_text.splitlines())
  70. txt_entries.append(f"{sub_number}. {single_line_text}")
  71.  
  72. # --- Save JSON ---
  73. with open(json_output_path, "w", encoding="utf-8") as f:
  74. json.dump(json_data, f, indent=4, ensure_ascii=False)
  75. print(
  76. f"Saved JSON (start_time capped to max {max_duration_sec}s before end_time) -> {json_output_path}"
  77. )
  78.  
  79. # --- Save TXT Chunks ---
  80. total_chunks = math.ceil(len(txt_entries) / chunk_size)
  81. txt_files_created = []
  82.  
  83. for i in range(total_chunks):
  84. chunk = txt_entries[i * chunk_size : (i + 1) * chunk_size]
  85. filename = f"{txt_prefix}_{i + 1}.txt"
  86.  
  87. with open(filename, "w", encoding="utf-8") as f:
  88. f.write("\n".join(chunk))
  89.  
  90. txt_files_created.append(filename)
  91.  
  92. print(
  93. f"Created {len(txt_files_created)} text chunks -> {', '.join(txt_files_created)}"
  94. )
  95.  
  96. return json_data, txt_files_created
  97.  
  98.  
  99. # --- Example Usage ---
  100. if __name__ == "__main__":
  101. parse_and_split_srt(
  102. srt_file_path="example.srt",
  103. json_output_path="full_subtitles.json",
  104. chunk_size=200,
  105. txt_prefix="translate_part",
  106. max_duration_sec=8.0,
  107. )
Advertisement
Add Comment
Please, Sign In to add comment