diff --git a/scripts/bin/shift-srt.py b/scripts/bin/shift-srt.py index 980a4eb..42e454c 100755 --- a/scripts/bin/shift-srt.py +++ b/scripts/bin/shift-srt.py @@ -1,6 +1,6 @@ -#!/usr/bin/env python3 import argparse from datetime import datetime, timedelta +from pathlib import Path def parse_time(s): return datetime.strptime(s, "%H:%M:%S,%f") @@ -8,27 +8,32 @@ def parse_time(s): def format_time(t): return t.strftime("%H:%M:%S,%f")[:-3] -def shift_srt(input_path, output_path, offset_seconds): +def shift_srt_in_memory(input_path: Path, offset_seconds: float, output_path: Path = None): offset = timedelta(seconds=offset_seconds) - with open(input_path, "r", encoding="utf-8") as infile, open(output_path, "w", encoding="utf-8") as outfile: - for line in infile: - if "-->" in line: - start, end = line.strip().split(" --> ") - new_start = format_time(parse_time(start) + offset) - new_end = format_time(parse_time(end) + offset) - outfile.write(f"{new_start} --> {new_end}\n") - else: - outfile.write(line) + lines = input_path.read_text(encoding="utf-8").splitlines(keepends=True) + + shifted_lines = [] + for line in lines: + if "-->" in line: + start, end = line.strip().split(" --> ") + new_start = format_time(parse_time(start) + offset) + new_end = format_time(parse_time(end) + offset) + shifted_lines.append(f"{new_start} --> {new_end}\n") + else: + shifted_lines.append(line) + + target_path = output_path if output_path else input_path + target_path.write_text("".join(shifted_lines), encoding="utf-8") def main(): parser = argparse.ArgumentParser(description="Shift subtitle timings in an SRT file.") - parser.add_argument("input", help="Path to the input .srt file") - parser.add_argument("output", help="Path to the output .srt file") + parser.add_argument("input", type=Path, help="Path to the input .srt file") parser.add_argument("offset", type=float, help="Time offset in seconds (e.g., 2.5 or -1.25)") + parser.add_argument("-o", "--output", type=Path, help="Optional output file. If not provided, input file is overwritten.") args = parser.parse_args() - shift_srt(args.input, args.output, args.offset) + shift_srt_in_memory(args.input, args.offset, args.output) if __name__ == "__main__": main()