-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsrt.py
110 lines (79 loc) · 3.34 KB
/
srt.py
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import re
class SRT:
def __init__(self, srt_document):
self.times = []
self.speakers = []
self.original_texts = []
self.translated_texts = []
self.column_count = 0
self.endl = "\n"
_times_found = 0
for i in range(0, int(len(srt_document))):
if self._convert_time(srt_document.items[i], test_only=True):
_times_found = _times_found + 1
if _times_found > 1:
break
self.column_count = self.column_count + 1
if len(srt_document) % self.column_count != 0:
count = 0
for item in srt_document.items:
count = count + 1
print (item)
if count == self.column_count:
count = 0
print("-----")
raise Exception("Document has no valid structure: ({})".format(self.column_count))
for i in range(0, int(len(srt_document) / self.column_count)):
index = i * self.column_count
if srt_document.items[index] == "":
continue
self.times.append(self._convert_time(srt_document.items[index]))
self.speakers.append(srt_document.items[index + 1])
self.original_texts.append(srt_document.items[index + 2])
self.translated_texts.append(srt_document.items[index + self.column_count - 1])
def _convert_time(self, time, test_only=False):
reg = re.compile("[0-9]{2}[:][0-9]{2}[:][0-9]{2}[:][0-9]*")
values = time.split(" ")
if len(values) < 2:
if test_only:
return False
raise ValueError(time)
res = reg.fullmatch(values[0])
if res is None:
if test_only:
return False
raise ValueError(time)
res = reg.fullmatch(values[1])
if res is None:
if test_only:
return False
raise ValueError(time)
if test_only:
return True
return "{},{:0<3} --> {},{:0<3}".format(values[0][:8], values[0][9:], values[1][:8], values[1][9:])
def __str__(self):
res = ""
for i in range(0, len(self.times)):
res = res + self.endl + str(i + 1) + self.endl + self.times[i] + self.endl + self.speakers[i] + self.endl + self.original_texts[i] + self.endl + self.translated_texts[i] + self.endl
return res
def format(self, index=True, speaker=False, original_text=False, translated_text=True):
# if nothing is True
if not index and not time and not speaker and not original_text and not translated_text:
return ""
res = ""
index_offset = 1
for i in range(0, len(self.times)):
if self.times[i] == "":
index_offset = index_offset - 1
continue
if index:
res = res + str(i + index_offset) + self.endl
res = res + self.times[i] + self.endl
if speaker:
res = res + self.speakers[i] + self.endl
if original_text:
res = res + self.original_texts[i] + self.endl
if translated_text:
res = res + self.translated_texts[i] + self.endl
res = res + self.endl
return res