-
-
Save aadnk/229c037044dc95eea90ae843289c1dc9 to your computer and use it in GitHub Desktop.
Merge two subtitles (SRT) into a combined SRT file with prefixes.
This file contains 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
import os | |
import re | |
import sys | |
import argparse | |
def convert_to_vtt(input_srt, output_vtt): | |
os.system(f"ffmpeg -i {input_srt} -c:s webvtt {output_vtt}") | |
def convert_to_srt(input_vtt, output_srt): | |
os.system(f"ffmpeg -i {input_vtt} -c:s subrip {output_srt}") | |
def add_prefix(input_vtt, prefix): | |
with open(input_vtt, "r", encoding="utf-8") as file: | |
content = file.read() | |
content = re.sub(r"(\d+\n)", rf"\1{prefix}: ", content) | |
with open(input_vtt, "w", encoding="utf-8") as file: | |
file.write(content) | |
def merge_vtt_files(input_vtt_a, input_vtt_b, output_vtt): | |
with open(input_vtt_a, "r", encoding="utf-8") as file_a, open(input_vtt_b, "r", encoding="utf-8") as file_b: | |
content_a = file_a.read() | |
content_b = file_b.read().replace("WEBVTT\n", "") | |
with open(output_vtt, "w", encoding="utf-8") as output_file: | |
output_file.write(content_a) | |
output_file.write("\n") | |
output_file.write(content_b) | |
def main(args): | |
convert_to_vtt(args.input_srt_a, args.temp_vtt_a) | |
convert_to_vtt(args.input_srt_b, args.temp_vtt_b) | |
add_prefix(args.temp_vtt_a, args.prefix_a) | |
add_prefix(args.temp_vtt_b, args.prefix_b) | |
merge_vtt_files(args.temp_vtt_a, args.temp_vtt_b, args.temp_combined_vtt) | |
convert_to_srt(args.temp_combined_vtt, args.output_srt) | |
# Clean up temporary files | |
os.remove(args.temp_vtt_a) | |
os.remove(args.temp_vtt_b) | |
os.remove(args.temp_combined_vtt) | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser(description="Merge two subtitle files with custom prefixes.") | |
parser.add_argument("input_srt_a", help="Input SRT file A") | |
parser.add_argument("input_srt_b", help="Input SRT file B") | |
parser.add_argument("--prefix_a", default="A", help="Prefix for subtitle entries in file A (default: A)") | |
parser.add_argument("--prefix_b", default="B", help="Prefix for subtitle entries in file B (default: B)") | |
parser.add_argument("--output_srt", default="combined.srt", help="Output combined SRT file (default: combined.srt)") | |
parser.add_argument("--temp_vtt_a", default="temp-A.vtt", help=argparse.SUPPRESS) | |
parser.add_argument("--temp_vtt_b", default="temp-B.vtt", help=argparse.SUPPRESS) | |
parser.add_argument("--temp_combined_vtt", default="temp-combined.vtt", help=argparse.SUPPRESS) | |
args = parser.parse_args() | |
main(args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment