This repository was archived by the owner on May 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathencoder.py
More file actions
316 lines (234 loc) · 9.28 KB
/
Copy pathencoder.py
File metadata and controls
316 lines (234 loc) · 9.28 KB
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
"""
Parses the .csv file from inference output and generate subtitle file.
"""
import pandas as pd
from pandas.io.formats.format import CategoricalFormatter
from config import ROOT_PATH_ABS, SSourceConfig as SSC
from config import RESULT_FOLDER_ABS
class Encoder(object):
"""
Decode pd dataframe for subtitles.
Args:
df: DataFrame containing all events starts and endings.
Attributes:
start_series(List(float)): Start timestamps for events.
end_series(List(float)): End timestamps for events.
texts: Pandas series containing all dialogue texts.
"""
def __init__(self, df:pd.DataFrame) -> None:
super().__init__()
self.df = df
self.start_series = [f"{self._format_time(float(fl))}" for fl in self.df.start]
self.end_series = [f"{self._format_time(float(fl))}" for fl in self.df.end]
# If the STT inference stage is skipped. Set default string "xxx"
try:
self.texts = self.df.recognized_text
except:
self.texts = ['xxx'] * len(self.start_series)
def _format_time(self, fl):
"""
Basic float to string conversion using the mathmatic way.
"""
int_str_part, decimal_str_part = str(fl).split(".")
int_part = int(int_str_part)
decimal_str_part = decimal_str_part[:2]
s = int_part % 60 # seconds
m = (int_part // 60) % 60 # minutes
h = int_part // 3600 # hours
return f"{h}:{m}:{s}.{decimal_str_part}"
class ASSEncoder(Encoder):
"""
Encode for .ass subtitle format.
Args:
df(pd.DataFrame): The dataframe contain source for events.
lang_style(str): The language style in ass standards.
title(str): The title for script infor.
x(str/int): X coordinate for subtitle.
y(str/int): Y coordinate for subtitle.
Properties:
script_info: The script information for .ass subtitle file.
v4_styles: V4 style setting for ssa subtitles.
v4plus_styles: V4+ style setting for ass subtitles.
events: Subtitle events.
"""
def __init__(self, df: pd.DataFrame, lang_style: str, title: str="ASFG", x=384, y=288) -> None:
super().__init__(df)
self.lang_style = lang_style
self.title = title
self.x = x
self.y = y
def _iter2str(self, iter):
"""
Transfer iterables to string.
Args:
iter: Iterable object.
tight(boolean): Whether to use blank space in delimiter.
Returns:
str_line: A single string line.
"""
delimiter = ","
list_source = [str(el) for el in iter]
str_line = delimiter.join(list_source)
return str_line
def _dict2str(self, d: dict, parse=True):
"""
Transfer Dict object to List object.
Args:
dict: The Dictionary object.
parse: Whether to parse dict series.
Returns:
str_lines: String lines.
"""
str_lines = []
for key in d.keys():
str_value = self._iter2str(d[key]) if parse else str(d[key])
str_line = f"{key}: {str_value}"
str_lines.append(str_line)
return str_lines
def _format_time_presentation(self, str_time):
"""
Perfect the format for fit ASS format.
Args:
str_time(str): Represent time as x:x:x.xx
Returns:
formatted_str_time(str): Represent time as x:xx:xx.xx
"""
i, f = str_time.split(".")
h, m, s = i.split(":")
m = ("0" + m) if len(m)<2 else m
s = ("0" + s) if len(s)<2 else s
f = ("0" + f) if len(f)<2 else f
formatted_str_time = f"{h}:{m}:{s}.{f}"
return formatted_str_time
@property
def script_info(self) -> list:
info = SSC.headers
if "Title" in info:
info["Title"] = self.title
if "PlayResX" in info:
info["PlayResX"] = self.x
if "PlayResY" in info:
info["PlayResY"] = self.y
return self._dict2str(info, parse=False)
@property
def v4_styles(self) -> list:
return self._dict2str({
"Format": SSC.v4_pairs.keys(),
"Style": SSC.v4_pairs.values(),
})
@property
def v4plus_styles(self) -> list:
return self._dict2str({
"Format": SSC.v4plus_pairs.keys(),
"Style": SSC.v4plus_pairs.values(),
})
@property
def events(self) -> list:
info = SSC.events_pairs
if "Style" in info:
info["Style"] = self.lang_style
if "Start" in info and "End" in info:
for (s, e, t) in zip(self.start_series, self.end_series, self.texts):
info["Start"] = self._format_time_presentation(s)
info["End"] = self._format_time_presentation(e)
info["Text"] = t
yield self._dict2str({
"Format": info.keys(),
"Dialogue": info.values(),
})
def generate(self, file_name, target_dir=RESULT_FOLDER_ABS, encoding="utf-8"):
"""Generate subtitle file using the encoded proproties.
Handle the propeties and write them in standard subtitle file format.
Here is the place where you turn content to files and you should
do the job about format and encoding only here.
"""
v4_styles = []
try:
v4_styles = self.v4_styles
except:
pass
v4plus_styles = []
try:
v4plus_styles = self.v4plus_styles
except:
pass
assert v4plus_styles or v4_styles, "No styles input for .ass files."
path = f"{target_dir}/{file_name}"
if (not ".ssa" in file_name) or (not ".ass" in file_name):
path = path + (".ass" if v4plus_styles else ".ssa")
with open(path, mode="w", encoding=encoding) as f:
for i in self.script_info:
f.write(i)
f.write("\n")
f.write("\n")
if v4plus_styles:
f.write("[V4+ Styles]")
f.write("\n")
for i in v4plus_styles:
f.write(i)
f.write("\n")
f.write("\n")
if v4_styles:
f.write("[V4 Styles]")
f.write("\n")
for i in v4_styles:
f.write(i)
f.write("\n")
f.write("\n")
f.write("[Events]")
f.write("\n")
f.write(next(self.events)[0])
for event in self.events:
f.write(event[1])
f.write("\n")
f.write("\n")
class SRTEncoder(Encoder):
"""Encode .srt subtitle files from pandas DataFrame.
Properies:
event_timestamps: Indicate the timeline.
"""
def __init__(self, df: pd.DataFrame) -> None:
super().__init__(df)
def _format_time_presentation(self, str_time):
"""Perfect the format of float numbers to fit SRT format.
Args:
str_time(str): Represent time as x:x:x.xx
Returns:
formatted_str_time(str): Represent time as xx:xx:xx,xx0
"""
i, f = str_time.split(".")
h, m, s = i.split(":")
h = ("0" + h) if len(h)<2 else h
m = ("0" + m) if len(m)<2 else m
s = ("0" + s) if len(s)<2 else s
while len(f) < 3:
f = f + "0"
formatted_str_time = f"{h}:{m}:{s},{f}"
return formatted_str_time
@property
def event_timestamps(self) -> list:
event_collections = []
for (s, e) in zip(self.start_series, self.end_series):
event_line = f"{self._format_time_presentation(s)} --> {self._format_time_presentation(e)}"
event_collections.append(event_line)
return event_collections
def generate(self, file_name, target_dir=ROOT_PATH_ABS, encoding="utf-8"):
"""
API offering subtitle generation survice.
Args:
file_name(str): The file name for generating the final result.
target_dir(str): Target folder holding the result.
encoding(str): The encoding for the subtitle file.
"""
path = f"{target_dir}/{file_name}"
if not "srt" in file_name:
path = path + ".srt"
with open(path, mode="w", encoding=encoding) as f:
for (idx, (timeline, text)) in enumerate(zip(self.event_timestamps, self.texts)):
f.write(str(idx+1))
f.write("\n")
f.write(timeline)
f.write("\n")
f.write(text)
f.write("\n")
f.write("\n")