Last active
February 13, 2025 14:31
-
-
Save 403-html/b1cf9e9845930cc22b18b1297931fbad to your computer and use it in GitHub Desktop.
Converts a frame-based subtitle file to SRT format.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
python convert_srt.py from.srt to.srt | |
default frame rate for most movies is: 23.976 | |
encoding is set to: windows-1250 (usually non-english subtitles have frame based subtitling) | |
Example "from.srt": | |
{0}{100}Hello, world! | |
{101}{300}This is a frame-based subtitle file. | |
Example "to.srt": | |
1 | |
00:00:00,000 --> 00:00:04,167 | |
Hello, world! | |
2 | |
00:00:04,167 --> 00:00:10,000 | |
This is a frame-based subtitle file. | |
""" | |
import re | |
import sys | |
def convert_to_srt(input_file, output_file, frame_rate=23.976, encoding='utf-8'): | |
try: | |
with open(input_file, 'r', encoding=encoding) as infile, open(output_file, 'w', encoding='utf-8') as outfile: | |
subtitle_number = 1 | |
for line in infile: | |
match = re.match(r'\{(\d+)\}\{(\d+)\}(.*)', line) | |
if match: | |
start_frame, end_frame, text = match.groups() | |
start_time = float(start_frame) / frame_rate | |
end_time = float(end_frame) / frame_rate | |
start_time_formatted = format_time(start_time) | |
end_time_formatted = format_time(end_time) | |
outfile.write(str(subtitle_number) + '\n') | |
outfile.write(f"{start_time_formatted} --> {end_time_formatted}\n") | |
outfile.write(text.strip() + '\n\n') | |
subtitle_number += 1 | |
elif line.strip(): | |
outfile.write(line) | |
except FileNotFoundError: | |
print(f"Error: Input file '{input_file}' not found.") | |
except UnicodeDecodeError as e: | |
print(f"Encoding error: {e}. Try a different encoding (e.g., 'latin-1', 'cp1252').") | |
return | |
except Exception as e: | |
print(f"An error occurred: {e}") | |
def format_time(seconds): | |
milliseconds = int(round((seconds * 1000) % 1000)) | |
seconds = int(seconds) | |
minutes = seconds // 60 | |
seconds %= 60 | |
hours = minutes // 60 | |
minutes %= 60 | |
return f"{hours:02}:{minutes:02}:{seconds:02},{milliseconds:03}" | |
if __name__ == "__main__": | |
if len(sys.argv) < 3: | |
print("Usage: python convert_subtitles.py <input_file> <output_file> [<frame_rate>]") | |
sys.exit(1) | |
input_file = sys.argv[1] | |
output_file = sys.argv[2] | |
if len(sys.argv) > 3: | |
try: | |
frame_rate = float(sys.argv[3]) | |
except ValueError: | |
print("Error: Invalid frame rate. Using default 23.976.") | |
frame_rate = 23.976 | |
else: | |
frame_rate = 23.976 | |
try: | |
convert_to_srt(input_file, output_file, frame_rate, encoding='windows-1250') | |
except Exception as e: | |
print(f"An error occurred: {e}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment