-
Notifications
You must be signed in to change notification settings - Fork 29
/
movies2anki.py
2535 lines (2005 loc) · 96.7 KB
/
movies2anki.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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# import the main window object (mw) from aqt
from aqt import mw, gui_hooks
# import the "get file" tool from utils.py
from aqt.qt import *
from aqt.utils import showInfo
from anki.utils import call, no_bundled_libs, is_mac, is_win
from .utils import format_filename
try:
from aqt.sound import _packagedCmd, si
import aqt.sound as sound # Anki 2.1.17+
except ImportError:
from anki.sound import _packagedCmd, si
import anki.sound as sound
from distutils.spawn import find_executable
from . import media
import json
import os
import re
import shutil
import string
import sys
import time
import tempfile
import traceback
import os
from collections import deque
from subprocess import check_output, check_call
from subprocess import Popen
import subprocess
from . import glob
from . import styles
sys.path.append(os.path.join(os.path.dirname(__file__), "vendor"))
import pysubs2
if is_mac and '/usr/local/bin' not in os.environ['PATH'].split(':'):
# https://docs.brew.sh/FAQ#my-mac-apps-dont-find-usrlocalbin-utilities
os.environ['PATH'] = "/usr/local/bin:" + os.environ['PATH']
if is_mac and '/opt/homebrew/bin' not in os.environ['PATH'].split(':'):
# https://docs.brew.sh/FAQ#my-mac-apps-dont-find-usrlocalbin-utilities
os.environ['PATH'] = "/opt/homebrew/bin:" + os.environ['PATH']
ffprobe_executable = find_executable("ffprobe")
ffmpeg_executable = find_executable("ffmpeg")
mpv_executable = find_executable("mpv")
if mpv_executable is None and is_mac:
mpv_executable = "/Applications/mpv.app/Contents/MacOS/mpv"
if not os.path.exists(mpv_executable):
mpv_executable = None
with_bundled_libs = False
if mpv_executable is None:
mpv_path, env = _packagedCmd(["mpv"])
mpv_executable = mpv_path[0]
with_bundled_libs = True
info = None
if is_win:
info = subprocess.STARTUPINFO()
info.wShowWindow = subprocess.SW_HIDE
info.dwFlags = subprocess.STARTF_USESHOWWINDOW
# maybe a fix for macOS
# if ffprobe_executable is None:
# ffprobe_executable = '/usr/local/bin/ffprobe'
# if ffmpeg_executable is None:
# ffmpeg_executable = '/usr/local/bin/ffmpeg'
# anki.utils.py
if is_win:
si = subprocess.STARTUPINFO()
try:
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
except:
# pylint: disable=no-member
si.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW
else:
si = None
# Determine if we're frozen with Pyinstaller or not.
if getattr(sys, 'frozen', False):
isFrozen = True
else:
isFrozen = False
# Create a set of arguments which make a ``subprocess.Popen`` (and
# variants) call work with or without Pyinstaller, ``--noconsole`` or
# not, on Windows and Linux. Typical use::
#
# subprocess.call(['program_to_run', 'arg_1'], **subprocess_args())
#
# When calling ``check_output``::
#
# subprocess.check_output(['program_to_run', 'arg_1'],
# **subprocess_args(False))
def subprocess_args(include_stdout=True):
# The following is true only on Windows.
if hasattr(subprocess, 'STARTUPINFO'):
# On Windows, subprocess calls will pop up a command window by default
# when run from Pyinstaller with the ``--noconsole`` option. Avoid this
# distraction.
si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# Windows doesn't search the path by default. Pass it an environment so
# it will.
env = os.environ
else:
si = None
env = None
# ``subprocess.check_output`` doesn't allow specifying ``stdout``::
#
# Traceback (most recent call last):
# File "test_subprocess.py", line 58, in <module>
# **subprocess_args(stdout=None))
# File "C:\Python27\lib\subprocess.py", line 567, in check_output
# raise ValueError('stdout argument not allowed, it will be overridden.')
# ValueError: stdout argument not allowed, it will be overridden.
#
# So, add it only if it's needed.
if include_stdout:
ret = {'stdout': subprocess.PIPE}
else:
ret = {}
# On Windows, running this from the binary produced by Pyinstaller
# with the ``--noconsole`` option requires redirecting everything
# (stdin, stdout, stderr) to avoid an OSError exception
# "[Error 6] the handle is invalid."
ret.update({'stdin': subprocess.PIPE,
'stderr': subprocess.PIPE,
'startupinfo': si,
'env': env })
return ret
def srt_time_to_seconds(time):
split_time = re.split(r'[,\.]', time)
major, minor = (split_time[0].split(':'), split_time[1])
return int(major[0]) * 3600 + int(major[1]) * 60 + int(major[2]) + float(minor) / 1000
def tsv_time_to_seconds(tsv_time):
return srt_time_to_seconds(tsv_time.replace(".", ","))
def get_time_parts(time):
millisecs = str(time).split(".")[1][:3]
if len(millisecs) != 3:
millisecs = millisecs + ('0' * (3 - len(millisecs)))
millisecs = int(millisecs)
mins, secs = divmod(time, 60)
hours, mins = divmod(mins, 60)
return (hours, mins, secs, millisecs)
def seconds_to_srt_time(time):
return '%02d:%02d:%02d,%03d' % get_time_parts(time)
def seconds_to_tsv_time(time):
return '%d.%02d.%02d.%03d' % get_time_parts(time)
def seconds_to_ffmpeg_time(time):
return '%02d:%02d:%02d.%03d' % get_time_parts(time)
def fix_empty_lines(content):
return re.sub('\n\n+', '\n\n', content)
def escape_double_quotes(content):
return re.sub('"', '"', content)
def is_not_sdh_subtitle(sub):
reg_exp_round_braces = r"^\([^)]*\)(\s*\([^)]*\))*$"
reg_exp_square_braces = r"^[-\s]*\[[^\]]*\]\s*(\s*\[[^\]]*\])*$"
reg_exp_music = r"^(\s*♪\s*)+$"
reg_exp_round_braces_with_tags = r"^(?:- )?(?:<[^>]+>)*\([^)]*\)(\s*\([^)]*\))*(?:<[^>]+>)*$"
reg_exp_round_braces_with_tags_multiline = r"^(\([^)]*\)(\s*\([^)]*\))*|\s|-|(?:<[^>]+>)*)*$"
if re.fullmatch(reg_exp_round_braces, sub):
return False
elif re.fullmatch(reg_exp_square_braces, sub):
return False
elif re.fullmatch(reg_exp_round_braces_with_tags, sub):
return False
elif re.fullmatch(reg_exp_round_braces_with_tags_multiline, sub):
return False
elif re.fullmatch(reg_exp_music, sub):
return False
elif sub == '♪':
return False
return True
def filter_subtitles(subs, is_ignore_SDH, is_gap_phrases):
subs2 = []
for sub_start, sub_end, sub_text in subs:
sub_text = sub_text.strip()
if 'Captioning by' in sub_text:
continue
if 'CaptionMax' in sub_text:
continue
sub_text2 = sub_text.translate(str.maketrans('', '', string.punctuation))
if sub_text2 in ['Hmm', 'Mm', 'Mmhmm', 'Oh', 'Ooh', 'Ugh']:
continue
if is_not_sdh_subtitle(sub_text):
subs2.append((sub_start, sub_end, sub_text))
return subs2
def format_subtitles(subs, is_ignore_SDH, is_gap_phrases):
config = mw.addonManager.getConfig(__name__)
join_lines_separator = config["join lines with"]
join_sentences_separator = config["join sentences with"]
subs2 = []
for sub_start, sub_end, sub_text in subs:
sub_text = re.sub(r"{\\\w+\d*}", "", sub_text)
sub_text = re.sub(r"\t", " ", sub_text)
sub_text = re.sub(r"\n +", "\n", sub_text)
sub_text = re.sub(r" +", " ", sub_text)
sub_text = re.sub(r'<\d+:\d+:\d+\.\d+>', '', sub_text)
sub_chunks = re.split(r'(\\N|\n)', sub_text)
sub_content = sub_chunks[0]
for sub_line in sub_chunks[1:]:
if sub_content and sub_content[-1] not in [u".", u"?", u"!", u"?", u"!", u"♪", '"'] and not sub_line.startswith('- '):
sub_content += join_lines_separator
else:
sub_content += join_sentences_separator
sub_content += sub_line
sub_content = sub_content.strip()
sub_content = re.sub(r'\]', '] ', sub_content)
sub_content = re.sub(r'\s+', ' ', sub_content)
sub_content = re.sub(r'(\w\w)\.([A-Z]\w\w)', r'\1 \2', sub_content)
subs2.append((sub_start, sub_end, sub_content))
return subs2
def read_subtitles(content, is_ignore_SDH, is_gap_phrases):
config = mw.addonManager.getConfig(__name__)
join_lines_separator = config["join lines with"]
join_sentences_separator = config["join sentences with"]
en_subs = []
content = re.sub(r'(?s)^WEBVTT.*?\n\n', '', content).strip()
content = re.sub(r'(^(?:\d+\n)?\d+:\d+:\d+[,\.]\d+\s+-->\s+\d+:\d+:\d+[,\.]\d+)', r'#~~~~~~~~~~~~~~#\1', content, flags=re.M)
for sub_id, sub in enumerate(content.strip().split('#~~~~~~~~~~~~~~#'), 1):
sub = re.sub(r'\n\s*\n', '\n', sub).strip()
if not sub:
continue
sub_chunks = sub.split('\n')
if ' --> ' in sub_chunks[0]:
sub_chunks.insert(0, sub_id)
sub_timecode = sub_chunks[1].split(' --> ')
sub_start = srt_time_to_seconds(sub_timecode[0].strip())
sub_end = srt_time_to_seconds(sub_timecode[1].strip())
if len(sub_chunks) >= 3:
# sub_content = join_lines_separator.join(sub_chunks[2:])
sub_content = sub_chunks[2:][0]
for sub_line in sub_chunks[2:][1:]:
if sub_content[-1] not in [u".", u"?", u"!", u"?", u"!", u"♪", '"'] and not sub_line.startswith('- '):
sub_content += join_lines_separator
else:
sub_content += join_sentences_separator
sub_content += sub_line
sub_content = re.sub(r"{\\\w+\d*}", "", sub_content)
sub_content = re.sub(r"\t", " ", sub_content)
sub_content = re.sub(r"\n +", "\n", sub_content)
sub_content = re.sub(r" +", " ", sub_content)
sub_content = sub_content.strip()
if len(sub_content) > 0:
if not is_ignore_SDH:
en_subs.append((sub_start, sub_end, sub_content))
else:
if is_not_sdh_subtitle(sub_content):
en_subs.append((sub_start, sub_end, sub_content))
# else:
# print "Ignore subtitle: %s" % repr(sub_content)
else:
if not is_gap_phrases:
en_subs.append((sub_start, sub_end, sub_content))
# print "Empty subtitle: %s" % repr(sub)
else:
pass
# print "Ignore empty subtitle: %s" % repr(sub)
return en_subs
# Формат субтитров
# [(start_time, end_time, subtitle), (), ...], [(...)], ...
def join_lines_within_subs(subs):
config = mw.addonManager.getConfig(__name__)
join_sentences_separator = config["join sentences with"]
subs_joined = []
global duration_longest_phrase
duration_longest_phrase = 0
for sub in subs:
sub_start = sub[0][0]
sub_end = sub[-1][1]
sub_content = join_sentences_separator.join(s[2] for s in sub)
subs_joined.append((sub_start, sub_end, sub_content.strip()))
if sub_end - sub_start > duration_longest_phrase:
duration_longest_phrase = int(sub_end - sub_start)
return subs_joined
def split_long_phrases(en_subs, phrases_duration_limit):
subs = []
for sub in en_subs:
sub_start = sub[0][0]
sub_end = sub[-1][1]
if (sub_end - sub_start) > phrases_duration_limit:
sub_chunks_num = int((sub_end - sub_start) / phrases_duration_limit) + 1
# sub_splitted = [[] for i in range(sub_chunks_num+1)]
sub_splitted = []
# +1 for [0...(sub_chunks_num-1)] not [0...sub_chunks_num]
sub_chunks_limit = (sub_end - sub_start + 1) / sub_chunks_num
for s in sub:
s_start = s[0]
s_end = s[1]
s_content = s[2]
if sub_splitted and sub_splitted[-1] and (s_end - sub_splitted[-1][0][0]) > phrases_duration_limit:
sub_splitted.append([])
if not sub_splitted:
sub_splitted.append([])
sub_splitted[-1].append((s_start, s_end, s_content))
for s in sub_splitted:
if not s:
continue
if len(s) != 0:
subs.append(s)
else:
subs.append(sub)
return subs
def remove_tags(sub):
sub = re.sub(r"<[^>]+>", "", sub)
sub = re.sub(r" +", " ", sub)
sub = sub.strip()
return sub
def convert_into_sentences(en_subs, phrases_duration_limit, join_lines_that_end_with, join_questions_with_answers, is_gap_phrases, is_split_long_phrases):
config = mw.addonManager.getConfig(__name__)
join_lines_separator = config["join lines with"]
# if phrases_duration_limit == 0 or not is_split_long_phrases:
# sentence_duration_limit = 15
# else:
# sentence_duration_limit = phrases_duration_limit
sentence_duration_limit = 25
subs = []
for sub in en_subs:
sub_start = sub[0]
sub_end = sub[1]
sub_content_original = sub[2]
sub_content = remove_tags(sub_content_original)
if not sub_content:
continue
if len(subs) > 0:
prev_sub_start = subs[-1][0]
prev_sub_end = subs[-1][1]
prev_sub_content_original = subs[-1][2]
sub_gap = sub_start - prev_sub_end
prev_sub_content = remove_tags(prev_sub_content_original)
flag = False
for regex in join_lines_that_end_with.split():
if (sub_content[0].isalpha() and sub_content[0].islower()) or re.search(regex + r"$", prev_sub_content):
flag = True
break
if sub_gap < 2.5 and prev_sub_content[-1].islower() and prev_sub_content[-1].isalpha():
flag = True
if sub_gap < 2.5 and prev_sub_content[-1] not in '.!?♪' and not sub_content[0].isupper() and (sub_content[0].isalpha() or sub_content[0].isdigit()):
flag = True
if '] ♪' in prev_sub_content or prev_sub_content.startswith('♪'):
flag = False
if prev_sub_content.endswith('♪') or sub_content.startswith('♪'):
flag = False
if sub_content.startswith('...'):
flag = True
if sub_content.startswith('—'):
flag = False
if prev_sub_content and prev_sub_content[-1] in [',', ':']:
flag = True
if prev_sub_content.endswith('...') and (sub_content[0].islower() and sub_content[0].isalpha()):
flag = True
# print('FLAG:', flag)
if not is_gap_phrases:
subs.append((sub_start, sub_end, sub_content_original))
# elif (prev_sub_content.endswith(u"?") or prev_sub_content.endswith(u"?")) and join_questions_with_answers and (sub_start - prev_sub_end) <= 5:
# subs[-1] = (prev_sub_start, sub_end, prev_sub_content_original + join_sentences_separator + sub_content_original)
elif flag and (sub_end - prev_sub_start) <= sentence_duration_limit:
subs[-1] = (prev_sub_start, sub_end, prev_sub_content_original + join_lines_separator + sub_content_original)
else:
subs.append((sub_start, sub_end, sub_content_original))
else:
subs.append((sub_start, sub_end, sub_content_original))
return subs
def join_questions(en_subs, ru_subs, is_gap_phrases):
config = mw.addonManager.getConfig(__name__)
join_sentences_separator = config["join sentences with"]
subs = []
sentence_duration_limit = 15
subs2 = []
for i, sub in enumerate(en_subs):
sub_start = sub[0]
sub_end = sub[1]
sub_content_original = sub[2]
if ru_subs:
sub2_content_original = ru_subs[i][2]
sub_content = remove_tags(sub_content_original)
if not sub_content:
continue
if len(subs) > 0:
prev_sub_start = subs[-1][0]
prev_sub_end = subs[-1][1]
prev_sub_content_original = subs[-1][2]
if ru_subs:
prev_sub2_content_original = subs2[-1][2]
prev_sub_content = remove_tags(prev_sub_content_original)
flag = True
if sub_content.startswith('♪'):
flag = False
if sub_content.endswith('?'):
flag = False
if not is_gap_phrases:
flag = False
# if sub_content.endswith('?') and not sub_content.startswith('- '):
# flag = False
if flag and (prev_sub_content.endswith(u"?") or prev_sub_content.endswith(u"?")) and (sub_start - prev_sub_end) <= 1 and (sub_end - prev_sub_start) <= sentence_duration_limit:
subs[-1] = (prev_sub_start, sub_end, prev_sub_content_original + join_sentences_separator + sub_content_original)
if ru_subs:
subs2[-1] = (prev_sub_start, sub_end, prev_sub2_content_original + join_sentences_separator + sub2_content_original)
else:
subs.append((sub_start, sub_end, sub_content_original))
if ru_subs:
subs2.append((sub_start, sub_end, sub2_content_original))
else:
subs.append((sub_start, sub_end, sub_content_original))
if ru_subs:
subs2.append((sub_start, sub_end, sub2_content_original))
return (subs, subs2)
# Unused
def convert_into_sentences_source(en_subs, phrases_duration_limit):
subs = []
for sub in en_subs:
sub_start = sub[0]
sub_end = sub[1]
sub_content_original = sub[2]
sub_content = remove_tags(sub_content_original)
if len(subs) > 0:
prev_sub_start = subs[-1][0]
prev_sub_end = subs[-1][1]
prev_sub_content_original = subs[-1][2]
prev_sub_content = remove_tags(prev_sub_content_original)
if (sub_start - prev_sub_end) <= 2 and (sub_end - prev_sub_start) < phrases_duration_limit and \
((sub_content[0] != '-' and
sub_content[0] != '"' and
sub_content[0] != u'♪' and
(prev_sub_content[-1] != '.' or (sub_content[0:3] == '...' or (prev_sub_content[-3:] == '...' and sub_content[0].islower()))) and
prev_sub_content[-1] != '?' and
prev_sub_content[-1] != '!' and
prev_sub_content[-1] != ']' and
prev_sub_content[-1] != ')' and
prev_sub_content[-1] != u'♪' and
prev_sub_content[-1] != '"' and
(sub_content[0].islower() or sub_content[0].isdigit())) or ((sub_content[0].islower() or sub_content[0] == 'I') and prev_sub_content[-1].islower() and prev_sub_content[-1].isalpha())):
subs[-1] = (prev_sub_start, sub_end, prev_sub_content_original + " " + sub_content_original)
else:
subs.append((sub_start, sub_end, sub_content_original))
else:
subs.append((sub_start, sub_end, sub_content_original))
return subs
def convert_into_phrases(en_subs, ru_subs, time_delta, phrases_duration_limit, is_split_long_phrases, is_gap_phrases):
subs = []
subs2 = []
for i, sub in enumerate(en_subs):
sub_start = sub[0]
sub_end = sub[1]
sub_content = sub[2]
if ru_subs:
sub2_content = ru_subs[i][2]
if not sub_content and not sub2_content:
continue
if is_gap_phrases and ( time_delta > 0 and len(subs) > 0 and (sub_start - prev_sub_end) < time_delta ):
subs[-1].append((sub_start, sub_end, sub_content))
subs2[-1].append((sub_start, sub_end, sub2_content))
else:
subs.append([(sub_start, sub_end, sub_content)])
subs2.append([(sub_start, sub_end, sub2_content)])
prev_sub_end = sub_end
if is_split_long_phrases:
subs = split_long_phrases(subs, phrases_duration_limit)
subs2 = split_long_phrases(subs2, phrases_duration_limit)
subs_with_line_timings = subs
subs = join_lines_within_subs(subs)
subs2 = join_lines_within_subs(subs2)
return (subs, subs2, subs_with_line_timings)
# TODO
def sync_subtitles(en_subs, ru_subs, join_lines_that_end_with):
config = mw.addonManager.getConfig(__name__)
join_lines_separator = config["join lines with"]
join_sentences_separator = config["join sentences with"]
subs = []
for en_start, en_end, en_text in en_subs:
subs.append({
'start': en_start,
'end': en_end,
'en': [en_text],
'ru': []
})
i = 0
pad = 0.3
for ru_start, ru_end, ru_text in ru_subs:
# if (ru_end - ru_start) > 1.5:
# ru_start += 0.25
# ru_end -= 0.25
# elif (ru_end - ru_start) > 1.0:
# ru_start += 0.15
# ru_end -= 0.2
# if (ru_end - ru_start) > 0.5:
if (ru_end - ru_start) > 0.3:
ru_start += 0.2
ru_end -= 0.1
# print('SYNC:', ru_text)
en_size = len(subs)
en_start, en_end, en_text, _ = subs[i].values()
while en_end <= ru_start:
if i+1 >= en_size:
break
i = i+1
en_start, en_end, en_text, _ = subs[i].values()
continue
if i+1 == en_size:
subs[i]['ru'].append(ru_text)
continue
if i == 0:
if ru_end <= en_start + pad:
continue
if ru_end <= en_end + 0.1:
subs[i]['ru'].append(ru_text)
continue
# assert i != 0
assert en_end > ru_start
ru_len = ru_end - ru_start
if ru_len == 0:
ru_len = 0.1
if ru_end <= en_end:
if ru_end <= en_start:
# print('FALSE:', ru_text)
# assert False, ru_text
continue
s_start = max(ru_start, en_start)
s_end = min(ru_end, en_end)
s_len = s_end - s_start
if s_len >= 0.6 or s_len / ru_len >= 0.6:
s_pos = i
else:
if i != 0:
s_pos = i - 1
subs[s_pos]['ru'].append(ru_text)
else:
assert ru_end > en_end
s_start = max(ru_start, en_start)
s_end = min(ru_end, en_end)
s_len = s_end - s_start
if s_len >= 0.4 or s_len / ru_len >= 0.4:
s_pos = i
else:
s_pos = i + 1
if s_pos >= len(subs):
s_pos = i
subs[s_pos]['ru'].append(ru_text)
while True:
if s_pos+1 < len(subs):
en_start, en_end, en_content, _ = subs[s_pos + 1].values()
if ru_end <= en_start:
break
# print('EN CONTENT:', en_content)
s_start = max(ru_start, en_start)
s_end = min(ru_end, en_end)
s_len = s_end - s_start
# print('START:', ru_start, en_start)
# print('END:', ru_end, en_end)
# print(s_len, s_len / ru_len)
if s_len >= 0.4 or s_len / ru_len >= 0.4:
subs[s_pos]['end'] = subs[s_pos+1]['end']
subs[s_pos]['en'].extend(subs[s_pos+1]['en'])
del subs[s_pos+1]
continue
break
ru_subs = []
# print('----------------------------------')
# print(' SUBTITLES ')
# print('----------------------------------')
maxlen = 0
for sub in subs:
start = sub['start']
end = sub['end']
maxlen = max(maxlen, end - start)
content = join_lines_separator.join(sub['ru'])
# content = content.replace('<br>', ' ')
content = re.sub(r'([\.\?\!]) - ', r'\1<br>- ', content)
content = re.sub(r'(<br>\s*<br>)', '<br>', content)
# print('RU:', content)
ru_subs.append([start, end, content])
# en_content = ' '.join(sub['en'])
# print('{:.0f}'.format(end-start))
# print('EN:', en_content)
# print('RU:', content)
# print('TIME MAX:', maxlen)
en_subs = []
for sub in subs:
start = sub['start']
end = sub['end']
content = join_lines_separator.join(sub['en'])
content = re.sub(r'([\.\?\!]) - ', r'\1<br>- ', content)
content = re.sub(r'(<br>\s*<br>)', '<br>', content)
en_subs.append([start, end, content])
return (en_subs, ru_subs)
subs = []
for en_sub in en_subs:
en_sub_start = en_sub[0]
en_sub_end = en_sub[1]
sub_content = []
subs.append((en_sub_start, en_sub_end, sub_content))
for ru_sub in ru_subs:
ru_sub_start = ru_sub[0]
ru_sub_end = ru_sub[1]
ru_sub_content = ru_sub[2]
# ru_sub_start = ru_sub_start + (ru_sub_end - ru_sub_start) / 2
# ru_sub_end = ru_sub_start
ru_sub_start += 0.25
ru_sub_end -= 0.25
if ru_sub_start < en_sub_start:
if ru_sub_end > en_sub_start and ru_sub_end < en_sub_end:
if ru_sub_end - en_sub_start >= 0.35: # TODO
sub_content.append(ru_sub_content)
elif ru_sub_end >= en_sub_end:
sub_content.append(ru_sub_content)
elif ru_sub_start >= en_sub_start and ru_sub_start < en_sub_end:
if ru_sub_end <= en_sub_end:
sub_content.append(ru_sub_content)
elif ru_sub_end > en_sub_end:
if en_sub_end - ru_sub_start >= 0.35: # TODO
sub_content.append(ru_sub_content)
tmp_subs = subs
subs = []
for sub in tmp_subs:
sub_start = sub[0]
sub_end = sub[1]
sub_content = []
for sub_line in sub[2]:
if not sub_content:
sub_content.append(sub_line)
continue
flag = False
for regex in join_lines_that_end_with.split():
if re.search(regex + r"$", sub_content[-1]):
flag = True
break
if flag and not sub_line.startswith('- '):
sub_content.append(join_lines_separator)
else:
sub_content.append(join_sentences_separator)
sub_content.append(sub_line)
sub_content = ''.join(sub_content)
subs.append((sub_start, sub_end, sub_content))
return subs
def add_pad_timings_between_phrases(subs, shift_start, shift_end):
for idx in range(len(subs)):
(start_time, end_time, subtitle) = subs[idx]
subs[idx] = (start_time - shift_start, end_time + shift_end, subtitle)
(start_time, end_time, subtitle) = subs[0]
if start_time < 0:
subs[0] = (0.0, end_time, subtitle)
def add_empty_subtitle(subs):
(start_time, end_time, subtitle) = subs[0][0]
if start_time > 15:
subs.insert(0, [(0.0, start_time, "")])
def change_subtitles_ending_time(subs, duration):
for idx in range(1, len(subs)):
(start_time, end_time, subtitle) = subs[idx]
(prev_start_time, prev_end_time, prev_subtitle) = subs[idx - 1]
if prev_end_time < start_time:
subs[idx - 1] = (prev_start_time, start_time, prev_subtitle)
(start_time, end_time, subtitle) = subs[0]
if start_time > 15:
subs.insert(0, (0.0, start_time, ""))
else:
subs[0] = (0.0, end_time, subtitle)
(start_time, end_time, subtitle) = subs[-1]
subs[-1] = (start_time, duration, subtitle)
def find_glob_files(glob_pattern):
# replace the left square bracket with [[]
glob_pattern = re.sub(r'\[', '[[]', glob_pattern)
# replace the right square bracket with []] but be careful not to replace
# the right square brackets in the left square bracket's 'escape' sequence.
glob_pattern = re.sub(r'(?<!\[)\]', '[]]', glob_pattern)
return glob.glob(glob_pattern)
def guess_srt_file(video_file, mask_list, default_filename):
for mask in mask_list:
glob_pattern = video_file[:-4] + mask
glob_result = find_glob_files(glob_pattern)
if len(glob_result) >= 1:
# print ("Found subtitle: " + glob_result[0]).encode('utf-8')
return glob_result[0]
else:
return default_filename
def getNameForCollectionDirectory(basedir, deck_name):
prefix = format_filename(deck_name)
directory = os.path.join(basedir, prefix + ".media")
return directory
def create_collection_dir(directory):
try:
os.makedirs(directory)
except OSError as ex:
return False
return True
def create_or_clean_collection_dir(directory):
# try:
# if os.path.exists(directory):
# # print "Remove dir " + directory.encode('utf-8')
# shutil.rmtree(directory)
# time.sleep(0.5)
# # print "Create dir " + directory.encode('utf-8')
# os.makedirs(directory)
# except OSError as ex:
# # print ex
# return False
return True
class Model(object):
def __init__(self):
self.video_file = ""
self.audio_id = -1
self.deck_name = ""
self.model_name = "movies2anki (add-on)"
self.default_model_names = ["movies2anki (add-on)", "movies2anki - subs2srs (image)", "movies2anki - subs2srs (video)", "movies2anki - subs2srs (audio)"]
self.en_srt = ""
self.ru_srt = ""
self.out_en_srt_suffix = "out.en.srt"
self.out_ru_srt_suffix = "out.ru.srt"
self.out_en_srt = "out.en.srt"
self.out_ru_srt = "out.ru.srt"
self.encodings = ["utf-8", "cp1251", "utf-16"]
self.sub_encoding = None
self.p = None
self.config = mw.addonManager.getConfig(__name__)
self.load_settings()
def default_settings(self):
self.input_directory = os.path.expanduser("~")
self.output_directory = mw.col.media.dir()
self.time_delta = 0.00
self.is_split_long_phrases = False
self.is_gap_phrases = True
self.phrases_duration_limit = 60
self.video_width = -2
self.video_height = 320
self.screenshot_width = -2
self.screenshot_height = 320
self.shift_start = 0.25
self.shift_end = 0.25
self.mode = "Phrases"
self.recent_deck_names = deque(maxlen = 5)
self.is_write_output_subtitles = False
self.is_write_output_subtitles_for_clips = False
self.is_create_clips_with_softsub = False
self.is_create_clips_with_hardsub = False
self.hardsub_style = "FontName=Arial,FontSize=24,OutlineColour=&H5A000000,BorderStyle=3"
self.is_ignore_sdh_subtitle = True
self.is_add_dir_to_media_path = False
# self.join_lines_that_end_with = r"\.\.\. , → [\u4e00-\u9fef]"
self.join_lines_that_end_with = r"\.\.\. , →"
self.join_questions_with_answers = False
def load_settings(self):
self.default_settings()
if 'video width' in self.config:
self.video_width = self.config["video width"]
if 'video height' in self.config:
self.video_height = self.config["video height"]
if "~input_directory" in self.config:
self.input_directory = self.config["~input_directory"]
if "~model_name" in self.config:
self.model_name = self.config["~model_name"]
if self.model_name == '"movies2anki - subs2srs':
self.model_name = "movies2anki - subs2srs (image)"
# self.output_directory = config.get('main', 'output_directory')
# self.video_width = config.getint('main', 'video_width')
# self.video_height = config.getint('main', 'video_height')
if "~screenshot_width" in self.config:
self.screenshot_width = self.config["~screenshot_width"]
if "~screenshot_height" in self.config:
self.screenshot_height = self.config["~screenshot_height"]
if "~shift_start" in self.config:
self.shift_start = self.config["~shift_start"]
if "~shift_end" in self.config:
self.shift_end = self.config["~shift_end"]
if "~time_delta" in self.config:
self.time_delta = self.config["~time_delta"]
if "~is_split_long_phrases" in self.config:
self.is_split_long_phrases = self.config["~is_split_long_phrases"]
if "~is_gap_phrases" in self.config:
self.is_gap_phrases = self.config["~is_gap_phrases"]
if "~phrases_duration_limit" in self.config:
self.phrases_duration_limit = self.config["~phrases_duration_limit"]
if "~mode" in self.config:
self.mode = self.config["~mode"]
if "~is_write_output_subtitles" in self.config:
self.is_write_output_subtitles = self.config["~is_write_output_subtitles"]
# if "~is_write_output_subtitles_for_clips" in self.config:
# self.is_write_output_subtitles_for_clips = self.config["~is_write_output_subtitles_for_clips"]
# if "~is_create_clips_with_softsub" in self.config:
# self.is_create_clips_with_softsub = self.config["~is_create_clips_with_softsub"]
# if "~is_create_clips_with_hardsub" in self.config:
# self.is_create_clips_with_hardsub = self.config["~is_create_clips_with_hardsub"]
# if "~hardsub_style" in self.config:
# self.hardsub_style = self.config["~hardsub_style"]
if "~is_ignore_sdh_subtitle" in self.config:
self.is_ignore_sdh_subtitle = self.config["~is_ignore_sdh_subtitle"]
# if "~is_add_dir_to_media_path" in self.config:
# self.is_add_dir_to_media_path = self.config["~is_add_dir_to_media_path"]
if "~join_lines_that_end_with" in self.config:
self.join_lines_that_end_with = self.config["~join_lines_that_end_with"]
if "~join_questions_with_answers" in self.config:
self.join_questions_with_answers = self.config["~join_questions_with_answers"]
if "~recent_deck_names" in self.config:
value = [e.strip() for e in self.config["~recent_deck_names"].split(',')]
if len(value) != 0:
self.recent_deck_names.extendleft(value)
def save_settings(self):
self.config['~input_directory'] = self.input_directory
self.config["~model_name"] = self.model_name
# self.config['~output_directory'] = self.output_directory.encode('utf-8')
# self.config['~video_width'] = str(self.video_width)
# self.config['~video_height'] = str(self.video_height)
self.config['~screenshot_width'] = self.screenshot_width
self.config['~screenshot_height'] = self.screenshot_height
self.config['~shift_start'] = self.shift_start
self.config['~shift_end'] = self.shift_end
self.config['~time_delta'] = self.time_delta
self.config['~is_split_long_phrases'] = self.is_split_long_phrases
self.config['~is_gap_phrases'] = self.is_gap_phrases
self.config['~phrases_duration_limit'] = self.phrases_duration_limit
self.config['~mode'] = self.mode
self.config['~is_write_output_subtitles'] = self.is_write_output_subtitles
# self.config['~is_write_output_subtitles_for_clips'] = str(self.is_write_output_subtitles_for_clips)
# self.config['~is_create_clips_with_softsub'] = str(self.is_create_clips_with_softsub)
# self.config['~is_create_clips_with_hardsub'] = str(self.is_create_clips_with_hardsub)
# self.config['~hardsub_style'] = self.hardsub_style.encode('utf-8')
self.config['~is_ignore_sdh_subtitle'] = self.is_ignore_sdh_subtitle
# self.config['~is_add_dir_to_media_path'] = str(self.is_add_dir_to_media_path)
self.config['~join_lines_that_end_with'] = self.join_lines_that_end_with
self.config['~join_questions_with_answers'] = self.join_questions_with_answers
self.config['~recent_deck_names'] = ",".join(reversed(self.recent_deck_names))
mw.addonManager.writeConfig(__name__, self.config)
def guess_encoding(self, file_content):
if file_content[:3] == b'\xef\xbb\xbf': # with bom
file_content = file_content[3:]
return file_content, 'utf-8'
try:
# https://github.com/chardet/chardet/pull/109
import chardet_with_utf16_fix
enc = chardet_with_utf16_fix.detect(file_content)['encoding']
return file_content, enc
except:
pass
return file_content, None
def convert_to_unicode(self, file_content):
file_content, enc = self.guess_encoding(file_content)
if enc: