forked from kelciour/movies2anki
-
Notifications
You must be signed in to change notification settings - Fork 0
/
movies2anki.py
1669 lines (1263 loc) · 60.4 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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import glob
import os
import re
import shutil
import string
import sys
import time
from collections import deque
from ConfigParser import SafeConfigParser
from PyQt4 import QtCore, QtGui
from subprocess import call
from subprocess import check_output
from subprocess import Popen
import subprocess
import os.path
# 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 = time.split(',')
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]
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*\[[^\]]*\])*$"
reg_exp_round_braces_with_tags = r"^(?:- )?(?:<[^>]+>)*\([^)]*\)(\s*\([^)]*\))*(?:<[^>]+>)*$"
reg_exp_round_braces_with_tags_multiline = r"^(\([^)]*\)(\s*\([^)]*\))*|\s|-|(?:<[^>]+>)*)*$"
if re.match(reg_exp_round_braces, sub):
return False
elif re.match(reg_exp_square_braces, sub):
return False
elif re.match(reg_exp_round_braces_with_tags, sub):
return False
elif re.match(reg_exp_round_braces_with_tags_multiline, sub):
return False
return True
def read_subtitles(content, is_ignore_SDH):
en_subs = []
for sub in content.strip().split('\n\n'):
sub_chunks = sub.split('\n')
if (len(sub_chunks) >= 3):
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())
sub_content = " ".join(sub_chunks[2:]).replace("\t", " ")
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:
print "Empty subtitle: %s" % repr(sub)
else:
print "Ignore subtitle: %s" % repr(sub)
return en_subs
# Формат субтитров
# [(start_time, end_time, subtitle), (), ...], [(...)], ...
def join_lines_within_subs(subs):
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 = ""
for s in sub:
sub_content = sub_content + " " + s[2]
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 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]
pos = int((s_end - sub_start) / sub_chunks_limit)
sub_splitted[pos].append((s_start, s_end, s_content))
for s in sub_splitted:
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):
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())):
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, time_delta, phrases_duration_limit, is_split_long_phrases):
subs = []
for sub in en_subs:
sub_start = sub[0]
sub_end = sub[1]
sub_content = sub[2]
if ( len(subs) > 0 and (sub_start - prev_sub_end) <= time_delta ):
subs[-1].append((sub_start, sub_end, sub_content))
else:
subs.append([(sub_start, sub_end, sub_content)])
prev_sub_end = sub_end
if is_split_long_phrases:
subs = split_long_phrases(subs, phrases_duration_limit)
subs_with_line_timings = subs
subs = join_lines_within_subs(subs)
return (subs, subs_with_line_timings)
def sync_subtitles(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]
if ru_sub_start < en_sub_start:
if ru_sub_end > en_sub_start and ru_sub_end < en_sub_end:
sub_content.append(ru_sub_content) # TODO
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:
sub_content.append(ru_sub_content) # TODO
tmp_subs = subs
subs = []
for sub in tmp_subs:
sub_start = sub[0]
sub_end = sub[1]
sub_content = " ".join(sub[2])
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 change_subtitles_ending_time(subs, subs_with_line_timings, is_separate_fragments_without_subtitles, time_delta):
shift = 0
subs_in = list(subs)
for idx in range(1, len(subs_in)):
(start_time, end_time, subtitle) = subs_in[idx]
(prev_start_time, prev_end_time, prev_subtitle) = subs_in[idx - 1]
if prev_end_time < start_time:
if is_separate_fragments_without_subtitles and (start_time - prev_end_time) > time_delta * 2:
subs.insert(idx + shift, (prev_end_time, start_time, ""))
if subs_with_line_timings is not None:
subs_with_line_timings.insert(idx + shift, [(prev_end_time, start_time, "")])
shift = shift + 1
else:
subs[idx + shift - 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, ""))
if subs_with_line_timings is not None:
subs_with_line_timings.insert(0, [(0.0, start_time, "")])
else:
subs[0] = (0.0, end_time, subtitle)
(start_time, end_time, subtitle) = subs[-1]
if is_separate_fragments_without_subtitles:
subs.append((end_time, end_time + 600, ""))
if subs_with_line_timings is not None:
subs_with_line_timings.append([(end_time, end_time + 600, "")])
else:
subs[-1] = (start_time, end_time + 600, 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 format_filename(deck_name):
"""
Returns the given string converted to a string that can be used for a clean
filename. Specifically, leading and trailing spaces are removed; other
spaces are converted to underscores; and anything that is not a unicode
alphanumeric, dash, underscore, or dot, is removed.
>>> get_valid_filename("john's portrait in 2004.jpg")
'johns_portrait_in_2004.jpg'
"""
s = deck_name.strip().replace(' ', '_')
return re.sub(r'(?u)[^-\w.]', '', s)
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.config_file_name = 'config.ini'
self.video_file = ""
self.audio_id = 0
self.deck_name = ""
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"]
self.sub_encoding = None
self.p = None
self.load_settings()
def default_settings(self):
self.input_directory = ""
self.output_directory = os.getcwd()
self.time_delta = 1.75
self.is_split_long_phrases = False
self.phrases_duration_limit = 60
self.video_width = 480
self.video_height = -2
self.shift_start = 0.75
self.shift_end = 0.75
self.mode = "Movie"
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.is_separate_fragments_without_subtitles = False
def load_settings(self):
self.default_settings()
if not os.path.isfile(self.config_file_name):
return
config = SafeConfigParser()
config.read(self.config_file_name)
self.input_directory = config.get('main', 'input_directory').decode('utf-8')
self.output_directory = config.get('main', 'output_directory').decode('utf-8')
self.video_width = config.getint('main', 'video_width')
self.video_height = config.getint('main', 'video_height')
self.shift_start = config.getfloat('main', 'pad_start')
self.shift_end = config.getfloat('main', 'pad_end')
self.time_delta = config.getfloat('main', 'gap_between_phrases')
self.is_split_long_phrases = config.getboolean('main', 'is_split_long_phrases')
self.phrases_duration_limit = config.getint('main', 'phrases_duration_limit')
self.mode = config.get('main', 'mode')
self.is_write_output_subtitles = config.getboolean('main', 'is_write_output_subtitles')
self.is_write_output_subtitles_for_clips = config.getboolean('main', 'is_write_output_subtitles_for_clips')
self.is_create_clips_with_softsub = config.getboolean('main', 'is_create_clips_with_softsub')
self.is_create_clips_with_hardsub = config.getboolean('main', 'is_create_clips_with_hardsub')
self.hardsub_style = config.get('main', 'hardsub_style')
self.is_ignore_sdh_subtitle = config.getboolean('main', 'is_ignore_sdh_subtitle')
self.is_add_dir_to_media_path = config.getboolean('main', 'is_add_dir_to_media_path')
self.is_separate_fragments_without_subtitles = config.getboolean('main', 'is_separate_fragments_without_subtitles')
value = [e.strip() for e in config.get('main', 'recent_deck_names').decode('utf-8').split(',')]
if len(value) != 0:
self.recent_deck_names.extendleft(value)
def save_settings(self):
config = SafeConfigParser()
config.add_section('main')
config.set('main', 'input_directory', self.input_directory.encode('utf-8'))
config.set('main', 'output_directory', self.output_directory.encode('utf-8'))
config.set('main', 'video_width', str(self.video_width))
config.set('main', 'video_height', str(self.video_height))
config.set('main', 'pad_start', str(self.shift_start))
config.set('main', 'pad_end', str(self.shift_end))
config.set('main', 'gap_between_phrases', str(self.time_delta))
config.set('main', 'is_split_long_phrases', str(self.is_split_long_phrases))
config.set('main', 'phrases_duration_limit', str(self.phrases_duration_limit))
config.set('main', 'mode', self.mode)
config.set('main', 'is_write_output_subtitles', str(self.is_write_output_subtitles))
config.set('main', 'is_write_output_subtitles_for_clips', str(self.is_write_output_subtitles_for_clips))
config.set('main', 'is_create_clips_with_softsub', str(self.is_create_clips_with_softsub))
config.set('main', 'is_create_clips_with_hardsub', str(self.is_create_clips_with_hardsub))
config.set('main', 'hardsub_style', self.hardsub_style.encode('utf-8'))
config.set('main', 'is_ignore_sdh_subtitle', str(self.is_ignore_sdh_subtitle))
config.set('main', 'is_add_dir_to_media_path', str(self.is_add_dir_to_media_path))
config.set('main', 'is_separate_fragments_without_subtitles', str(self.is_separate_fragments_without_subtitles))
config.set('main', 'recent_deck_names', ",".join(reversed(self.recent_deck_names)).encode('utf-8'))
with open(self.config_file_name, 'w') as f:
config.write(f)
def convert_to_unicode(self, file_content):
for enc in self.encodings:
try:
content = file_content.decode(enc)
self.sub_encoding = enc
return content
except UnicodeDecodeError:
pass
self.sub_encoding = None
return file_content
def load_subtitle(self, filename, is_ignore_SDH):
if len(filename) == 0:
return []
file_content = open(filename, 'rU').read()
if file_content[:3]=='\xef\xbb\xbf': # with bom
file_content = file_content[3:]
## Оставляем только одну пустую строку между субтитрами
file_content = fix_empty_lines(file_content)
## Конвертируем субтитры в Unicode
file_content = self.convert_to_unicode(file_content)
## Читаем субтитры
return read_subtitles(file_content, is_ignore_SDH)
def encode_str(self, enc_str):
if self.sub_encoding == None:
return enc_str
return enc_str.encode('utf-8')
def write_subtitles(self, file_name, subs):
f_out = open(file_name, 'w')
for idx in range(len(subs)):
f_out.write(self.encode_str(str(idx+1) + "\n"))
f_out.write(self.encode_str(seconds_to_srt_time(subs[idx][0]) + " --> " + seconds_to_srt_time(subs[idx][1]) + "\n"))
f_out.write(self.encode_str(subs[idx][2] + "\n"))
f_out.write(self.encode_str("\n"))
f_out.close()
def write_tsv_file(self, deck_name, en_subs, ru_subs, directory):
prefix = format_filename(deck_name)
filename = os.path.join(directory, prefix + ".tsv")
f_out = open(filename, 'w')
ffmpeg_split_timestamps = []
for idx in range(len(en_subs)):
start_time = seconds_to_tsv_time(en_subs[idx][0])
end_time = seconds_to_tsv_time(en_subs[idx][1])
en_sub = en_subs[idx][2]
en_sub = re.sub('\n', ' ', en_sub)
en_sub = escape_double_quotes(en_sub)
ru_sub = ru_subs[idx][2]
ru_sub = re.sub('\n', ' ', ru_sub)
ru_sub = escape_double_quotes(ru_sub)
tag = prefix
sequence = str(idx + 1).zfill(3) + "_" + start_time
filename_suffix = ""
if self.is_create_clips_with_hardsub:
filename_suffix = ".sub"
sound = prefix + "_" + start_time + "-" + end_time + ".mp3"
video = prefix + "_" + start_time + "-" + end_time + filename_suffix + ".mp4"
if self.is_add_dir_to_media_path:
sound = prefix + ".media/" + sound
video = prefix + ".media/" + video
f_out.write(self.encode_str(tag + "\t" + sequence + "\t[sound:" + sound + "]\t[sound:" + video + "]\t"))
f_out.write(self.encode_str(en_sub))
f_out.write(self.encode_str("\t"))
f_out.write(self.encode_str(ru_sub))
f_out.write(self.encode_str('\n'))
ffmpeg_split_timestamps.append((prefix + "_" + start_time + "-" + end_time,
seconds_to_ffmpeg_time(en_subs[idx][0]),
seconds_to_ffmpeg_time(en_subs[idx][1])))
f_out.close()
return ffmpeg_split_timestamps
def create_subtitles(self):
print "--------------------------"
print "Video file: %s" % self.video_file.encode('utf-8')
print "Audio id: %s" % self.audio_id
print "English subtitles: %s" % self.en_srt.encode('utf-8')
print "Russian subtitles: %s" % self.ru_srt.encode('utf-8')
print "English subtitles output: %s" % self.out_en_srt.encode('utf-8')
print "Russian subtitles output: %s" % self.out_ru_srt.encode('utf-8')
print "Write output subtitles: %s" % self.is_write_output_subtitles
print "Write output subtitles for clips: %s" % self.is_write_output_subtitles_for_clips
print "Create clips with softsub: %s" % self.is_create_clips_with_softsub
print "Create clips with hardsub: %s" % self.is_create_clips_with_hardsub
print "Style for hardcoded subtitles: %s" % self.hardsub_style
print "Separate fragments without subtitles in Movie mode: %s" % self.is_separate_fragments_without_subtitles
print "Ignore SDH subtitles: %s" % self.is_ignore_sdh_subtitle
print "Output Directory: %s" % self.output_directory.encode('utf-8')
print "Video width: %s" % self.video_width
print "Video height: %s" % self.video_height
print "Pad start: %s" % self.shift_start
print "Pad end: %s" % self.shift_end
print "Gap between phrases: %s" % self.time_delta
print "Split Long Phrases: %s" % self.is_split_long_phrases
print "Max length phrases: %s" % self.phrases_duration_limit
print "Mode: %s" % self.mode
print "Deck name: %s" % self.deck_name.encode('utf-8')
print "--------------------------"
self.is_subtitles_created = False
# Загружаем английские субтитры в формате [(start_time, end_time, subtitle), (...), ...]
print "Loading English subtitles..."
en_subs = self.load_subtitle(self.en_srt, self.is_ignore_sdh_subtitle)
print "Encoding: %s" % self.sub_encoding
print "English subtitles: %s" % len(en_subs)
# Разбиваем субтитры на предложения
self.en_subs_sentences = convert_into_sentences(en_subs, self.phrases_duration_limit)
print "English sentences: %s" % len(self.en_subs_sentences)
# Разбиваем субтитры на фразы
self.en_subs_phrases, self.subs_with_line_timings = convert_into_phrases(self.en_subs_sentences, self.time_delta, self.phrases_duration_limit, self.is_split_long_phrases)
print "English phrases: %s" % len(self.en_subs_phrases)
# Загружаем русские субтитры в формате [(start_time, end_time, subtitle), (...), ...]
print "Loading Russian subtitles..."
ru_subs = self.load_subtitle(self.ru_srt, self.is_ignore_sdh_subtitle)
print "Encoding: %s" % self.sub_encoding
print "Russian subtitles: %s" % len(ru_subs)
# Для preview диалога
self.num_en_subs = len(en_subs)
self.num_ru_subs = len(ru_subs)
self.num_phrases = len(self.en_subs_phrases)
# Синхронизируем русские субтитры с получившимися английскими субтитрами
print "Syncing Russian subtitles with English phrases..."
self.ru_subs_phrases = sync_subtitles(self.en_subs_phrases, ru_subs)
# Добавляем смещения к каждой фразе
print "Adding Pad Timings between English phrases..."
add_pad_timings_between_phrases(self.en_subs_phrases, self.shift_start, self.shift_end)
print "Adding Pad Timings between Russian phrases..."
add_pad_timings_between_phrases(self.ru_subs_phrases, self.shift_start, self.shift_end)
if self.mode == "Movie":
# Меняем длительность фраз в английских субтитрах
print "Changing duration English subtitles..."
change_subtitles_ending_time(self.en_subs_phrases, self.subs_with_line_timings, self.is_separate_fragments_without_subtitles, self.time_delta)
# Меняем длительность фраз в русских субтитрах
print "Changing duration Russian subtitles..."
change_subtitles_ending_time(self.ru_subs_phrases, None, self.is_separate_fragments_without_subtitles, self.time_delta)
self.is_subtitles_created = True
def write_output_subtitles(self):
# Записываем английские субтитры
print "Writing English subtitles..."
self.write_subtitles(self.out_en_srt, self.en_subs_phrases)
# Записываем русские субтитры
print "Writing Russian subtitles..."
self.write_subtitles(self.out_ru_srt, self.ru_subs_phrases)
def create_tsv_file(self):
# Формируем tsv файл для импорта в Anki
print "Writing tsv file..."
self.ffmpeg_split_timestamps.append(self.write_tsv_file(self.deck_name, self.en_subs_phrases, self.ru_subs_phrases, self.output_directory))
def getTimeDelta(self):
return self.time_delta
def getVideoWidth(self):
return self.video_width
def getVideoHeight(self):
return self.video_height
def getShiftStart(self):
return self.shift_start * 1000
def getShiftEnd(self):
return self.shift_end * 1000
def setShiftStart(self, value):
self.shift_start = value / 1000.0
def setShiftEnd(self, value):
self.shift_end = value / 1000.0
def getPhrasesDurationLimit(self):
return self.phrases_duration_limit
def getMode(self):
return self.mode
class VideoWorker(QtCore.QThread):
updateProgress = QtCore.pyqtSignal(int)
updateProgressWindowTitle = QtCore.pyqtSignal(str)
updateProgressText = QtCore.pyqtSignal(str)
jobFinished = QtCore.pyqtSignal(float)
batchJobsFinished = QtCore.pyqtSignal()
errorRaised = QtCore.pyqtSignal(str)
def __init__(self, data):
QtCore.QThread.__init__(self)
self.model = data
self.canceled = False
def cancel(self):
self.canceled = True
def run(self):
self.video_resolution = str(self.model.video_width) + ":" + str(self.model.video_height)
time_start = time.time()
num_files_completed = 0
num_files = sum(len(files) for files in self.model.ffmpeg_split_timestamps)
for idx in range(len(self.model.ffmpeg_split_timestamps)):
if self.canceled:
break
if self.model.batch_mode:
ffmpeg_split_timestamps = self.model.ffmpeg_split_timestamps[idx]
video_file, en_srt, ru_srt, deck_name = self.model.jobs[idx]
self.model.video_file = video_file
self.model.en_srt = en_srt
self.model.ru_srt = ru_srt
self.model.deck_name = deck_name
collection_dir = getNameForCollectionDirectory(self.model.output_directory, self.model.deck_name)
ret = create_collection_dir(collection_dir)
if ret == False:
self.errorRaised.emit("Can't create media directory.")
self.canceled = True
break
self.updateProgressWindowTitle.emit("Generate Video & Audio Clips [%s/%s]" % (idx + 1, len(self.model.jobs)))
else:
ffmpeg_split_timestamps = self.model.ffmpeg_split_timestamps[idx]
prefix = format_filename(self.model.deck_name)
for i in range(len(ffmpeg_split_timestamps)):
if self.canceled:
break
chunk = ffmpeg_split_timestamps[i]
self.updateProgress.emit((num_files_completed * 1.0 / num_files) * 100)
filename = self.model.output_directory + os.sep + prefix + ".media" + os.sep + chunk[0]
ss = chunk[1]
to = chunk[2]
t = tsv_time_to_seconds(to) - tsv_time_to_seconds(ss)
af_d = 0.25
af_st = 0
af_to = t - af_d
af_params = "afade=t=in:st=%s:d=%s,afade=t=out:st=%s:d=%s" % (af_st, af_d, af_to, af_d)
print ss
self.updateProgressText.emit(ss)
# clip subtitles
if self.model.is_write_output_subtitles_for_clips or self.model.is_create_clips_with_softsub or self.model.is_create_clips_with_hardsub:
with open(filename + ".srt", 'w') as f_sub:
clip_subs = self.model.subs_with_line_timings[i]
clip_sub_shift = tsv_time_to_seconds(ss)
for sub_id in range(len(clip_subs)):
f_sub.write(self.model.encode_str(str(sub_id+1) + "\n"))
f_sub.write(self.model.encode_str(seconds_to_srt_time(clip_subs[sub_id][0] - clip_sub_shift) + " --> " + seconds_to_srt_time(clip_subs[sub_id][1] - clip_sub_shift) + "\n"))
f_sub.write(self.model.encode_str(clip_subs[sub_id][2] + "\n"))
f_sub.write(self.model.encode_str("\n"))
vf = '"'
vf += "scale=" + self.video_resolution
if self.model.is_create_clips_with_hardsub:
srt_style = self.model.hardsub_style
srt_filename = os.path.abspath(filename + ".srt")
if srt_filename[1] == ":": # Windows
srt_filename = srt_filename.replace("\\", "/")
srt_filename = srt_filename.replace(":", "\\\\:")
vf += ",subtitles=" + srt_filename + ":force_style='" + srt_style + "'"
vf += '"'
softsubs_options = ""
softsubs_map = ""
if self.model.is_create_clips_with_softsub:
softsubs_options = "-i" + " " + '"' + filename + ".srt" + '"' + " " + "-c:s mov_text"
softsubs_map = "-map 1:0"
filename_suffix = ""
if self.model.is_create_clips_with_hardsub:
filename_suffix = ".sub"
cmd = " ".join(["ffmpeg", "-ss", ss, "-i", '"' + self.model.video_file + '"', softsubs_options, "-strict", "-2", "-loglevel", "quiet", "-t", str(t), "-af", af_params, "-map", "0:v:0", "-map", "0:a:" + str(self.model.audio_id), softsubs_map, "-c:v", "libx264", "-vf", vf, "-c:a", "aac", "-ac", "2", '"' + filename + filename_suffix + ".mp4" + '"'])
print cmd.encode('utf-8')
self.model.p = Popen(cmd.encode(sys.getfilesystemencoding()), shell=True, **subprocess_args())
self.model.p.wait()
if (self.model.is_create_clips_with_hardsub or self.model.is_create_clips_with_softsub) and not self.model.is_write_output_subtitles_for_clips:
os.remove(filename + ".srt")
if self.canceled:
break
cmd = " ".join(["ffmpeg", "-ss", ss, "-i", '"' + self.model.video_file + '"', "-loglevel", "quiet", "-t", str(t), "-af", af_params, "-map", "0:a:" + str(self.model.audio_id), '"' + filename + ".mp3" + '"'])
print cmd.encode('utf-8')
self.model.p = Popen(cmd.encode(sys.getfilesystemencoding()), shell=True, **subprocess_args())
self.model.p.wait()
num_files_completed += 1
time_end = time.time()
time_diff = (time_end - time_start)
if not self.canceled:
self.updateProgress.emit(100)
self.jobFinished.emit(time_diff)
if self.canceled:
print "Canceled"
else:
print "Done"
if self.model.batch_mode:
self.batchJobsFinished.emit()
class JobsInfo(QtGui.QDialog):
def __init__(self, message, parent=None):
super(JobsInfo, self).__init__(parent)
self.initUI(message)
def initUI(self, message):
okButton = QtGui.QPushButton("OK")
cancelButton = QtGui.QPushButton("Cancel")
okButton.clicked.connect(self.ok)
cancelButton.clicked.connect(self.cancel)
reviewEdit = QtGui.QTextEdit()
reviewEdit.setReadOnly(True)
reviewEdit.setText(message)
grid = QtGui.QGridLayout()
grid.setSpacing(10)
grid.addWidget(reviewEdit, 1, 1, 1, 3)
grid.addWidget(okButton, 2, 2)
grid.addWidget(cancelButton, 2, 3)
grid.setColumnStretch(1,1)
self.setLayout(grid)
self.setWindowTitle('movies2anki [Batch Processing]')
self.setModal(True)
self.setMinimumSize(400, 300)
def ok(self):
self.done(1)
def cancel(self):
self.done(0)
class Example(QtGui.QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.model = Model()
self.audio_streams = []
self.directory = self.model.input_directory
self.initUI()
def initUI(self):
w = QtGui.QWidget()
vbox = QtGui.QVBoxLayout()
# ---------------------------------------------------
filesGroup = self.createFilesGroup()
vbox.addWidget(filesGroup)
# ---------------------------------------------------
outputGroup = self.createOutputGroup()
vbox.addWidget(outputGroup)
# ---------------------------------------------------
optionsGroup = self.createOptionsGroup()
vbox.addWidget(optionsGroup)
# ---------------------------------------------------
bottomGroup = self.createBottomGroup()
vbox.addLayout(bottomGroup)
# ---------------------------------------------------
self.videoButton.clicked.connect(self.showVideoFileDialog)
self.audioIdComboBox.currentIndexChanged.connect(self.setAudioId)
self.subsEngButton.clicked.connect(self.showSubsEngFileDialog)
self.subsRusButton.clicked.connect(self.showSubsRusFileDialog)
self.outDirButton.clicked.connect(self.showOutDirectoryDialog)
self.deckComboBox.editTextChanged.connect(self.setDeckName)
self.previewButton.clicked.connect(self.preview)
self.startButton.clicked.connect(self.start)
self.timeSpinBox.valueChanged.connect(self.setTimeDelta)
self.splitPhrasesSpinBox.valueChanged.connect(self.setPhrasesDurationLimit)
self.widthSpinBox.valueChanged.connect(self.setVideoWidth)
self.heightSpinBox.valueChanged.connect(self.setVideoHeight)
self.startSpinBox.valueChanged.connect(self.setShiftStart)
self.endSpinBox.valueChanged.connect(self.setShiftEnd)
self.movieRadioButton.toggled.connect(self.setMovieMode)
self.phrasesRadioButton.toggled.connect(self.setPhrasesMode)
self.videoEdit.textChanged.connect(self.changeVideoFile)
self.subsEngEdit.textChanged.connect(self.changeEngSubs)
self.subsRusEdit.textChanged.connect(self.changeRusSubs)
self.outDirEdit.textChanged.connect(self.changeOutDir)
# ---------------------------------------------------
vbox.addStretch(1)
w.setLayout(vbox)
self.setCentralWidget(w)
self.adjustSize()
self.setWindowTitle('movies2anki')
self.show()
def closeEvent(self, event):
# save settings
self.model.save_settings()
QtGui.QMainWindow.closeEvent(self, event)
def showVideoFileDialog(self):
fname = unicode(QtGui.QFileDialog.getOpenFileName(directory = self.directory, filter = "Video Files (*.avi *.mkv *.mp4 *.ts);;All files (*.*)"))
self.videoEdit.setText(fname)
def showSubsEngFileDialog(self):
fname = unicode(QtGui.QFileDialog.getOpenFileName(directory = self.directory, filter = "Subtitle Files (*.srt)"))
self.subsEngEdit.setText(fname)
self.directory = os.path.dirname(fname)
def showSubsRusFileDialog(self):
fname = unicode(QtGui.QFileDialog.getOpenFileName(directory = self.directory, filter = "Subtitle Files (*.srt)"))
self.subsRusEdit.setText(fname)