-
Notifications
You must be signed in to change notification settings - Fork 1
/
__init__.py
405 lines (364 loc) · 14.7 KB
/
__init__.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
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
393
394
395
396
397
398
399
400
401
402
403
404
405
import os
import sys
import bpy
from bpy.types import Operator
from bpy_extras.io_utils import ImportHelper
from bpy.props import StringProperty, BoolProperty, EnumProperty
import pathlib
import re
bl_info = {
"name": "Subtitle Import & Translation",
"author": "tintwotin",
"version": (0, 1, 0),
"blender": (3, 0, 0),
"description": "Import, translate or bulk change subtitles",
"location": "Sequence Editor > Strip Menu > Import Subtitles",
"warning": "",
"tracker_url": "",
"category": "Sequencer",
}
class SEQUENCER_OT_import_subtitles(Operator, ImportHelper):
"""Import & Translate Subtitles"""
bl_idname = "sequencer.import_subtitles"
bl_label = "Import & Translate Subtitles"
bl_options = {"REGISTER", "UNDO"}
filename_ext = [".srt", ".ass"]
filter_glob: StringProperty(
default="*.srt;*.ass;*.ssa;*.mpl2;*.tmp;*.vtt;*.microdvd",
options={"HIDDEN"},
maxlen=255,
)
do_translate: BoolProperty(
name="Translate Subtitles", description="Translate subtitles", default=False, options={"HIDDEN"},
)
translate_from: EnumProperty(
name="From",
description="Translate from",
items=(
("auto", "Any language (detect)", ""),
("bg", "Bulgarian", ""),
("zh", "Chinese", ""),
("cs", "Czech", ""),
("da", "Danish", ""),
("nl", "Dutch", ""),
("en", "English", ""), # Only usable for source language
# ("en-US", "English (American)", ""), # Only usable for destination language
# ("en-GB", "English (British)", ""), # Only usable for destination language
("et", "Estonian", ""),
("fi", "Finnish", ""),
("fr", "French", ""),
("de", "German", ""),
("el", "Greek", ""),
("hu", "Hungarian", ""),
("id", "Indonesian", ""),
("it", "Italian", ""),
("ja", "Japanese", ""),
("lv", "Latvian", ""),
("lt", "Lithuanian", ""),
("pl", "Polish", ""),
("pt", "Portuguese", ""), # Only usable for source language
# ("pt-PT", "Portuguese", ""), # Only usable for destination language
# ("pt-BR", "Portuguese (Brazilian)", ""), # Only usable for destination language
("ro", "Romanian", ""),
("ru", "Russian", ""),
("sk", "Slovak", ""),
("sl", "Slovenian", ""),
("es", "Spanish", ""),
("sv", "Swedish", ""),
("tr", "Turkish", ""),
("uk", "Ukrainian", ""),
),
default="auto",
options={"HIDDEN"},
)
translate_to: EnumProperty(
name="To",
description="Translate to",
items=(
# ("auto", "Any language (detect)", ""),
("bg", "Bulgarian", ""),
("zh", "Chinese", ""),
("cs", "Czech", ""),
("da", "Danish", ""),
("nl", "Dutch", ""),
# ("en", "English", ""), # Only usable for source language
("en-US", "English (American)", ""), # Only usable for destination language
("en-GB", "English (British)", ""), # Only usable for destination language
("et", "Estonian", ""),
("fi", "Finnish", ""),
("fr", "French", ""),
("de", "German", ""),
("el", "Greek", ""),
("hu", "Hungarian", ""),
("id", "Indonesian", ""),
("it", "Italian", ""),
("ja", "Japanese", ""),
("lv", "Latvian", ""),
("lt", "Lithuanian", ""),
("pl", "Polish", ""),
# ("pt", "Portuguese", ""), # Only usable for source language
("pt-PT", "Portuguese", ""), # Only usable for destination language
(
"pt-BR",
"Portuguese (Brazilian)",
"",
), # Only usable for destination language
("ro", "Romanian", ""),
("ru", "Russian", ""),
("sk", "Slovak", ""),
("sl", "Slovenian", ""),
("es", "Spanish", ""),
("sv", "Swedish", ""),
("tr", "Turkish", ""),
("uk", "Ukrainian", ""),
),
default="en-US",
options={"HIDDEN"},
)
def execute(self, context):
if self.do_translate:
print(self.translate_from)
try:
from srtranslator import SrtFile
from srtranslator.translators.deepl import DeeplTranslator
except ModuleNotFoundError:
import site
import subprocess
import sys
app_path = site.USER_SITE
if app_path not in sys.path:
sys.path.append(app_path)
pybin = sys.executable # bpy.app.binary_path_python # Use for 2.83
print("Ensuring: pip")
try:
subprocess.call([pybin, "-m", "ensurepip"])
except ImportError:
pass
self.report({"INFO"}, "Installing: srtranslator module.")
print("Installing: srtranslator module")
subprocess.check_call([pybin, "-m", "pip", "install", "srtranslator"])
try:
from srtranslator import SrtFile
from srtranslator.translators.deepl import DeeplTranslator
self.report({"INFO"}, "Detected: srtranslator module.")
print("Detected: srtranslator module")
except ModuleNotFoundError:
print("Installation of the srtranslator module failed")
self.report(
{"INFO"},
"Installing srtranslator module failed! Try to run Blender as administrator.",
)
return {"CANCELLED"}
file = self.filepath
if not file:
return {"CANCELLED"}
print("Invalid file")
self.report({"INFO"}, "Invalid file")
translator = DeeplTranslator()
if pathlib.Path(file).is_file():
print("Translating. Please Wait.")
self.report({"INFO"}, "Translating. Please Wait.")
srt = SrtFile(file)
srt.translate(translator, self.translate_from, self.translate_to)
# Making the result subtitles prettier
srt.wrap_lines()
srt.save(f"{os.path.splitext(file)[0]}_translated.srt")
translator.quit()
print("Translating finished.")
self.report({"INFO"}, "Translating finished.")
try:
import pysubs2
except ModuleNotFoundError:
import site
import subprocess
import sys
app_path = site.USER_SITE
if app_path not in sys.path:
sys.path.append(app_path)
pybin = sys.executable # bpy.app.binary_path_python # Use for 2.83
print("Ensuring: pip")
try:
subprocess.call([pybin, "-m", "ensurepip"])
except ImportError:
pass
self.report({"INFO"}, "Installing: pysubs2 module.")
print("Installing: pysubs2 module")
subprocess.check_call([pybin, "-m", "pip", "install", "pysubs2"])
try:
import pysubs2
except ModuleNotFoundError:
print("Installation of the pysubs2 module failed")
self.report(
{"INFO"},
"Installing pysubs2 module failed! Try to run Blender as administrator.",
)
return {"CANCELLED"}
render = bpy.context.scene.render
fps = render.fps / render.fps_base
fps_conv = fps / 1000
editor = bpy.data.scenes[0].sequence_editor
sequences = bpy.context.sequences
if not sequences:
addSceneChannel = 1
else:
channels = [s.channel for s in sequences]
channels = sorted(list(set(channels)))
empty_channel = channels[-1] + 1
addSceneChannel = empty_channel
file = self.filepath
if self.do_translate:
file = f"{os.path.splitext(file)[0]}_translated.srt"
if not file:
return {"CANCELLED"}
if pathlib.Path(file).is_file():
if (
pathlib.Path(file).suffix
not in pysubs2.formats.FILE_EXTENSION_TO_FORMAT_IDENTIFIER
):
print("Unable to extract subtitles from file")
self.report({"INFO"}, "Unable to extract subtitles from file")
return {"CANCELLED"}
try:
subs = pysubs2.load(file, fps=fps, encoding="utf-8")
except:
print("Import failed. Text encoding must be in UTF-8.")
self.report({"INFO"}, "Import failed. Text encoding must be in UTF-8.")
return {"CANCELLED"}
if not subs:
print("No file imported.")
self.report({"INFO"}, "No file imported")
return {"CANCELLED"}
for line in subs:
italics = False
bold = False
position = False
pos = []
line.text = line.text.replace("\\N", "\n")
if r"<i>" in line.text or r"{\i1}" in line.text or r"{\i0}" in line.text:
italics = True
line.text = line.text.replace("<i>", "")
line.text = line.text.replace("</i>", "")
line.text = line.text.replace("{\\i0}", "")
line.text = line.text.replace("{\\i1}", "")
if r"<b>" in line.text or r"{\b1}" in line.text or r"{\b0}" in line.text:
bold = True
line.text = line.text.replace("<b>", "")
line.text = line.text.replace("</b>", "")
line.text = line.text.replace("{\\b0}", "")
line.text = line.text.replace("{\\b1}", "")
if r"{" in line.text:
pos_trim = re.search(r"\{\\pos\((.+?)\)\}", line.text)
print(pos_trim)
pos_trim = pos_trim.group(1)
print(pos_trim)
pos = pos_trim.split(",")
x = int(pos[0]) / render.resolution_x
y = (render.resolution_y - int(pos[1])) / render.resolution_y
position = True
line.text = re.sub(r"{.+?}", "", line.text)
new_strip = editor.sequences.new_effect(
line.text,
"TEXT",
addSceneChannel,
frame_start=int(line.start * fps_conv),
frame_end=int(line.end * fps_conv),
)
new_strip.text = line.text
new_strip.wrap_width = 0.68
new_strip.font_size = 44
new_strip.location[1] = 0.25
new_strip.align_x = "CENTER"
new_strip.align_y = "TOP"
new_strip.use_shadow = True
new_strip.use_box = True
if position:
new_strip.location[0] = x
new_strip.location[1] = y
new_strip.align_x = "LEFT"
if italics:
new_strip.use_italic = True
if bold:
new_strip.use_bold = True
return {"FINISHED"}
def draw(self, context):
pass
class SEQUENCER_PT_import_subtitles(bpy.types.Panel):
bl_space_type = 'FILE_BROWSER'
bl_region_type = 'TOOL_PROPS'
bl_label = "Translate"
bl_parent_id = "FILE_PT_operator"
@classmethod
def poll(cls, context):
sfile = context.space_data
operator = sfile.active_operator
print(operator.bl_idname)
return operator.bl_idname == "SEQUENCER_OT_import_subtitles"
def draw(self, context):
layout = self.layout
layout.use_property_split = True
layout.use_property_decorate = False # No animation.
sfile = context.space_data
operator = sfile.active_operator
layout = layout.column(heading="Subtitles")
layout.prop(operator, "do_translate", text="")
col = layout.column(align=False)
col.prop(operator, "translate_from", text="From")
col.prop(operator, "translate_to", text="To")
col.active = operator.do_translate
class SEQUENCER_OT_copy_textprops_to_selected(Operator):
"""Copy properties from active text strip to selected text strips"""
bl_idname = "sequencer.copy_textprops_to_selected"
bl_label = "Copy Properties to Selected"
bl_options = {"REGISTER", "UNDO"}
def execute(self, context):
current_scene = bpy.context.scene
try:
active = current_scene.sequence_editor.active_strip
except AttributeError:
self.report({"INFO"}, "No active strip selected")
return {"CANCELLED"}
for strip in context.selected_sequences:
if strip.type == active.type == "TEXT":
strip.wrap_width = active.wrap_width
strip.font = active.font
strip.use_italic = active.use_italic
strip.use_bold = active.use_bold
strip.font_size = active.font_size
strip.color = active.color
strip.use_shadow = active.use_shadow
strip.shadow_color = active.shadow_color
strip.use_box = active.use_box
strip.box_color = active.box_color
strip.box_margin = active.box_margin
strip.location[0] = active.location[0]
strip.location[1] = active.location[1]
strip.align_x = active.align_x
strip.align_y = active.align_y
return {"FINISHED"}
def import_subtitles(self, context):
layout = self.layout
layout.separator()
layout.operator("sequencer.import_subtitles", icon="IMPORT")
def copyto_panel_append(self, context):
strip = context.active_sequence_strip
strip_type = strip.type
if strip_type == "TEXT":
layout = self.layout
layout.operator(SEQUENCER_OT_copy_textprops_to_selected.bl_idname)
classes = (
SEQUENCER_OT_import_subtitles,
SEQUENCER_PT_import_subtitles,
SEQUENCER_OT_copy_textprops_to_selected,
)
def register():
for cls in classes:
bpy.utils.register_class(cls)
bpy.types.SEQUENCER_MT_strip.append(import_subtitles)
bpy.types.SEQUENCER_PT_effect.append(copyto_panel_append)
def unregister():
bpy.types.SEQUENCER_PT_effect.remove(copyto_panel_append)
for cls in classes:
bpy.utils.unregister_class(cls)
bpy.types.SEQUENCER_MT_strip.remove(import_subtitles)
if __name__ == "__main__":
register()