#!/usr/bin/python3 """Script for changing timelines of out-of-sync subtitles.""" import argparse from typing import List, Tuple def main(): """Create a new file with update timeline, given the offset in seconds.""" parser = argparse.ArgumentParser() parser.add_argument('file', help='file containing the subtitles to update') parser.add_argument( 'offset', help='number of seconds to update the file with' ) args = parser.parse_args() file = args.file offset = int(args.offset) output: List[str] = [] with open(file, 'r') as subtitles: for line in subtitles.readlines(): if '-->' in line: start: str = line.split(' --> ')[0] new_start: str = get_new_timeline(start, offset) end: str = line.split(' --> ')[1] new_end: str = get_new_timeline(end, offset) new_line: str = "{} --> {}".format(new_start, new_end) output.append(new_line) else: output.append(line) new_file = "UPDATED.{}".format(file) with open(new_file, 'w') as newfile: newfile.write(''.join(output)) def convert_time_to_total_seconds(hrs: int, mns: int, scs: int) -> int: """Take hours, minutes, seconds, Return total seconds.""" minutes: int = hrs * 60 + mns seconds: int = minutes * 60 + scs return seconds def convert_time_to_h_m_s(seconds: int) -> Tuple[int, int, int]: """Take total seconds, Return hours, minutes, seconds.""" minutes: int = seconds // 60 hours = minutes // 60 minutes %= 60 seconds %= 60 return hours, minutes, seconds def get_new_timeline(string: str, offset: int) -> str: """Convert timeline.""" hours: str = string.split(':')[0] minutes: str = string.split(':')[1] seconds: str = string.split(':')[2].split(',')[0] milliseconds: str = string.split(',')[1] temp_seconds = convert_time_to_total_seconds( int(hours), int(minutes), int(seconds) ) temp_seconds += offset new_hours, new_minutes, new_seconds = convert_time_to_h_m_s(temp_seconds) new_h = "{0:02d}".format(new_hours) new_m = "{0:02d}".format(new_minutes) new_s = "{0:02d}".format(new_seconds) new_string: str = "{}:{}:{},{}".format( new_h, new_m, new_s, milliseconds ) return new_string if __name__ == '__main__': main()