-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsynchronisation.py
More file actions
2271 lines (2012 loc) · 116 KB
/
synchronisation.py
File metadata and controls
2271 lines (2012 loc) · 116 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
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
import os, re, subprocess, tempfile, shutil, time, sys, stat, datetime, threading
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
def is_running_in_docker():
"""Check if running inside a Docker container."""
try:
if os.path.exists('/.dockerenv'):
return True
with open('/proc/1/cgroup', 'r') as f:
return 'docker' in f.read()
except:
return False
def get_skipped_movies_from_config():
"""Read skipped movies from config file."""
CONFIG_PATH = Path(__file__).parent.resolve() / '.config'
if not CONFIG_PATH.exists():
return {}
lines = CONFIG_PATH.read_text(encoding='utf-8').splitlines()
in_skipped = False
skipped = {}
for line in lines:
if line.strip() == '[skipped_movies]':
in_skipped = True
continue
if in_skipped:
if line.strip().startswith('['):
break
if line.strip():
entry = line.strip()
if '[' in entry and entry.endswith(']'):
parts = entry.rsplit(' [', 1)
if len(parts) == 2:
movie_path = parts[0]
lang_part = parts[1][:-1]
languages = {lang.strip().lower() for lang in lang_part.split(',') if lang.strip()}
skipped[movie_path] = languages
return skipped
def add_skipped_movie_language_to_config(movie_path: Path, language: str):
"""Add a movie-language combination to skipped_movies in config."""
CONFIG_PATH = Path(__file__).parent.resolve() / '.config'
skipped_movies = get_skipped_movies_from_config()
movie_key = str(movie_path.resolve())
if movie_key in skipped_movies:
skipped_movies[movie_key].add(language.lower())
else:
skipped_movies[movie_key] = {language.lower()}
skipped_entries = set()
for path, languages in skipped_movies.items():
if languages:
lang_str = ','.join(sorted(languages)).upper()
skipped_entries.add(f"{path} [{lang_str}]")
# Write to config
write_runtime_blocks_to_config_sync(skipped_entries=skipped_entries)
def write_runtime_blocks_to_config_sync(token=None, skipped_entries=None):
"""Write runtime configuration blocks to config file."""
CONFIG_PATH = Path(__file__).parent.resolve() / '.config'
SEP = '--'
TOKEN_COMMENT = 'JWT token for OpenSubtitles API. Acquisition.py will update this automatically.'
TOKEN_TAG = '[token]'
SKIPPED_COMMENT = 'List of movies that were skipped manually. Remove an entry below in order to make it appear again.'
SKIPPED_TAG = '[skipped_movies]'
RUNTIME_TAG = '[RUNTIME]'
if not CONFIG_PATH.exists():
lines = []
else:
lines = CONFIG_PATH.read_text(encoding='utf-8').splitlines()
out = []
for line in lines:
out.append(line)
if line.strip().lower() == RUNTIME_TAG.lower():
break
runtime_blocks = []
runtime_blocks.append('')
runtime_blocks.append(SEP)
runtime_blocks.append(TOKEN_COMMENT)
runtime_blocks.append(TOKEN_TAG)
if token is None:
# Try to get existing token from config
for line in lines:
if line.strip() and not line.startswith('[') and not line.startswith('--') and 'JWT' not in line:
idx = lines.index(line)
if idx > 0 and '[token]' in lines[idx-1]:
token = line.strip()
break
if token:
runtime_blocks.append(token)
else:
runtime_blocks.append('')
if skipped_entries is None:
skipped_movies_dict = get_skipped_movies_from_config()
skipped_entries_set = set()
for path, languages in skipped_movies_dict.items():
if languages:
lang_str = ','.join(sorted(languages)).upper()
skipped_entries_set.add(f"{path} [{lang_str}]")
skipped_entries = skipped_entries_set
runtime_blocks.append(SEP)
runtime_blocks.append(SKIPPED_COMMENT)
runtime_blocks.append(SKIPPED_TAG)
for entry in sorted(skipped_entries):
runtime_blocks.append(entry)
out = [line.rstrip() for line in out]
out.extend(runtime_blocks)
CONFIG_PATH.write_text('\n'.join(out), encoding='utf-8')
def calculate_subtitle_offset(original_path, synchronized_path):
"""Calculate time offset between original and synchronized subtitle files."""
try:
def parse_srt_first_timestamp(file_path):
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
lines = f.readlines()
for line in lines:
if '-->' in line:
start_time = line.split('-->')[0].strip()
time_parts = start_time.split(':')
if len(time_parts) == 3:
hours = int(time_parts[0])
minutes = int(time_parts[1])
seconds_ms = time_parts[2].split(',')
seconds = int(seconds_ms[0])
milliseconds = int(seconds_ms[1]) if len(seconds_ms) > 1 else 0
total_seconds = hours * 3600 + minutes * 60 + seconds + milliseconds / 1000.0
return total_seconds
return 0.0
if not os.path.exists(original_path) or not os.path.exists(synchronized_path):
return 0.0
original_time = parse_srt_first_timestamp(original_path)
synchronized_time = parse_srt_first_timestamp(synchronized_path)
offset = abs(original_time - synchronized_time)
return offset
except Exception as e:
print_and_log(f"{sync_tag()} {Fore.YELLOW}Warning: Could not calculate subtitle offset: {str(e)}{Style.RESET_ALL}", log_only=True)
return 0.0
def synchronize_subtitle_with_ffsubsync(video_path, subtitle_path, output_path):
"""Synchronize subtitle file with video using ffsubsync and return success status with offset."""
try:
if not os.path.exists(video_path):
print_and_log(f"{sync_tag()} {Fore.RED}Video file not found: {video_path}{Style.RESET_ALL}")
return False, 0.0
if not os.path.exists(subtitle_path):
print_and_log(f"{sync_tag()} {Fore.RED}Subtitle file not found: {subtitle_path}{Style.RESET_ALL}")
return False, 0.0
print_and_log(f"{sync_tag()} {Fore.CYAN}Synchronizing {os.path.basename(subtitle_path)} with video...{Style.RESET_ALL}")
cmd = [
'ffsubsync', video_path,
'-i', subtitle_path,
'-o', output_path,
]
try:
result = subprocess.run(cmd, timeout=600)
if result.returncode == 0 and os.path.exists(output_path):
offset_seconds = calculate_subtitle_offset(subtitle_path, output_path)
print_and_log(f"{sync_tag()} {Fore.GREEN}Synchronization successful! Offset: {offset_seconds:.3f}s{Style.RESET_ALL}")
return True, offset_seconds
else:
print_and_log(f"{sync_tag()} {Fore.RED}FFSubSync failed with return code {result.returncode}{Style.RESET_ALL}")
return False, 0.0
except Exception as proc_error:
print_and_log(f"{sync_tag()} {Fore.RED}Process error during synchronization: {str(proc_error)}{Style.RESET_ALL}")
return False, 0.0
except subprocess.TimeoutExpired:
print_and_log(f"{sync_tag()} {Fore.RED}FFSubSync timed out after 10 minutes{Style.RESET_ALL}")
return False, 0.0
except Exception as e:
print_and_log(f"{sync_tag()} {Fore.RED}Error during synchronization: {str(e)}{Style.RESET_ALL}")
return False, 0.0
def check_required_packages():
"""Check if all required packages are installed and show install instructions if missing."""
required_packages = ["colorama", "platformdirs", "langdetect"]
missing = []
for package in required_packages:
try:
__import__(package)
except ImportError:
missing.append(package)
if missing:
print("\n" + "="*60)
print(" SUBSERVIENT SYNCHRONISATION - PACKAGE REQUIREMENTS ERROR")
print("="*60)
print("\nThe following required packages are missing:")
for pkg in missing:
print(f" - {pkg}")
print(f"\nTo resolve this issue:")
print(f" 1. Navigate to your main Subservient folder")
print(f" 2. Run subordinate.py so that it automatically installs the required packages.")
print(f" 3. If 2 is not happening, choose option '4' to install & verify requirements")
print(f" 4. After installation, try running synchronisation.py again")
print(f"\nIf you don't have subordinate.py, please download the complete")
print(f"Subservient package from the official source.")
print("\n" + "="*60)
input("Press Enter to exit...")
sys.exit(1)
check_required_packages()
from langdetect import detect
from colorama import init, Fore, Style
from collections import defaultdict
from platformdirs import user_config_dir
from pathlib import Path
from utils import (ASCII_ART, clear_and_print_ascii, map_lang_3to2,
trim_movie_name, scan_subtitle_coverage, display_coverage_results,
get_skip_dirs_from_config)
init(autoreset=True)
BANNER_LINE = f" {Style.BRIGHT}{Fore.RED}[Phase 4/4]{Style.RESET_ALL} Subtitle Synchronisation"
script_dir = os.path.dirname(os.path.abspath(__file__))
CONFIG_PATH = os.path.join(script_dir, '.config')
ANSI_ESCAPE = re.compile(r'\x1b\[[0-9;]*m|\033\[[0-9;]*m')
run_counter = 1
if os.path.exists(CONFIG_PATH):
with open(CONFIG_PATH, encoding='utf-8') as f:
run_counter = next((int(line.split('=', 1)[1].strip()) for line in f
if line.strip().lower().startswith('run_counter') and '=' in line), 1)
LOGS_DIR = os.path.join(script_dir, 'logs', f'Subservient-run-{run_counter}')
os.makedirs(LOGS_DIR, exist_ok=True)
existing_log = next((os.path.join(LOGS_DIR, f) for f in os.listdir(LOGS_DIR)
if f.startswith('synchronisation_log') and f.endswith('.txt')), None)
if existing_log:
LOG_FILE = existing_log
with open(LOG_FILE, 'r+', encoding='utf-8') as f:
content = f.read()
part_count = content.count('Synchronisation - part') + 1
f.seek(0, 2)
if f.tell() > 0:
f.write('\n')
f.write(f'Synchronisation - part {part_count}\n')
else:
log_time = datetime.datetime.now().strftime('%d-%m-%Y_%H.%M.%S')
LOG_FILE = os.path.join(LOGS_DIR, f"synchronisation_log_{log_time}.txt")
with open(LOG_FILE, 'a', encoding='utf-8') as f:
f.write('Synchronisation - part 1\n')
def read_config_as_dict(config_path):
"""Read config file and return key-value pairs as dictionary."""
if not os.path.exists(config_path):
return {}
with open(config_path, encoding='utf-8') as f:
return {m.group(1).strip().lower(): m.group(2).strip()
for line in f if (m := re.match(r'^([a-zA-Z0-9_]+)\s*=\s*(.+)$', line.strip()))}
def strip_ansi(text):
"""Remove ANSI color codes from text."""
return ANSI_ESCAPE.sub('', text)
def sync_tag():
"""Return formatted synchronisation tag for console output."""
return f"{Style.BRIGHT}{Fore.BLUE}[Synchronisation]{Style.RESET_ALL}"
def sync_mode_tag():
"""Return formatted synchronisation tag with mode indicator for sync-specific messages."""
mode_tag = f"{Style.DIM}{Fore.YELLOW}[Smart Sync]{Style.RESET_ALL}" if SMART_SYNC else f"{Style.DIM}{Fore.YELLOW}[First Match]{Style.RESET_ALL}"
return f"{Style.BRIGHT}{Fore.BLUE}[Synchronisation]{Style.RESET_ALL} {mode_tag}"
def print_and_log(msg, end='\n', log_only=False):
"""Print message to console and write to log file."""
if not log_only:
print(msg, end=end)
with open(LOG_FILE, 'a', encoding='utf-8') as f:
f.write(strip_ansi(msg) + ('' if end == '' else end))
def input_and_log(prompt):
"""Get user input and log it to file."""
print_and_log(prompt, end='')
answer = input('')
with open(LOG_FILE, 'a', encoding='utf-8') as f:
f.write(f'[USER INPUT] {strip_ansi(answer)}\n')
return answer
def ensure_initial_setup():
"""Check if Subservient initial setup is complete."""
config_dir = Path(user_config_dir()) / "Subservient"
pathfile = config_dir / "Subservient_pathfiles"
required_keys = ["subservient_anchor", "subordinate_path", "extraction_path", "acquisition_path", "synchronisation_path", "utils_path"]
if not pathfile.exists():
show_setup_error()
lines = pathfile.read_text(encoding="utf-8").splitlines()
keys = {l.split('=')[0] for l in lines if '=' in l}
if not all(k in keys for k in required_keys):
show_setup_error()
def show_setup_error():
"""Display setup error message and exit."""
error_msg = (f"{Fore.RED}{Style.BRIGHT}[ERROR]{Style.RESET_ALL} Initial setup not complete.\n\n"
f"{Fore.YELLOW}To get started with Subservient:{Style.RESET_ALL}\n"
f"{Fore.CYAN}1.{Style.RESET_ALL} Ensure subordinate.py is in the main folder with other scripts\n"
f"{Fore.CYAN}2.{Style.RESET_ALL} Run subordinate.py to perform setup and register script paths\n"
f"{Fore.CYAN}3.{Style.RESET_ALL} After setup, move subordinate.py to process movies\n\n"
f"{Fore.YELLOW}See README for more details.{Style.RESET_ALL}\n")
print_and_log(error_msg)
input("Press Enter to exit...")
sys.exit(1)
with open(LOG_FILE, 'a+', encoding='utf-8') as f:
f.write(strip_ansi(ASCII_ART) + '\n')
f.write(strip_ansi(BANNER_LINE) + '\n\n')
clear_and_print_ascii(BANNER_LINE)
ensure_initial_setup()
pathfile = os.path.join(user_config_dir(), "Subservient", "Subservient_pathfiles")
anchor_path = script_dir
if os.path.exists(pathfile):
with open(pathfile, "r", encoding="utf-8") as f:
anchor_path = next((line.strip().split("=", 1)[1] for line in f
if line.startswith("subservient_anchor=")), anchor_path)
os.chdir(anchor_path)
skip_dirs = get_skip_dirs_from_config()
videos = []
for root, dirs, files in os.walk(anchor_path):
dirs[:] = [d for d in dirs if d.lower() not in skip_dirs]
if any(f.endswith((".mkv", ".mp4")) for f in files):
videos.extend(os.path.join(root, f) for f in files if f.endswith((".mkv", ".mp4")))
dirs[:] = []
config_values = read_config_as_dict(CONFIG_PATH)
pause_seconds = int(float(config_values.get('pause_seconds', 3)))
ACCEPT_OFFSET_THRESHOLD = float(config_values.get('accept_offset_threshold', 0.05))
REJECT_OFFSET_THRESHOLD = float(config_values.get('reject_offset_threshold', 2.5))
PRESERVE_FORCED_SUBTITLES = config_values.get('preserve_forced_subtitles', 'false').lower() in ('true', '1', 'yes', 'on')
PRESERVE_UNWANTED_SUBTITLES = config_values.get('preserve_unwanted_subtitles', 'false').lower() in ('true', '1', 'yes', 'on')
SMART_SYNC = config_values.get('smart_sync', 'false').lower() in ('true', '1', 'yes', 'on')
drift_marked = False
def read_languages_from_config(config_path):
"""Read and validate language settings from config file."""
if not os.path.exists(config_path):
print_and_log(f"{sync_tag()} {Fore.RED}Config file not found. Defaulting to English.{Style.RESET_ALL}")
return handle_language_default_warning()
with open(config_path, 'r', encoding='utf-8') as f:
for line in f:
if line.strip().lower().startswith('languages'):
parts = line.split('=', 1)
if len(parts) == 2:
langs = [l.strip() for l in parts[1].split(',') if l.strip()]
if langs:
return langs
break
print_and_log(f"{sync_tag()} {Fore.RED}{Style.BRIGHT}No valid languages found in config!{Style.RESET_ALL}")
print_and_log(f"{sync_tag()} {Fore.YELLOW}Defaulting to English.{Style.RESET_ALL}")
return handle_language_default_warning()
def handle_language_default_warning():
"""Handle language config warning with user choice to continue or exit."""
while True:
print_and_log(f"\n{Fore.RED}{Style.BRIGHT}WARNING: No valid languages found in config!{Style.RESET_ALL}")
print_and_log(f"{Fore.YELLOW}Defaulting to English only.{Style.RESET_ALL}")
print_and_log(f"\n{Fore.CYAN}1{Style.RESET_ALL} = Continue with English only")
print_and_log(f"{Fore.RED}2{Style.RESET_ALL} = Exit and fix config file")
choice = input(f"Make a choice [{Fore.CYAN}1{Style.RESET_ALL}/{Fore.RED}2{Style.RESET_ALL}]: ").strip()
if choice == "1":
print_and_log(f"{Fore.YELLOW}Continuing with English only.{Style.RESET_ALL}\n")
return ['en']
elif choice == "2":
print_and_log(f"{Fore.RED}Exiting. Please fix your config file.{Style.RESET_ALL}")
sys.exit(1)
else:
print_and_log(f"{Fore.RED}Invalid choice. Please enter 1 or 2.{Style.RESET_ALL}")
def read_series_mode_from_config(config_path):
"""Read series mode setting from config file."""
if not os.path.exists(config_path):
print_and_log(f"{sync_tag()} {Fore.YELLOW}Config file not found. Defaulting to film mode.{Style.RESET_ALL}")
return False
with open(config_path, 'r', encoding='utf-8') as f:
for line in f:
if line.strip().lower().startswith('series_mode'):
parts = line.split('=', 1)
if len(parts) == 2:
val = parts[1].strip().lower()
return val in ['1', 'true', 'yes', 'on']
print_and_log(f"{sync_tag()} {Fore.YELLOW}series_mode not found in config. Defaulting to film mode.{Style.RESET_ALL}")
return False
def extract_sxxexx_code(name: str) -> str | None:
"""Extract season/episode code from filename."""
import re
match = re.search(r"[sS](\d{1,2})[eE](\d{1,2})", name)
return f"S{int(match.group(1)):02d}E{int(match.group(2)):02d}" if match else None
def run_ffmpeg_with_progress(cmd, output_path, orig_size):
"""Run ffmpeg command with progress bar based on output file size."""
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
stop_flag = threading.Event()
def show_progress():
while not stop_flag.is_set():
try:
if os.path.exists(output_path):
size = os.path.getsize(output_path)
percent = min(100, int(size * 100 / orig_size)) if orig_size else 0
bar = ('#' * (percent // 2)).ljust(50)
print(f"\r[{bar}] {percent:3d}% ", end='', flush=True)
except Exception:
pass
time.sleep(0.5)
print('\r' + ' ' * 60 + '\r', end='', flush=True)
t = threading.Thread(target=show_progress)
t.start()
stdout, stderr = process.communicate()
stop_flag.set()
t.join()
return stdout, stderr
clear_and_print_ascii(BANNER_LINE)
successful_syncs = 0
successful_syncs_per_lang = {}
LANGUAGES = read_languages_from_config(CONFIG_PATH)
SERIES_MODE = read_series_mode_from_config(CONFIG_PATH)
def extract_sxxexx(filename):
"""Extract season/episode code (SxxExx) from filename."""
match = re.search(r'(S\d{2}E\d{2})', filename, re.IGNORECASE)
return match.group(1).upper() if match else None
sxxexx_to_video = {}
if SERIES_MODE:
for video in videos:
if code := extract_sxxexx(os.path.basename(video)):
sxxexx_to_video[code] = video
FAILED_SUBS = set()
FAILED_DETAILS = {}
for f in os.listdir():
if f.endswith('.FAILED.srt'):
for pattern in [r"(?P<basename>.+)\.(?P<lang>[a-z]{2})\.number\d+\.FAILED\.srt$",
r"(?P<basename>.+)\.(?P<lang>[a-z]{2})\.FAILED\.srt$"]:
if m := re.match(pattern, f):
base, lang = m.group('basename'), m.group('lang')
FAILED_SUBS.add((base, lang))
FAILED_DETAILS[(base, lang)] = f
break
if FAILED_SUBS:
print_and_log(f"{sync_tag()} {Fore.RED}{Style.BRIGHT}Detected subtitles marked as FAILED (will be skipped):{Style.RESET_ALL}")
for (base, lang) in sorted(FAILED_SUBS):
print_and_log(f" {Fore.LIGHTRED_EX}* {base} [{lang.upper()}] ({FAILED_DETAILS[(base, lang)]}){Style.RESET_ALL}")
def print_video_header(video_name, idx, total):
"""Print formatted header for current video being processed."""
bar = f"{Fore.CYAN}[{idx}/{total}]{Style.RESET_ALL} {Fore.LIGHTYELLOW_EX}{os.path.basename(video_name).upper()}{Style.RESET_ALL}"
print(bar.ljust(79), end='\n', flush=True)
def cleanup_duplicates_in_folder(folder: str, languages):
"""Remove redundant numbered subtitle files when correct ones exist."""
try:
files = os.listdir(folder)
except Exception:
return
for f in files:
if f.endswith(('.mkv', '.mp4')):
base_name = os.path.splitext(f)[0]
# Extract series code if in series mode
sxxexx_code = None
if SERIES_MODE:
sxxexx_code = extract_sxxexx_code(f)
for lang in languages:
# Determine correct filename patterns based on mode and content
correct_patterns = []
if SERIES_MODE and sxxexx_code:
# Series mode with SxxExx code
if sxxexx_code.lower() in base_name.lower():
# Video already has SxxExx in name
correct_patterns.append(f"{base_name}.{lang}.srt")
else:
# Video doesn't have SxxExx
correct_patterns.append(f"{base_name}.{sxxexx_code}.{lang}.srt")
else:
# Movie mode or series without clear SxxExx
correct_patterns.append(f"{base_name}.{lang}.srt")
# Check if any correct pattern exists
correct_exists = any(os.path.exists(os.path.join(folder, pattern)) for pattern in correct_patterns)
if correct_exists:
# Clean up numbered files - multiple patterns:
# Pattern 1: filename.number1.lang.srt (old pattern)
# Pattern 2: 1234.lang.number1.S01E01.srt (acquisition pattern)
for g in files:
is_numbered_old_pattern = (
g.startswith(f"{base_name}.") and
f".{lang}.srt" in g and
any(f".number{num}." in g for num in range(1, 100))
)
is_numbered_acquisition_pattern = (
f".{lang}.number" in g and
g.endswith('.srt') and
any(f".number{num}." in g for num in range(1, 100)) and
(sxxexx_code is None or sxxexx_code in g)
)
if (g not in correct_patterns and
(is_numbered_old_pattern or is_numbered_acquisition_pattern) and
not g.endswith('.FAILED.srt') and
not g.endswith('.DRIFT.srt')):
try:
os.remove(os.path.join(folder, g))
print_and_log(f"{sync_tag()} {Fore.YELLOW}Removed redundant numbered subtitle: {g}{Style.RESET_ALL}")
except Exception as e:
print_and_log(f"{sync_tag()} {Fore.RED}Could not remove {g}: {e}{Style.RESET_ALL}")
def comprehensive_cleanup_extracted_files():
"""
Comprehensive cleanup of all non-synchronized subtitle files and extracted folders.
Removes everything that is not a proper synchronized subtitle (video_name.lang.srt).
"""
print_and_log(f"{sync_tag()} {Fore.LIGHTYELLOW_EX}Comprehensive cleanup: removing all non-synchronized files...{Style.RESET_ALL}")
total_dirs = 1
all_dirs = []
all_dirs.append(anchor_path)
# Collect all directories to process
for root, dirs, files in os.walk(anchor_path):
dirs[:] = [d for d in dirs if d.lower() not in skip_dirs]
for d in dirs:
dir_path = os.path.join(root, d)
all_dirs.append(dir_path)
total_dirs += 1
processed_dirs = 0
start_time = time.time()
total_removed = 0
total_folders_removed = 0
def update_progress():
elapsed = time.time() - start_time
progress = processed_dirs / total_dirs if total_dirs > 0 else 0
bar_length = 40
filled_length = int(bar_length * progress)
bar = '█' * filled_length + '░' * (bar_length - filled_length)
print(f"\\r{sync_tag()} {Fore.CYAN}[{bar}]{Style.RESET_ALL} {progress*100:.1f}% ({processed_dirs}/{total_dirs}) - {elapsed:.1f}s", end='', flush=True)
# Process root directory first
removed = cleanup_non_sync_files_in_folder(anchor_path)
total_removed += removed
processed_dirs += 1
update_progress()
# Process all subdirectories
for root, dirs, files in os.walk(anchor_path):
dirs[:] = [d for d in dirs if d.lower() not in skip_dirs]
for d in dirs:
folder_path = os.path.join(root, d)
time.sleep(0.1)
removed = cleanup_non_sync_files_in_folder(folder_path)
total_removed += removed
processed_dirs += 1
update_progress()
print() # New line after progress bar
# Remove episode folders and temp directories
folders_removed = cleanup_episode_and_temp_folders()
total_folders_removed += folders_removed
if total_removed > 0 or total_folders_removed > 0:
print_and_log(f"{sync_tag()} {Fore.GREEN}Comprehensive cleanup complete: removed {total_removed} files and {total_folders_removed} folders{Style.RESET_ALL}")
else:
print_and_log(f"{sync_tag()} {Fore.YELLOW}Comprehensive cleanup complete: no files needed removal{Style.RESET_ALL}")
def cleanup_non_sync_files_in_folder(folder: str):
"""
Remove all subtitle files that are not synchronized subtitles.
Keeps only files matching video_name.lang.srt pattern.
"""
removed_count = 0
try:
files = os.listdir(folder)
except Exception:
return removed_count
# Get video files in this folder to determine valid synchronized subtitle names
video_files = [f for f in files if f.endswith(('.mkv', '.mp4'))]
# Create set of valid synchronized subtitle names
valid_sync_names = set()
for video_file in video_files:
base_name = os.path.splitext(video_file)[0]
# Extract series code if in series mode
sxxexx_code = None
if SERIES_MODE:
sxxexx_code = extract_sxxexx_code(video_file)
for lang in LANGUAGES:
# Determine correct filename patterns based on mode and content
if SERIES_MODE and sxxexx_code:
# Series mode with SxxExx code
if sxxexx_code.lower() in base_name.lower():
# Video already has SxxExx in name
valid_sync_names.add(f"{base_name}.{lang}.srt")
else:
# Video doesn't have SxxExx
valid_sync_names.add(f"{base_name}.{sxxexx_code}.{lang}.srt")
else:
# Movie mode or series without clear SxxExx
valid_sync_names.add(f"{base_name}.{lang}.srt")
# Remove any subtitle file that doesn't match synchronized pattern
for file in files:
if file.endswith('.srt'):
# Keep synchronized subtitles
if file in valid_sync_names:
continue
# Keep FAILED and DRIFT files (user might want to inspect them)
if file.endswith(('.FAILED.srt', '.DRIFT.srt')):
continue
# Remove everything else (numbered, extracted, temporary, etc.)
try:
file_path = os.path.join(folder, file)
os.remove(file_path)
print_and_log(f"{sync_tag()} {Fore.YELLOW}Removed non-sync subtitle: {file}{Style.RESET_ALL}")
removed_count += 1
except Exception as e:
print_and_log(f"{sync_tag()} {Fore.RED}Could not remove {file}: {e}{Style.RESET_ALL}")
# Remove SUBTITLES.S##.LANG.zip files only at the END of synchronization
elif (file.lower().startswith('subtitles.s') and
file.lower().endswith('.zip') and
'.' in file):
try:
file_path = os.path.join(folder, file)
os.remove(file_path)
print_and_log(f"{sync_tag()} {Fore.YELLOW}Removed processed SUBTITLES archive: {file}{Style.RESET_ALL}")
removed_count += 1
except Exception as e:
print_and_log(f"{sync_tag()} {Fore.RED}Could not remove {file}: {e}{Style.RESET_ALL}")
return removed_count
def cleanup_episode_and_temp_folders():
"""
Remove episode folders and temporary extraction directories.
"""
removed_count = 0
# Walk through all directories
for root, dirs, files in os.walk(anchor_path, topdown=False): # topdown=False to delete children before parents
dirs[:] = [d for d in dirs if d.lower() not in skip_dirs]
for d in dirs[:]: # Use slice copy since we'll be modifying the list
folder_path = os.path.join(root, d)
folder_name_lower = d.lower()
# Remove episode folders (episode 1, episode 01, etc.)
if re.match(r'episode\\s*\\d+', folder_name_lower):
try:
import shutil
shutil.rmtree(folder_path)
print_and_log(f"{sync_tag()} {Fore.YELLOW}Removed episode folder: {d}{Style.RESET_ALL}")
dirs.remove(d) # Remove from dirs list so os.walk doesn't try to descend into it
removed_count += 1
except Exception as e:
print_and_log(f"{sync_tag()} {Fore.RED}Could not remove episode folder {d}: {e}{Style.RESET_ALL}")
# Remove temp extraction directories
elif folder_name_lower.startswith('temp_extract_'):
try:
import shutil
shutil.rmtree(folder_path)
print_and_log(f"{sync_tag()} {Fore.YELLOW}Removed temp folder: {d}{Style.RESET_ALL}")
dirs.remove(d)
removed_count += 1
except Exception as e:
print_and_log(f"{sync_tag()} {Fore.RED}Could not remove temp folder {d}: {e}{Style.RESET_ALL}")
# Remove empty SUBTITLES.S##.LANG folders (keep ZIP files)
elif (folder_name_lower.startswith('subtitles.s') and
'.' in folder_name_lower and
not folder_name_lower.endswith('.zip')):
try:
# Check if folder is empty or only contains files we don't need
folder_files = os.listdir(folder_path)
if not folder_files: # Empty folder
os.rmdir(folder_path)
print_and_log(f"{sync_tag()} {Fore.YELLOW}Removed empty SUBTITLES folder: {d}{Style.RESET_ALL}")
dirs.remove(d)
removed_count += 1
except Exception as e:
print_and_log(f"{sync_tag()} {Fore.RED}Could not remove SUBTITLES folder {d}: {e}{Style.RESET_ALL}")
return removed_count
def final_cleanup_prompt_and_cleanup():
"""Perform final cleanup of duplicate and redundant subtitle files."""
print_and_log(f"{sync_tag()} {Fore.LIGHTYELLOW_EX}Final cleanup: removing duplicate/redundant subtitles...{Style.RESET_ALL}")
total_dirs = 1
all_dirs = []
all_dirs.append(anchor_path)
for root, dirs, files in os.walk(anchor_path):
dirs[:] = [d for d in dirs if d.lower() not in skip_dirs]
for d in dirs:
dir_path = os.path.join(root, d)
all_dirs.append(dir_path)
total_dirs += 1
processed_dirs = 0
start_time = time.time()
def update_progress():
elapsed = time.time() - start_time
progress = processed_dirs / total_dirs if total_dirs > 0 else 0
bar_length = 40
filled_length = int(bar_length * progress)
bar = '█' * filled_length + '░' * (bar_length - filled_length)
print(f"\r{sync_tag()} {Fore.CYAN}[{bar}]{Style.RESET_ALL} {progress*100:.1f}% ({processed_dirs}/{total_dirs}) - {elapsed:.1f}s", end='', flush=True)
cleanup_duplicates_in_folder(anchor_path, LANGUAGES)
processed_dirs += 1
update_progress()
for root, dirs, files in os.walk(anchor_path):
dirs[:] = [d for d in dirs if d.lower() not in skip_dirs]
for d in dirs:
time.sleep(0.25)
cleanup_duplicates_in_folder(os.path.join(root, d), LANGUAGES)
processed_dirs += 1
update_progress()
print()
cleaned_internal_subs = 0
not_cleaned_internal_subs = 0
not_cleaned_videos = []
manual_choices = {}
def has_internal_subs(video_path):
"""Check if video file contains internal subtitle streams."""
cmd = ["ffprobe", "-v", "error", "-select_streams", "s",
"-show_entries", "stream=index", "-of", "csv=p=0", video_path]
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return bool(result.stdout.strip())
def remove_internal_subs(video_path):
"""Remove all internal subtitle streams from video file."""
temp_path = video_path + ".nointernal.mkv"
cmd = ["ffmpeg", "-hide_banner", "-y", "-i", video_path,
"-map", "0:v", "-map", "0:a", "-c", "copy", "-sn", temp_path]
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode == 0 and os.path.exists(temp_path):
os.replace(temp_path, video_path)
return True
else:
if os.path.exists(temp_path):
os.remove(temp_path)
return False
def prompt_and_cleanup_internal_subs():
"""Handle internal subtitle cleanup with interactive user prompts for each video.
This complex function processes videos with internal subtitles and prompts users
to decide whether to keep or remove them. It handles different scenarios based on
missing external subtitles and duplicate language tracks.
"""
global cleaned_internal_subs, not_cleaned_internal_subs, not_cleaned_videos, manual_choices
total = sum(1 for video in videos if has_internal_subs(video) and any(
not (os.path.exists(f"{os.path.splitext(video)[0]}.{lang}.srt") or
(SERIES_MODE and extract_sxxexx_code(video) and
os.path.exists(f"{os.path.splitext(video)[0]}.{lang}.{extract_sxxexx_code(video)}.srt")))
for lang in LANGUAGES)
)
idx = 0
for video in videos:
video_basename, ext = os.path.splitext(video)
all_present = True
missing_langs = []
for lang in LANGUAGES:
found = False
# Check standard naming: filename.lang.srt
expected_standard = f"{video_basename}.{lang}.srt"
if os.path.exists(expected_standard):
found = True
# Check series naming if in series mode
if not found and SERIES_MODE:
sxxexx_code = extract_sxxexx_code(video)
if sxxexx_code:
# Check if video filename already contains the episode code
if sxxexx_code.lower() in video_basename.lower():
# Video already has SxxExx in name, subtitle should use standard naming
expected_series = f"{video_basename}.{lang}.srt"
else:
# Video doesn't have SxxExx, subtitle should have SxxExx before language
expected_series = f"{video_basename}.{sxxexx_code}.{lang}.srt"
if os.path.exists(expected_series):
found = True
if not found:
all_present = False
missing_langs.append(lang)
if all_present:
if has_internal_subs(video):
print_and_log(f"{sync_tag()} {Fore.LIGHTYELLOW_EX}Removing internal subtitles for compatibility...{Style.RESET_ALL}")
if remove_internal_subs(video):
cleaned_internal_subs += 1
print_and_log(f"{sync_tag()} {Fore.GREEN}Internal subtitles removed from {video}.{Style.RESET_ALL}")
else:
not_cleaned_internal_subs += 1
not_cleaned_videos.append(video)
print_and_log(f"{sync_tag()} {Fore.RED}Failed to remove internal subtitles from {video}.{Style.RESET_ALL}")
else:
print_and_log(f"{sync_tag()} {Fore.LIGHTYELLOW_EX}No internal subtitles detected in {video}. Skipping removal step.{Style.RESET_ALL}")
else:
if has_internal_subs(video):
idx += 1
year_match = re.search(r'(19|20)\d{2}', os.path.basename(video))
year = year_match.group(0) if year_match else ''
title = f"[{idx}/{total}] {os.path.basename(video).upper()}"
if year:
title += f" ({year})"
clear_and_print_ascii(BANNER_LINE)
print_and_log(f"{Style.BRIGHT}{Fore.LIGHTYELLOW_EX}{title}{Style.RESET_ALL}\n")
cmd = [
"ffprobe", "-v", "error", "-select_streams", "s", "-show_entries",
"stream=index:stream_tags=language:stream_tags=title:stream_tags=handler_name:stream_tags=codec_name",
"-of", "csv=p=0", video
]
try:
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8')
lines = [l for l in result.stdout.strip().split('\n') if l.strip()]
except Exception:
lines = []
if lines:
print_and_log(f"{Fore.WHITE}Found internal subtitle tracks:{Style.RESET_ALL}")
for l in lines:
parts = l.split(',')
lang = next((p for p in parts if len(p) == 3 and p.isalpha()), None)
codec = next((p for p in parts if p in ('subrip', 'hdmv_pgs_subtitle', 'dvd_subtitle', 'mov_text')), None)
desc = []
if lang:
desc.append(f"{Fore.CYAN}{lang.upper()}{Style.RESET_ALL} (VOBSUB)")
if codec:
desc.append(f"{Fore.LIGHTBLACK_EX}{codec}{Style.RESET_ALL}")
print_and_log(f" - {' '.join(desc) if desc else l}")
else:
print_and_log(f"{Fore.WHITE}No internal subtitle tracks found (unexpected).{Style.RESET_ALL}")
if missing_langs:
print_and_log(f"\n{Fore.WHITE}Missing external subtitles (SRT) for:{Style.RESET_ALL}")
for lang in missing_langs:
print_and_log(f" - {Fore.LIGHTRED_EX}{lang.upper()}{Style.RESET_ALL}")
present_langs = set()
internal_langs = set()
external_langs = set()
for l in lines:
parts = l.split(',')
lang = next((p for p in parts if len(p) == 3 and p.isalpha()), None)
if lang:
lang2 = map_lang_3to2(lang)
internal_langs.add(lang2)
for lang in LANGUAGES:
found_external = False
# Check standard naming: filename.lang.srt
expected_standard = f"{video_basename}.{lang}.srt"
if os.path.exists(expected_standard):
found_external = True
# Check series naming if in series mode: filename.lang.S01E01.srt
if not found_external and SERIES_MODE:
sxxexx_code = extract_sxxexx_code(video)
if sxxexx_code:
expected_series = f"{video_basename}.{lang}.{sxxexx_code}.srt"
if os.path.exists(expected_series):
found_external = True
if found_external:
external_langs.add(lang)
present_langs = internal_langs.union(external_langs)
duplicates = internal_langs.intersection(external_langs)
all_present = all(lang in present_langs for lang in LANGUAGES)
if all_present and not duplicates:
print_and_log(f"\n{Fore.GREEN}✓ All required languages are present (internally and/or externally), no duplicates found.{Style.RESET_ALL}")
print_and_log(f"{Fore.GREEN}✓ Recommended: Keep internal subtitles to ensure all subtitle languages remain available.{Style.RESET_ALL}")
print_and_log(f"{Fore.YELLOW}⚠ Alternative: Remove internal subtitles if you prefer external SRT files only.{Style.RESET_ALL}\n")
print_and_log(f"{Fore.CYAN}1{Style.RESET_ALL} = {Style.BRIGHT}Keep internal subtitles {Fore.LIGHTYELLOW_EX}(recommended, no duplicates){Style.RESET_ALL}")
print_and_log(f"{Fore.YELLOW}2{Style.RESET_ALL} = Remove all internal subtitles completely {Fore.LIGHTYELLOW_EX}(will cause missing subtitles for some languages, not recommended){Style.RESET_ALL}\n")
valid_choices = ['1', '2', '']
else:
print_and_log(f"\n{Fore.YELLOW}⚠ Some required languages lack external subtitles.{Style.RESET_ALL}")
print_and_log(f"{Fore.YELLOW}⚠ Keep internal when no external SRT is available for that language.{Style.RESET_ALL}")
print_and_log(f"{Fore.LIGHTYELLOW_EX}What would you like to do?{Style.RESET_ALL}")
print_and_log(f"{Fore.CYAN}1{Style.RESET_ALL} = {Style.BRIGHT}Keep internal subtitles {Fore.LIGHTYELLOW_EX}(duplicate subtitles can occur){Style.RESET_ALL}")
print_and_log(f"{Fore.CYAN}2{Style.RESET_ALL} = Remove internal subtitles only for languages with external subtitles present {Fore.LIGHTYELLOW_EX}(recommended){Style.RESET_ALL}")
print_and_log(f"{Fore.YELLOW}3{Style.RESET_ALL} = Remove all internal subtitles completely {Fore.LIGHTYELLOW_EX}(Will cause missing subtitles, not recommended){Style.RESET_ALL}\n")
valid_choices = ['1', '2', '3', '']
while True:
if all_present and not duplicates:
choice = input_and_log(f"Make a choice [{Fore.CYAN}1{Style.RESET_ALL}/{Fore.YELLOW}2{Style.RESET_ALL}]: ").strip()
if choice == "1" or choice == "":
print_and_log(f"{Fore.GREEN}Internal subtitles kept for this video.{Style.RESET_ALL}\n")
not_cleaned_internal_subs += 1
not_cleaned_videos.append(video)
manual_choices[video] = 'kept'
break
elif choice == "2":
temp_path = video + ".nointernal.mkv"
orig_size = os.path.getsize(video)
cmd = [
"ffmpeg", "-hide_banner", "-y", "-i", video,
"-map", "0:v", "-map", "0:a", "-c", "copy", "-sn", temp_path
]
print_and_log(f"{Fore.LIGHTYELLOW_EX}Remuxing to remove all internal subtitles...{Style.RESET_ALL}")
stdout, stderr = run_ffmpeg_with_progress(cmd, temp_path, orig_size)
for line in (stdout + '\n' + stderr).splitlines():
if 'muxing overhead' in line or 'frame' in line or 'size' in line:
print_and_log(line)
if os.path.exists(temp_path):
os.replace(temp_path, video)
cleaned_internal_subs += 1
print_and_log(f"{Fore.GREEN}Internal subtitles removed from {video}.{Style.RESET_ALL}")
manual_choices[video] = 'removed'
else:
not_cleaned_internal_subs += 1
not_cleaned_videos.append(video)
print_and_log(f"{Fore.RED}Failed to remove internal subtitles from {video}.{Style.RESET_ALL}")
manual_choices[video] = 'failed'
break
else:
print_and_log(f"{Fore.RED}Invalid choice. Please enter 1 or 2.{Style.RESET_ALL}")
else:
choice = input_and_log(f"Make a choice [{Fore.CYAN}1{Style.RESET_ALL}/{Fore.CYAN}2{Style.RESET_ALL}/{Fore.YELLOW}3{Style.RESET_ALL}]: ").strip()
if choice == "1" or choice == "":
print_and_log(f"{Fore.GREEN}Internal subtitles kept for this video.{Style.RESET_ALL}\n")
not_cleaned_internal_subs += 1
not_cleaned_videos.append(video)
manual_choices[video] = 'kept'
break
elif choice == "2":
removed_any = False
probe_cmd = [
"ffprobe", "-v", "error", "-select_streams", "s", "-show_entries",
"stream=index:stream_tags=language", "-of", "csv=p=0", video
]
result = subprocess.run(probe_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8')
probe_lines = [l for l in result.stdout.strip().split('\n') if l.strip()]
subtitle_streams = []
ffmpeg_sub_idx = 0
for l in probe_lines:
parts = l.split(',')
if len(parts) >= 1:
stream_idx = parts[0]
stream_lang = parts[1].lower() if len(parts) >= 2 and parts[1] else 'und'
subtitle_streams.append((ffmpeg_sub_idx, stream_idx, stream_lang))
ffmpeg_sub_idx += 1
for lang in LANGUAGES:
has_external = any(os.path.exists(f"{video_basename}.{lang}.srt"))
if has_external:
print_and_log(f"{Fore.YELLOW}Removing internal subtitle for {Fore.CYAN}{lang.upper()}{Fore.YELLOW} from the video file. Please wait...{Style.RESET_ALL}")
streams_to_keep = []
lang_removed = False
for ffmpeg_idx, stream_idx, stream_lang in subtitle_streams:
matches_lang = False
if map_lang_3to2(stream_lang) == lang:
matches_lang = True