Created
September 4, 2022 11:34
-
-
Save mgd020/e60b9b44aedf32eebc227094a2ecc748 to your computer and use it in GitHub Desktop.
Offset and scale SRT translation file
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
from dataclasses import dataclass | |
from datetime import datetime, timedelta | |
TIME_FORMAT = '%H:%M:%S,%f' | |
def load_time(s: str) -> float: | |
t = datetime.strptime(s, TIME_FORMAT) | |
return (t - t.replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds() | |
def dump_time(s: float) -> str: | |
t = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0) | |
return (t + timedelta(seconds=s)).time().strftime(TIME_FORMAT)[:-3] | |
@dataclass | |
class Subtitle: | |
index: int | |
start: float | |
finish: float | |
text: list[str] | |
def __str__(self): | |
return ( | |
f'{self.index}\n' | |
f'{dump_time(self.start)} --> {dump_time(self.finish)}\n' | |
) + '\n'.join(self.text) | |
def iter_subtitles(file): | |
while True: | |
# '1\n' | |
try: | |
index = int(next(file)[:-1]) | |
except StopIteration: | |
return | |
# '00:01:38,246 --> 00:01:39,855\n' | |
start, finish = next(file)[:-1].split(' --> ') | |
start, finish = load_time(start), load_time(finish) | |
# "We're screwed.\n" | |
# '\n' | |
text = [] | |
while True: | |
try: | |
line = next(file) | |
except StopIteration: | |
break | |
if len(line) == 1: | |
break | |
text.append(line[:-1]) | |
yield Subtitle(index, start, finish, text) | |
def main(path, start, finish): | |
with open(path, 'r') as file: | |
subtitles = list(iter_subtitles(file)) | |
subtitles_start = subtitles[0].start | |
scale = (finish - start) / (subtitles[-1].finish - subtitles_start) | |
for sub in subtitles: | |
sub.start = (sub.start - subtitles_start) * scale + start | |
sub.finish = (sub.finish - subtitles_start) * scale + start | |
print(sub) | |
print('') | |
if __name__ == '__main__': | |
import argparse | |
parser = argparse.ArgumentParser() | |
parser.add_argument('path', help='Path of SRT file to read') | |
parser.add_argument('start', type=load_time, help='Time when the first word is started (HH:MM:SS,fff)') | |
parser.add_argument('finish', type=load_time, help='Time when the last word is finished (HH:MM:SS,fff)') | |
main(**vars(parser.parse_args())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment