Repository navigation
Expand file tree
/
Copy pathsrt.py
More file actions
392 lines (344 loc) · 13.5 KB
/
Copy pathsrt.py
File metadata and controls
392 lines (344 loc) · 13.5 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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# python 3.6
import json
import os
import platform
import pydeepl as deepl # https://github.com/EmilioK97/pydeepl/blob/master/pydeepl/pydeepl.py
import threading
import time
class Translator:
def __isFile(self, object=None):
if object == None:
object = self.file
try:
os.listdir(object)
return False
except Exception:
return True
def autodir(self):
try:
directory = os.path.dirname(os.path.realpath(__file__))
if platform.system() == 'Linux':
slash = '/'
elif platform.system() == 'Windows':
slash = '\\'
self.dir = directory + slash
return True
except Exception:
self.dir = None
return False
def autofile(self):
try:
objects = os.listdir(self.dir)
srtfiles = []
try:
for i in range(0, len(objects)):
try:
os.listdir(objects[i])
except Exception:
if objects[i].split(".")[-1] == "srt":
srtfiles.append(objects[i])
try:
self.file = srtfiles[0]
except Exception: # no srt files found in the current directory
self.file = None
return False
except Exception: # no files found in the current directory (practical paradoxon)
self.file = None
return False
except Exception: # no directory selected
self.file = None
return False
def __init__(self, dir=None, thefile=None):
# define directory and automaticly fill if possible
if dir == None:
self.autodir()
else:
self.dir = str(dir)
# define file and automaticly fill if possible
if thefile == None:
self.autofile()
else:
self.file = str(thefile)
# define other
self.filecontent = []
self.interpreted = json.loads('{}')
self.translated = json.loads('{}')
self.fromlang = "auto"
self.tolang = "DE" #['DE', 'EN', 'FR', 'ES', 'IT', 'NL', 'PL']
self.threadtime = 0.3 # (in seconds) change this to a higher value if you get a "TranslationError DeepL call resulted in a unknown result." and wait some time to retry.
def __repr__(self):
return str(self.dir + self.file)
def setdir(self, dir):
try:
os.listdir(dir)
self.dir = dir
return dir
except Exception:
pass
def setfile(self, file):
try:
open(self.dir+str(file))
self.file = file
return file
except Exception:
pass
def _check(self):
try:
os.listdir(self.dir)
try:
open(self.dir + self.file, "r")
return True, "Checked!"
except Exception:
return False, "Failed to read file!"
except Exception:
return False, "Failed to read directory!"
def splithtml(self, string):
string = str(string)
splitten = [""]
for i in range(0, len(string)):
if string[i] == "<":
splitten.append("<")
elif string[i] == ">":
splitten[-1] = splitten[-1] + ">"
if i != len(string) - 1:
splitten.append("")
else:
splitten[-1] = splitten[-1] + string[i]
return splitten
def removehtml(self, content):
if not content is list:
content = self.splithtml(content)
string = ""
if len(content) != 0:
for i in range(0, len(content)):
try:
if not content[i][0] == "<":
string += content[i]
except Exception:
pass
return string
else:
return content
def ishtml(self, string):
if string[0] == "<":
return True
else:
return False
def readfile(self):
filename = open(self.dir + self.file, "r", encoding='utf-8')
content = filename.readlines()
filename.close()
content.insert(0, "\n")
for i in range(0, len(content)): # remove BOM
content[i] = content[i].replace('\ufeff', "")
for i in range(0, len(content)): # removing html
content[i] = self.removehtml(content[i].rstrip())
self.filecontent = content
return content
def buildstring(self, ls, spacer):
string = ""
for i in range(0, len(ls)):
string = string + str(spacer) + str(ls[i])
return string
def interprete(self):
frames = []
for i in range(0, len(self.filecontent)):
if self.filecontent[i].rstrip() == "": # create a new sublist, when there is a free line (start of a new subtitle-frame)
frames.append([])
else: # append content to the latest sublist
frames[len(frames) - 1].append(self.filecontent[i].rstrip())
for i in range(0, len(frames)): # create json data
self.interpreted[frames[i][0]] = {}
self.interpreted[frames[i][0]]['time'] = str(frames[i][1])
sentences = []
for j in range(2, len(frames[i])): # append text to the json data
sentences.append(frames[i][j].split(" "))
self.interpreted[str(frames[i][0])]['lines'] = sentences
return self.interpreted
def translate(self):
interpreted = self.interpreted
self.translated = interpreted
sentence = ""
lines = json.loads('{}') # save the amount of words of the lines in different frames in a json-string
for i in range(0, len(interpreted)): # frame
try: lines[str(i + 1)]
except: lines[str(i + 1)] = {}
for j in range(0, len(interpreted[str(i + 1)]['lines'])): # lines
try: lines[str(i + 1)]
except: lines[str(i + 1)] = {}
sentence = sentence + self.buildstring(interpreted[str(i + 1)]['lines'][j], " ")
try:
lines[str(i + 1)][str(j)] = len(interpreted[str(i + 1)]['lines'][j])
except Exception: pass
if sentence[-1] in ".!?" and not sentence[-2] in ".!?": # end of a sentence at the end of a line found
thread = threading.Thread(target=self.translation_executor, args=((sentence, lines),))
thread.start()
time.sleep(self.threadtime) # change this to a higher value if you get a "TranslationError DeepL call resulted in a unknown result." and wait some time to retry.
sentence = ""
lines = json.loads('{}')
thread.join()
def translation_executor(self, datatuple):
sentence = datatuple[0]
lines = datatuple[1]
sentence = deepl.translate(sentence, self.tolang, self.fromlang).split(" ") # translate the sentence
print(self.buildstring(sentence, " ")[1:])
totalframes = len(lines)
framecounter = 0
for i in range(0, len(sentence)): # add buffer to prevent errors
sentence.append([])
for i in lines: # frames
framecounter += 1
tallest_key = -1
for j in lines[i]:
if int(j) > tallest_key:
tallest_key = int(j)
for j in lines[i]: # line
wordamount = lines[i][j]
if framecounter == totalframes and int(j) == tallest_key: # last line of the translated section
newline = sentence
else: # not the last
newline = sentence[:wordamount]
sentence = sentence[wordamount:]
self.translated[i]['lines'][int(j)] = []
for k in range(0, len(newline)): # replace the original sentence with the translated sentence
if newline[k] != []:
self.translated[i]['lines'][int(j)].append(newline[k])
if len(self.translated[i]['lines'][int(j)]) == 0: # prevent errors, if the translated is shorter than the original sentence
self.translated[i]['lines'][int(j)] = " "
newline = []
def buildfile(self):
content = self.translated # create the file
newfilename = self.buildstring(self.file.split(".")[:-1], "") + "_" + self.tolang.upper() + ".srt"
try: os.remove(self.dir + newfilename)
except: pass
f = open(self.dir + newfilename, 'w')
for i in range(0,len(content)):
f.write(str(i + 1) + "\n")
f.write(content[str(i + 1)]['time'] + "\n")
for j in range(0, len(content[str(i + 1)]['lines'])):
text = self.buildstring(content[str(i + 1)]['lines'][j], " ")[1:]
#text = text.encode('cp850','replace').decode('cp850')
f.write(text + "\n")
if not i == len(content) - 1: # two free lines at the end of a file could cause errors
f.write("\n")
f.close()
def run(self):
good, error = self._check()
if not good:
return error
self.readfile()
self.interprete()
print(json.dumps(self.interpreted, indent=4))
self.translate()
self.buildfile()
def printProperties(self):
print("Selected properties:")
print(" directory:", self.dir)
print(" file:", self.file)
print(" translate from:", self.fromlang)
print(" translate to:", self.tolang)
def printCommands(self):
print("Commands:")
print(" autodir - select the workdirectory")
print(" dir <dir> - select another path")
print(" autofile - select automaticly a .srt file from the selected path")
print(" file <filename> - select a .srt file from the selected path")
print(" fromlang <lang> - choose a the language of the file.")
print(" tolang <lang> - choose a the language of the file.")
print(" show - show all properties")
print(" langs - show all languages")
print(" run - start the translation")
def printLanguages(self):
print("Available languages:")
print(" DE, EN, FR, ES, IT, NL, PL")
print(" You can also choose \"auto\" for the base language.")
if __name__ == "__main__":
tl = Translator()
tl.printProperties()
print("")
tl.printCommands()
print("")
tl.printLanguages()
while True:
com = []
inp = input("\nCommand: ").split(" ")
print()
com.append(inp[0])
args = ""
for i in range(1, len(inp)):
args = args + " " + inp[i]
if args != "":
args = args[1:]
com.append(args)
if com[0] == "autodir":
tl.autodir()
tl.printProperties()
elif com[0] == "dir":
if platform.system() == 'Linux':
if com[1][-1:] != "/":
com[1] += "/"
elif platform.system() == 'Windows':
if com[1][-1:] != "\\":
com[1] += "\\"
if os.path.exists(com[1]):
tl.dir = com[1]
tl.printProperties()
else:
print(" ERROR: The path is not available!\n Use \\\\ on Windows and / on Linux. ")
continue
elif com[0] == "autofile":
lastfile = tl.file
if tl.autofile() == False:
tl.file = lastfile
print(" ERROR: There is no .srt file.")
else:
tl.printProperties()
continue
elif com[0] == "file":
if args[-4:] != ".srt":
print(" ERROR: This is not an .srt file.")
continue
try:
open(tl.dir + args)
tl.file = args
tl.printProperties()
continue
except:
print(" ERROR: Can't access file.")
continue
elif com[0] == "fromlang":
if args.upper() in ['DE', 'EN', 'FR', 'ES', 'IT', 'NL', 'PL']:
tl.fromlang = args.upper()
tl.printProperties()
continue
elif args.lower() == "auto":
tl.fromlang = "auto"
tl.printProperties()
continue
else:
print(" ERROR: Unavailable language\n")
tl.printLanguages()
continue
elif com[0] == "tolang":
if args.upper() in ['DE', 'EN', 'FR', 'ES', 'IT', 'NL', 'PL']:
tl.tolang = args.upper()
tl.printProperties()
continue
else:
print(" ERROR: Unavailable language.\n")
tl.printLanguages()
continue
elif com[0] == "run":
print(" Startung translation of", tl)
tl.run()
exit()
elif com[0] == "show":
tl.printProperties()
continue
elif com[0] == "langs":
tl.printLanguages()
continue
else:
print(" ERROR: Invalid command.\n")
tl.printCommands()
continue