-
Notifications
You must be signed in to change notification settings - Fork 0
/
srtoffset
executable file
·78 lines (69 loc) · 2.78 KB
/
srtoffset
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python3
"""
Script to offset the time in subtitle files in the .srt format. Script
takes in the filename and the offset (in milliseconds) to add or
subtract from the subtitles. It then writes the new subtitles to the
same file. Alternately you can specify the filename as '-' and then
the script will read input from stdin and write output to stdout.
"""
__version__ = '1.0'
__author__ = 'Einar Egilsson'
__date__ = 'March 20th 2008'
__url__ = 'http://einaregilsson.com/2008/03/20/subtitle-fixer/'
import sys, re, datetime
MILLISECOND = 1
SECOND = 1000 * MILLISECOND
MINUTE = 60 * SECOND
HOUR = 60 * MINUTE
def offset_time(time, offset):
""" Takes in list with [hour, minute, second, millisecond] and returns
it with offset milliseconds added and normalized
"""
ms = sum(map(int.__mul__, time, [HOUR, MINUTE, SECOND, MILLISECOND]))
ms += offset
return [ms / HOUR, ms % HOUR / MINUTE, ms % MINUTE / SECOND, ms % SECOND]
def fix_subtitles(lines, offset, output):
""" Takes in list (lines) with all the lines from the subtitle file, adds
offset milliseconds to it and writes the file to output.
"""
pattern = r'(\d\d):(\d\d):(\d\d)[,\.](\d\d\d) --> (\d\d):(\d\d):(\d\d)[,\.](\d\d\d)'
sepPattern = r'\d\d:\d\d:\d\d([,\.])\d\d\d --> \d\d:\d\d:\d\d([,\.])\d\d\d'
for line in lines:
sep = ","
sepMatch = re.match(sepPattern, line)
if sepMatch:
sep = sepMatch.group(1)
timestamp = "%02d:%02d:%02d{sep}%03d".format(sep=sep)
match = re.match(pattern, line)
if match:
nrs = [int(nr) for nr in match.groups(0)]
start = offset_time(nrs[:4], offset)
end = offset_time(nrs[4:8], offset)
output.write(timestamp % tuple(start))
output.write(' --> ')
output.write((timestamp + '\n') % tuple(end))
else:
output.write(line)
def print_header():
print('Subtitle Fixer v%s' % __version__)
print('Author: %s' % __author__)
print(__url__)
print('')
if __name__ == '__main__':
if len(sys.argv) != 3:
print_header()
print('Usage: suboffset.py <filename> <offset-in-milliseconds>')
print('Use - for filename to read from stdin and print to stdout')
sys.exit(1)
offset = int(sys.argv[2])
file = None
if sys.argv[1] == '-': #Read from stdin and print to stdout
fix_subtitles(sys.stdin.readlines(), offset, sys.stdout)
else: #read from file and write to same file
file = open(sys.argv[1], 'r')
lines = file.readlines()
file.close()
file = open(sys.argv[1], 'w')
fix_subtitles(lines, offset, file)
file.close()
print('Finished adding %s milliseconds to %s' % (offset, sys.argv[1]))