-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsubordinate.py
More file actions
1751 lines (1533 loc) · 95.8 KB
/
subordinate.py
File metadata and controls
1751 lines (1533 loc) · 95.8 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
import sys
import subprocess
from datetime import datetime
import re
from pathlib import Path
try:
from colorama import init, Fore, Style
init(autoreset=True)
except ImportError:
class MockColor:
def __getattr__(self, name):
return ""
Fore = Style = MockColor()
def ensure_core_requirements():
"""Install core Python packages required for Subservient to function.
Checks if required packages are installed and offers to install missing ones.
Exits the program after installation or if user declines installation.
"""
REQUIRED_PACKAGES = [
("colorama", None),
("platformdirs", None),
("pycountry", None),
("requests", None),
("tqdm", None),
("ffsubsync", None),
("langdetect", None),
]
missing = []
for pkg, import_name in REQUIRED_PACKAGES:
try:
__import__(import_name or pkg)
except ImportError:
missing.append(pkg)
if missing:
print("\n[Subservient] The following required packages are missing:")
for pkg in missing:
print(f" - {pkg}")
if os.name == 'nt':
import shutil
import glob
cl_path = shutil.which('cl')
if not cl_path:
vs_patterns = [
r"C:\Program Files\Microsoft Visual Studio\*\*\VC\Tools\MSVC\*\bin\Hostx64\x64\cl.exe",
r"C:\Program Files (x86)\Microsoft Visual Studio\*\*\VC\Tools\MSVC\*\bin\Hostx64\x64\cl.exe",
r"C:\Program Files\Microsoft Visual Studio\*\*\VC\Tools\MSVC\*\bin\Hostx86\x86\cl.exe",
r"C:\Program Files (x86)\Microsoft Visual Studio\*\*\VC\Tools\MSVC\*\bin\Hostx86\x86\cl.exe",
r"C:\Program Files (x86)\Microsoft Visual Studio\*\BuildTools\VC\Tools\MSVC\*\bin\Hostx64\x64\cl.exe",
r"C:\Program Files (x86)\Microsoft Visual Studio\*\BuildTools\VC\Tools\MSVC\*\bin\Hostx86\x86\cl.exe",
r"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\cl.exe",
r"C:\Program Files (x86)\Microsoft Visual Studio\2017\*\VC\Tools\MSVC\*\bin\Hostx64\x64\cl.exe",
r"C:\Program Files (x86)\Microsoft Visual Studio\2017\*\VC\Tools\MSVC\*\bin\Hostx86\x86\cl.exe"
]
found_cl = any(glob.glob(pattern) for pattern in vs_patterns)
if not found_cl:
print(f"\n{Fore.YELLOW}ERROR: Build tools not installed. Python packages require Microsoft Visual C++ Build Tools to compile.{Style.RESET_ALL}")
print(f"{Fore.YELLOW}Please install Microsoft Visual C++ Build Tools first before installing Python packages.{Style.RESET_ALL}")
print(f"{Fore.WHITE}In the README, look for chapter: {Fore.CYAN}'1. Installing and Configuring Subservient', step 4{Style.RESET_ALL}")
print(f"{Fore.WHITE}In there, check the 'External Tools' section for installation instructions.{Style.RESET_ALL}")
input("\nPress Enter to exit...")
sys.exit(1)
choice = input("\nWould you like to install ALL missing packages now? [y/n]: ").strip().lower()
if choice in ('', 'y', 'yes'):
try:
subprocess.check_call([sys.executable, '-m', 'pip', 'install', *missing])
print("\nSuccessfully installed required packages.\n")
if os.name == 'nt':
os.system('cls')
else:
os.system('clear')
print("[Subservient] All essential packages for Subservient are now installed.")
print("[Subservient] It's strongly recommended to verify and test all packages")
print("[Subservient] When opening subordinate.py, use option '4' to test the installed packages.")
print("[Subservient] Please close this terminal and try restarting subordinate.py =)\n\n")
input("Press Enter to exit...")
sys.exit(0)
except Exception as e:
print(f"\n[ERROR] Failed to install packages: {e}\nPlease install them manually and restart the script.")
input("\nPress Enter to exit...")
sys.exit(1)
else:
print("\n[Subservient] Required packages are missing. Exiting.")
input("\nPress Enter to exit...")
sys.exit(1)
ensure_core_requirements()
print("[Subservient] Loading imports..")
import importlib.util
import time
from pathlib import Path
from platformdirs import user_config_dir
from datetime import datetime
import re
import pycountry
import requests
BANNER_LINE = f" {Fore.LIGHTRED_EX}[Phase 1/4]{Style.RESET_ALL} Subservient Set-up"
# Initialize logging
def setup_logging():
"""Set up logging for subordinate.py pre-flight checklist."""
global LOG_FILE, LOGS_DIR
# Get anchor path
config_dir = Path(user_config_dir()) / "Subservient"
pathfile = config_dir / "Subservient_pathfiles"
anchor_path = Path(__file__).parent.resolve()
if pathfile.exists():
try:
with open(pathfile, "r", encoding="utf-8") as f:
for line in f:
if line.startswith("utils_path="):
utils_path = Path(line.split("=", 1)[1].strip())
anchor_path = utils_path.parent
break
except Exception:
pass
# Read run counter from config
config_path = anchor_path / '.config'
run_counter = 1
if config_path.exists():
try:
with open(config_path, encoding='utf-8') as f:
for line in f:
if line.strip().lower().startswith('run_counter'):
try:
run_counter = int(line.split('=', 1)[1].strip())
except:
run_counter = 1
break
except Exception:
pass
# Note: Logging will be initialized when user chooses to start the run
def strip_ansi(text):
"""Remove ANSI color codes from text."""
ansi_escape = re.compile(r'\x1b\[[0-9;]*m|\033\[[0-9;]*m')
return ansi_escape.sub('', text)
def print_and_log(msg, end='\n'):
"""Print message to console and write to log file."""
print(msg, end=end)
if LOG_FILE:
try:
with LOG_FILE.open('a', encoding='utf-8') as f:
f.write(strip_ansi(msg) + ('' if end == '' else end))
except Exception:
pass # Continue silently if logging fails
def sub_tag():
"""Return formatted subordinate tag for console output."""
return f"{Style.BRIGHT}{Fore.BLUE}[Subordinate]{Style.RESET_ALL}"
# Initialize logging variables
LOG_FILE = None
LOGS_DIR = None
# Note: Logging will be set up when user confirms to start the run
# setup_logging()
def write_anchor_to_pathfile():
"""Write current directory path to Subservient pathfiles config.
Writes or updates the subservient anchor path in the pathfile and
creates config directory and pathfile if they don't exist.
"""
config_dir = Path(user_config_dir()) / "Subservient"
config_dir.mkdir(parents=True, exist_ok=True)
pathfile = config_dir / "Subservient_pathfiles"
anchor_path = str(Path(__file__).resolve().parent)
lines = []
if pathfile.exists():
with open(pathfile, "r", encoding="utf-8") as f:
lines = f.read().splitlines()
found = False
for i, line in enumerate(lines):
if line.startswith("subservient_anchor="):
lines[i] = f"subservient_anchor={anchor_path}"
found = True
break
if not found:
lines.append(f"subservient_anchor={anchor_path}")
else:
lines = [f"subservient_anchor={anchor_path}"]
with open(pathfile, "w", encoding="utf-8") as f:
f.write("\n".join(lines) + "\n")
def write_subordinate_path_to_pathfile():
"""Write current subordinate.py path to Subservient pathfiles config.
Updates the subordinate_path entry in the pathfile to reflect the current
location of subordinate.py, enabling other modules to find this script.
"""
config_dir = Path(user_config_dir()) / "Subservient"
config_dir.mkdir(parents=True, exist_ok=True)
pathfile = config_dir / "Subservient_pathfiles"
subordinate_path = str(Path(__file__).resolve())
lines = []
if pathfile.exists():
with open(pathfile, "r", encoding="utf-8") as f:
lines = f.read().splitlines()
found = False
for i, line in enumerate(lines):
if line.startswith("subordinate_path="):
lines[i] = f"subordinate_path={subordinate_path}"
found = True
break
if not found:
lines.append(f"subordinate_path={subordinate_path}")
else:
lines = [f"subordinate_path={subordinate_path}"]
with open(pathfile, "w", encoding="utf-8") as f:
f.write("\n".join(lines) + "\n")
def print_subservient_checklist():
"""Display pre-flight checklist for Subservient setup and usage.
Shows current configuration and video processing settings including mode,
processing type, language settings, and other important parameters.
For series mode, provides TV series detection and analysis.
"""
config_dir = Path(user_config_dir()) / "Subservient"
pathfile = config_dir / "Subservient_pathfiles"
anchor_path = None
if pathfile.exists():
with open(pathfile, "r", encoding="utf-8") as f:
for line in f:
if line.startswith("utils_path="):
utils_path = Path(line.split("=", 1)[1].strip())
anchor_path = utils_path.parent
break
if anchor_path is None:
anchor_path = Path(__file__).parent.resolve()
config_path = anchor_path / '.config'
config = {}
if config_path.exists():
with open(config_path, encoding='utf-8') as f:
for line in f:
line = line.strip()
m = re.match(r'^([a-zA-Z0-9_]+)\s*=\s*(.+)$', line)
if m:
config[m.group(1).strip().lower()] = m.group(2).strip()
series_mode = config.get('series_mode', None)
top_downloads = config.get('top_downloads', None)
delete_extra_videos = config.get('delete_extra_videos', None)
smart_sync = config.get('smart_sync', None)
local_path = Path(__file__).parent.resolve()
video_exts = {'.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm'}
direct_videos = [f for f in local_path.iterdir() if f.is_file() and f.suffix.lower() in video_exts]
is_series_mode = series_mode and series_mode.strip().lower() == 'true'
if is_series_mode:
series_info = utils.detect_series_structure(local_path)
if direct_videos:
# In series mode, multiple video files = multiple file processing
# Single video file = single file processing
if len(direct_videos) > 1:
processing_type = f"{Fore.CYAN}Multiple file processing{Style.RESET_ALL}"
else:
processing_type = f"{Fore.CYAN}Single file processing{Style.RESET_ALL}"
folder_count_display = f"{Fore.GREEN}1{Style.RESET_ALL}"
else:
if series_info['series_detected']:
# In series mode, always show batch processing regardless of series count
processing_type = f"{Fore.CYAN}Batch processing{Style.RESET_ALL}"
folder_count_display = f"{Fore.GREEN}{series_info['folder_analysis']['video_folders']}{Style.RESET_ALL}"
else:
processing_type = f"{Fore.CYAN}Batch processing{Style.RESET_ALL}"
folder_count_display = f"{Fore.RED}0{Style.RESET_ALL}"
else:
if direct_videos:
# In movie mode, direct videos = single file processing (even if multiple movies)
processing_type = f"{Fore.CYAN}Single file processing{Style.RESET_ALL}"
folder_count_display = f"{Fore.GREEN}1{Style.RESET_ALL}"
else:
subfolders = [f for f in local_path.iterdir() if f.is_dir()]
count = sum(1 for folder in subfolders if [f for f in folder.iterdir() if f.is_file() and f.suffix.lower() in video_exts])
processing_type = f"{Fore.CYAN}Batch processing{Style.RESET_ALL}"
folder_count_display = f"{Fore.GREEN}{count}{Style.RESET_ALL}"
mode = (f"{Fore.GREEN}TV Series mode{Style.RESET_ALL}" if is_series_mode
else f"{Fore.GREEN}Movie mode{Style.RESET_ALL}" if series_mode
else f"{Fore.RED}N/A (series_mode missing in config){Style.RESET_ALL}")
# Add sync mode display
sync_mode_display = (f"{Fore.CYAN}Smart Sync{Style.RESET_ALL}" if smart_sync and smart_sync.strip().lower() == 'true'
else f"{Fore.CYAN}First Match{Style.RESET_ALL}" if smart_sync
else f"{Fore.RED}N/A (smart_sync missing in config){Style.RESET_ALL}")
subtitle_downloads = f"{Fore.YELLOW}{top_downloads}{Style.RESET_ALL}" if top_downloads else f"{Fore.RED}N/A{Style.RESET_ALL}"
if delete_extra_videos is not None:
delete_status = (f"{Fore.RED}PERMANENTLY DELETE extra videos{Style.RESET_ALL}"
if delete_extra_videos.strip().lower() == 'true'
else f"{Fore.CYAN}Move extra videos to 'Extras' folder{Style.RESET_ALL}")
else:
delete_status = f"{Fore.RED}N/A (delete_extra_videos missing in config){Style.RESET_ALL}"
folder_path = Path(__file__).parent.resolve()
folder_name = folder_path.name
short_path = str(folder_path.parent / (folder_name[:37] + '...' if len(folder_name) > 40 else folder_name))
reject_offset_threshold = config.get('reject_offset_threshold', None)
threshold_str = (f"{float(reject_offset_threshold):.1f}s"
if reject_offset_threshold and reject_offset_threshold.replace('.', '').isdigit()
else f"{Fore.RED}N/A{Style.RESET_ALL}")
print_and_log(f"{Style.BRIGHT}{Fore.BLUE} [ Subservient Pre-Flight Checklist ]{Style.RESET_ALL}\n")
if is_series_mode:
# Check for potential movies in series mode
potential_movie_info = utils.detect_potential_movies_in_series_mode(local_path, config_path)
has_series_warning = potential_movie_info['has_potential_movies']
else:
# Check for potential series in video mode
potential_series_info = utils.detect_potential_series_in_video_mode(local_path, config_path)
has_series_warning = potential_series_info['has_potential_series']
# Only show detailed info if there are NO warnings
if not has_series_warning:
print_and_log(f" {Fore.WHITE}Location:{Style.RESET_ALL} {Fore.LIGHTYELLOW_EX}{short_path}{Style.RESET_ALL}")
print_and_log(f" {Fore.WHITE}Mode:{Style.RESET_ALL} {mode}")
print_and_log(f" {Fore.WHITE}Processing type:{Style.RESET_ALL} {processing_type}")
print_and_log(f" {Fore.WHITE}Sync mode:{Style.RESET_ALL} {sync_mode_display}")
# Only show "Maps found" in movie mode, not in series mode
if not is_series_mode:
print_and_log(f" {Fore.WHITE}Maps found:{Style.RESET_ALL} {folder_count_display}")
subtitle_langs = config.get('languages', None)
audio_langs = config.get('audio_track_languages', None)
print_and_log(f" {Fore.WHITE}Subtitle languages to find:{Style.RESET_ALL} {Fore.LIGHTYELLOW_EX}{subtitle_langs if subtitle_langs else 'N/A'}{Style.RESET_ALL}")
print_and_log(f" {Fore.WHITE}Audio track languages to keep:{Style.RESET_ALL} {Fore.LIGHTYELLOW_EX}{audio_langs if audio_langs else 'N/A'}{Style.RESET_ALL}")
print_and_log(f" {Fore.WHITE}Subtitle downloads per batch:{Style.RESET_ALL} {subtitle_downloads}")
print_and_log(f" {Fore.WHITE}Extra video handling:{Style.RESET_ALL} {delete_status}")
print_and_log(f" {Fore.WHITE}Subtitle delay threshold:{Style.RESET_ALL} {Fore.LIGHTYELLOW_EX}{threshold_str}{Style.RESET_ALL}")
# Show resync mode status
resync_mode = config.get('resync_mode', 'false').lower() in ('true', '1', 'yes', 'on')
resync_status = f"{Fore.RED}{Style.BRIGHT}ENABLED (will move existing subtitles){Style.RESET_ALL}" if resync_mode else f"{Fore.GREEN}Disabled{Style.RESET_ALL}"
print_and_log(f" {Fore.WHITE}Resync mode:{Style.RESET_ALL} {resync_status}")
# Show appropriate menu based on whether there are warnings
if has_series_warning:
if is_series_mode:
print_and_log(f"{Fore.RED}⚠️ CANNOT START - MISSING SxxExx NAMING IN SERIES MODE{Style.RESET_ALL}")
print_and_log(f" {Fore.YELLOW}Found videos without proper SxxExx codes (e.g. S01E01, S02E05){Style.RESET_ALL}")
print_and_log(f" {Fore.WHITE}All videos must have SxxExx naming for episode detection{Style.RESET_ALL}")
print_and_log(f"\n {Fore.WHITE}Fix by:{Style.RESET_ALL}")
print_and_log(f" {Fore.CYAN}• Adding SxxExx codes to ALL video filenames{Style.RESET_ALL}")
print_and_log(f" {Fore.CYAN}• OR moving movies to separate location{Style.RESET_ALL}")
else:
print_and_log(f"\n{Fore.RED}⚠️ CANNOT START - SERIES DETECTED IN MOVIE MODE{Style.RESET_ALL}")
print_and_log(f" {Fore.YELLOW}Found folders with 3+ videos that appear to be TV series{Style.RESET_ALL}")
print_and_log(f" {Fore.WHITE}In movie mode, series content is NOT allowed in the scan area{Style.RESET_ALL}")
print_and_log(f"\n {Fore.WHITE}Please go through this check:{Style.RESET_ALL}")
print_and_log(f" {Fore.CYAN}• Are you trying to process TV series? -> set series_mode=true{Style.RESET_ALL}")
print_and_log(f" {Fore.CYAN}• Are you trying to process Movies? -> Make sure there are no multiple video files in folders{Style.RESET_ALL}")
print_and_log(f"\n {Fore.LIGHTRED_EX}Series and movies cannot be processed together!{Style.RESET_ALL}")
print_and_log(f"\n{Fore.RED} 1{Style.RESET_ALL} = Exit to fix configuration")
else:
print_and_log(f"\n{Fore.LIGHTYELLOW_EX} Is everything set correctly?{Style.RESET_ALL}")
print_and_log(f"{Fore.GREEN} 1{Style.RESET_ALL} = Looks good, start Subservient!")
print_and_log(f"{Fore.RED} 2{Style.RESET_ALL} = This is incorrect. Exit so that I can fix it")
# Return whether there's a series warning
return has_series_warning
def print_main_menu():
"""Display main menu options for Subservient."""
"""Display the main menu options for the Subservient application."""
print(f"\n{Style.BRIGHT}{Fore.YELLOW}What would you like to do?{Style.RESET_ALL}\n")
print(f" {Fore.GREEN}1{Style.RESET_ALL} = Start Subservient")
print(f" {Fore.GREEN}2{Style.RESET_ALL} = Scan subtitle coverage")
print(f" {Fore.GREEN}3{Style.RESET_ALL} = Show quick instructions")
print(f" {Fore.GREEN}4{Style.RESET_ALL} = Install & verify requirements")
print(f" {Fore.GREEN}5{Style.RESET_ALL} = Extra tools")
print(f" {Fore.GREEN}6{Style.RESET_ALL} = Recreate .config file")
print(f" {Fore.GREEN}7{Style.RESET_ALL} = Open README file")
print(f" {Fore.GREEN}8{Style.RESET_ALL} = Exit\n")
def print_subtitle_cleaner_intro():
"""Display subtitle cleaner introduction and options."""
utils.clear_and_print_ascii(BANNER_LINE)
print(f"{Style.BRIGHT}{Fore.BLUE}[Subservient]{Style.RESET_ALL} Subtitle Cleaner\n")
print(f"{Style.BRIGHT}{Fore.CYAN}What is Subtitle Cleaner?{Style.RESET_ALL}")
print(f"{Fore.WHITE}Subtitle Cleaner removes unwanted content from .srt subtitle files, such as:{Style.RESET_ALL}")
print(f" • {Fore.LIGHTYELLOW_EX}Advertisements and promotional text{Style.RESET_ALL}")
print(f" • {Fore.LIGHTYELLOW_EX}Website credits and watermarks{Style.RESET_ALL}")
print(f" • {Fore.LIGHTYELLOW_EX}Translator notes and metadata{Style.RESET_ALL}")
print(f" • {Fore.LIGHTYELLOW_EX}Other unwanted content that clutters subtitles{Style.RESET_ALL}")
print(f"\n{Fore.WHITE}All original files are automatically backed up to:{Style.RESET_ALL}")
print(f" {Fore.LIGHTBLACK_EX}{utils.get_subservient_folder()}/data/subtitle_backups/{Style.RESET_ALL}")
print(f"\n{Style.BRIGHT}{Fore.YELLOW}What would you like to do?{Style.RESET_ALL}\n")
print(f" {Fore.GREEN}1{Style.RESET_ALL} = Clean subtitle files (remove ads and unwanted content)")
print(f" {Fore.GREEN}2{Style.RESET_ALL} = Restore subtitle changes (undo previous cleaning)")
print(f" {Fore.RED}3{Style.RESET_ALL} = Return to extra tools menu\n")
print(f"{Style.DIM}Note: Make sure you're in a directory with video files and .srt subtitle files.{Style.RESET_ALL}")
def print_extra_tools_menu():
"""Display extra tools menu with available tools."""
utils.clear_and_print_ascii(BANNER_LINE)
print(f"{Style.BRIGHT}{Fore.BLUE}[Subservient]{Style.RESET_ALL} Extra Tools\n")
print(f"{Style.BRIGHT}{Fore.CYAN}Available Tools:{Style.RESET_ALL}")
print(f"{Fore.WHITE}Select a tool to use:{Style.RESET_ALL}\n")
print(f" {Fore.GREEN}1{Style.RESET_ALL} = Subtitle Cleaner - Remove ads and unwanted content from subtitle files")
print(f" {Fore.GREEN}2{Style.RESET_ALL} = Delete moved_subtitles folders - Clean up old subtitle backups")
print(f" {Fore.RED}3{Style.RESET_ALL} = Return to main menu\n")
print(f"{Style.DIM}More tools will be added in future updates.{Style.RESET_ALL}")
def show_extra_tools_menu():
"""Handle the Extra Tools menu interface."""
while True:
print_extra_tools_menu()
choice = input(f"{Fore.LIGHTYELLOW_EX}Make a choice:{Style.RESET_ALL} ").strip()
if choice == "1":
show_subtitle_cleaner()
elif choice == "2":
show_delete_moved_subtitles_confirmation()
elif choice == "3":
break
else:
print(f"{Fore.RED}Invalid choice. Please select 1, 2, or 3.{Style.RESET_ALL}")
time.sleep(1)
def show_subtitle_cleaner():
"""Handle the Subtitle Cleaner main interface."""
while True:
print_subtitle_cleaner_intro()
choice = input(f"{Fore.LIGHTYELLOW_EX}Make a choice:{Style.RESET_ALL} ").strip()
if choice == "1":
try:
utils.run_subtitle_cleaning_interface()
except Exception as e:
utils.clear_and_print_ascii(BANNER_LINE)
print(f"{Style.BRIGHT}{Fore.RED}[Error]{Style.RESET_ALL}")
print(f"{Fore.RED}An error occurred while running subtitle cleaning: {str(e)}{Style.RESET_ALL}")
print(f"{Fore.YELLOW}Please make sure all required dependencies are installed.{Style.RESET_ALL}")
input(f"\n{Fore.YELLOW}Press Enter to continue...{Style.RESET_ALL} ")
elif choice == "2":
try:
utils.run_subtitle_restore_interface()
except Exception as e:
utils.clear_and_print_ascii(BANNER_LINE)
print(f"{Style.BRIGHT}{Fore.RED}[Error]{Style.RESET_ALL}")
print(f"{Fore.RED}An error occurred while running subtitle restore: {str(e)}{Style.RESET_ALL}")
print(f"{Fore.YELLOW}Please make sure all required dependencies are installed.{Style.RESET_ALL}")
input(f"\n{Fore.YELLOW}Press Enter to continue...{Style.RESET_ALL} ")
elif choice == "3":
break
else:
print(f"{Fore.RED}Invalid choice. Please select 1, 2, or 3.{Style.RESET_ALL}")
time.sleep(1)
def show_delete_moved_subtitles_confirmation():
"""Show confirmation screen before deleting moved_subtitles folders."""
utils.clear_and_print_ascii(BANNER_LINE)
print(f"{Style.BRIGHT}{Fore.BLUE}[Subservient]{Style.RESET_ALL} Delete moved_subtitles Folders\n")
print(f"{Style.BRIGHT}{Fore.CYAN}What this tool does:{Style.RESET_ALL}")
print(f"This tool scans for 'moved_subtitles' folders and deletes them after checking")
print(f"whether you still have external subtitle files for all languages.\n")
print(f"{Style.BRIGHT}{Fore.YELLOW}Important:{Style.RESET_ALL}")
print(f"Only use this tool when you have good replacements for the backup subtitles.")
print(f"The tool will warn you if external subtitles are missing, but use with caution!\n")
print(f"{Fore.WHITE}What would you like to do?{Style.RESET_ALL}\n")
print(f" {Fore.GREEN}1{Style.RESET_ALL} = Yes, delete moved_subtitles folders")
print(f" {Fore.RED}2{Style.RESET_ALL} = Return to extra tools menu\n")
choice = input(f"{Fore.LIGHTYELLOW_EX}Make a choice:{Style.RESET_ALL} ").strip()
if choice == "1":
delete_moved_subtitles_folders()
elif choice == "2":
return
else:
print(f"{Fore.RED}Invalid choice. Returning to menu.{Style.RESET_ALL}")
time.sleep(1)
def delete_moved_subtitles_folders():
"""Delete moved_subtitles folders after checking subtitle coverage."""
try:
banner = f" {Fore.YELLOW}Delete moved_subtitles Folders{Style.RESET_ALL}"
utils.clear_and_print_ascii(banner)
# Get current directory and config
current_dir = Path(__file__).parent.resolve()
config_dir = Path(user_config_dir()) / "Subservient"
pathfile = config_dir / "Subservient_pathfiles"
anchor_path = current_dir
if pathfile.exists():
with open(pathfile, "r", encoding="utf-8") as f:
for line in f:
if line.startswith("subservient_anchor="):
anchor_path = Path(line.split("=", 1)[1].strip())
break
# Get languages from config
languages = ['en']
config_path1 = anchor_path / '.config'
if config_path1.exists():
languages = utils.get_languages_from_config(config_path1)
else:
try:
subservient_folder = utils.get_subservient_folder()
config_path2 = subservient_folder / '.config'
if config_path2.exists():
languages = utils.get_languages_from_config(config_path2)
except Exception:
languages = ['en']
print(f"{Fore.CYAN}Scanning for moved_subtitles folders...{Style.RESET_ALL}\n")
# Find all moved_subtitles folders recursively (no skip_dirs restrictions)
moved_folders = []
for root, dirs, files in os.walk(current_dir):
if "moved_subtitles" in dirs:
moved_folder = Path(root) / "moved_subtitles"
moved_folders.append(moved_folder)
if not moved_folders:
print(f"{Fore.GREEN}No moved_subtitles folders found.{Style.RESET_ALL}")
input(f"\n{Fore.YELLOW}Press Enter to return to the menu...{Style.RESET_ALL} ")
return
print(f"{Fore.CYAN}Found {len(moved_folders)} moved_subtitles folder(s).{Style.RESET_ALL}\n")
deleted_count = 0
skipped_count = 0
for moved_folder in moved_folders:
parent_dir = moved_folder.parent
# Find subtitle files in moved_subtitles folder
moved_subs = list(moved_folder.glob("*.srt")) + list(moved_folder.glob("*.ass"))
if not moved_subs:
# Empty folder, safe to delete
print(f"{Fore.YELLOW}• {parent_dir.name}/moved_subtitles/ (empty){Style.RESET_ALL}")
try:
import shutil
shutil.rmtree(moved_folder)
print(f" {Fore.GREEN}✓ Deleted{Style.RESET_ALL}\n")
deleted_count += 1
except Exception as e:
print(f" {Fore.RED}✗ Error: {str(e)}{Style.RESET_ALL}\n")
skipped_count += 1
continue
# Detect languages in moved_subtitles folder
moved_langs = set()
for sub_file in moved_subs:
for lang in languages:
if f".{lang}." in sub_file.name.lower():
moved_langs.add(lang)
break
if not moved_langs:
# Can't detect languages, assume safe to delete
print(f"{Fore.YELLOW}• {parent_dir.name}/moved_subtitles/ ({len(moved_subs)} subtitle(s), no configured languages detected){Style.RESET_ALL}")
try:
import shutil
shutil.rmtree(moved_folder)
print(f" {Fore.GREEN}✓ Deleted{Style.RESET_ALL}\n")
deleted_count += 1
except Exception as e:
print(f" {Fore.RED}✗ Error: {str(e)}{Style.RESET_ALL}\n")
skipped_count += 1
continue
# Check if parent directory has external subtitles for all moved languages
missing_langs = []
for lang in moved_langs:
# Look for .srt files with language code in parent directory
external_subs = list(parent_dir.glob(f"*.{lang}.srt")) + list(parent_dir.glob(f"*.{lang}.ass"))
if not external_subs:
missing_langs.append(lang)
# Display folder info
lang_list = ", ".join(sorted(moved_langs))
print(f"{Fore.CYAN}• {parent_dir.name}/moved_subtitles/{Style.RESET_ALL}")
print(f" Languages in moved_subtitles: {Fore.YELLOW}{lang_list}{Style.RESET_ALL}")
if missing_langs:
missing_list = ", ".join(sorted(missing_langs))
print(f" {Fore.RED}[WARNING] Missing in parent folder: {missing_list}{Style.RESET_ALL}")
confirm = input(f" Delete anyway? (y/n): ").strip().lower()
if confirm == 'y':
try:
import shutil
shutil.rmtree(moved_folder)
print(f" {Fore.GREEN}✓ Deleted{Style.RESET_ALL}\n")
deleted_count += 1
except Exception as e:
print(f" {Fore.RED}✗ Error: {str(e)}{Style.RESET_ALL}\n")
skipped_count += 1
else:
print(f" {Fore.YELLOW}○ Skipped{Style.RESET_ALL}\n")
skipped_count += 1
else:
print(f" {Fore.GREEN}✓ All languages present in parent folder{Style.RESET_ALL}")
try:
import shutil
shutil.rmtree(moved_folder)
print(f" {Fore.GREEN}✓ Deleted{Style.RESET_ALL}\n")
deleted_count += 1
except Exception as e:
print(f" {Fore.RED}✗ Error: {str(e)}{Style.RESET_ALL}\n")
skipped_count += 1
# Summary
print(f"\n{Style.BRIGHT}{Fore.CYAN}Summary:{Style.RESET_ALL}")
print(f" {Fore.GREEN}Deleted: {deleted_count}{Style.RESET_ALL}")
print(f" {Fore.YELLOW}Skipped: {skipped_count}{Style.RESET_ALL}")
input(f"\n{Fore.YELLOW}Press Enter to return to the menu...{Style.RESET_ALL} ")
except Exception as e:
utils.clear_and_print_ascii(BANNER_LINE)
print(f"{Style.BRIGHT}{Fore.RED}[Error]{Style.RESET_ALL}")
print(f"{Fore.RED}An error occurred: {str(e)}{Style.RESET_ALL}")
input(f"\n{Fore.YELLOW}Press Enter to continue...{Style.RESET_ALL} ")
def print_instructions_page(page):
"""Display specified page of usage instructions.
Shows a specific page of the instruction manual (pages 1-5).
"""
utils.clear_and_print_ascii(BANNER_LINE)
if page == 1:
print(f"{Style.BRIGHT}{Fore.CYAN}[1/5] Installing, configuring and running Subservient{Style.RESET_ALL}\n")
print(f"{Fore.GREEN}1.{Style.RESET_ALL} Start by selecting option {Fore.YELLOW}'4'{Style.RESET_ALL} in the menu.")
print(f" This will check if all required packages are installed and working.")
print(f" If there are any issues, consult the README, ask ChatGPT, or open an issue on GitHub.")
print(f" All errors and test results are shown in the terminal and saved in the logs folder.\n")
elif page == 2:
print(f"{Style.BRIGHT}{Fore.CYAN}[2/5] Configuration: .config and OpenSubtitles{Style.RESET_ALL}\n")
print(f"{Fore.GREEN}2.{Style.RESET_ALL} Open the {Fore.YELLOW}.config{Style.RESET_ALL} file in your Subservient folder.")
print(f" Fill in all required settings. The most important are:")
print(f" - {Fore.CYAN}OpenSubtitles API key{Style.RESET_ALL}")
print(f" - {Fore.CYAN}Username and password{Style.RESET_ALL}\n")
print(f" You need to create an OpenSubtitles account and then create a 'consumer' (API application).")
print(f" Detailed instructions for this are in the README.")
print(f" Adjust other settings as needed for your preferences.\n")
elif page == 3:
print(f"{Style.BRIGHT}{Fore.CYAN}[3/5] Placing subordinate.py and processing modes{Style.RESET_ALL}\n")
print(f"{Fore.GREEN}3.{Style.RESET_ALL} Move {Fore.YELLOW}subordinate.py{Style.RESET_ALL} to the folder you want to process.")
print(f" There are two modes:")
print(f" - {Fore.CYAN}Single file processing:{Style.RESET_ALL} Place subordinate.py in a folder with one video file.")
print(f" - {Fore.CYAN}Batch processing:{Style.RESET_ALL} Place subordinate.py in a folder with multiple subfolders, each containing a video file.")
print(f" If there is a video file next to subordinate.py, single file mode is used. Otherwise, batch mode is used.\n")
print(f" {Fore.YELLOW}In your .config, the setting 'series_mode' is available.\n It is 'false' by default, but set it to 'true' if you want to process TV series.{Style.RESET_ALL}")
print(f" {Fore.LIGHTRED_EX}Do not mix single movies and series in one run, as this WILL cause unwanted results!{Style.RESET_ALL}\n")
print(f" So make sure that your video files are correctly organized before starting.\n")
elif page == 4:
print(f"{Style.BRIGHT}{Fore.CYAN}[4/5] Running Subservient and pre-flight checklist{Style.RESET_ALL}\n")
print(f"{Fore.GREEN}4.{Style.RESET_ALL} Once subordinate.py is in the right place, run it and choose {Fore.YELLOW}'1'{Style.RESET_ALL} to start.")
print(f" You will see a pre-flight checklist with all important variables and settings.")
print(f" Carefully check these before continuing.")
print(f" If everything looks correct, you can proceed.\n")
print(f" Subservient will now go through the Extraction, Acquisition and Synchronisation phase.")
print(f" If everything is configured correctly, this process is automatic for the most part.")
print(f" Only when something is not clear for Subservient, will it start asking you what to do.\n")
elif page == 5:
print(f"{Style.BRIGHT}{Fore.CYAN}[5/5] Tips & Troubleshooting{Style.RESET_ALL}\n")
print(f"{Fore.GREEN}*{Style.RESET_ALL} If you move subordinate.py, run it again in the new folder to update the location.")
print(f"{Fore.GREEN}*{Style.RESET_ALL} All logs and outputs are saved in the main Subservient folder.")
print(f"{Fore.GREEN}*{Style.RESET_ALL} If you have issues, check your .config and requirements first.")
print(f"{Fore.GREEN}*{Style.RESET_ALL} For advanced options, see the README or .config comments.")
print(f"{Fore.GREEN}*{Style.RESET_ALL} Still stuck? Open an issue on GitHub or ask ChatGPT for help.\n")
print(f"{Fore.LIGHTWHITE_EX}Subservient is free and open source.\nIf you appreciate the project, you can support future development via Buy Me a Coffee:{Style.RESET_ALL}")
print(f"{Fore.CYAN}https://buymeacoffee.com/nexigen{Style.RESET_ALL}\n")
print(f"{Fore.LIGHTWHITE_EX}I can't always offer one-on-one support to everyone, but donors are welcome to join my Discord for extra help.\nDonors can also get my builds/patches earlier (or as soon as I commit them) as an extra 'thank you'.\nMany thanks for understanding, for donating, and heck.. even just for using Subservient.{Style.RESET_ALL}")
print(f"{Fore.LIGHTMAGENTA_EX}-Nexigen")
def show_instructions():
"""Show paginated instructions for using Subservient.
Interactive instruction manual with navigation between pages allowing
users to go through 5 pages of setup and usage instructions.
"""
page = 1
total_pages = 5
while True:
print_instructions_page(page)
if page < total_pages:
nav = input(f"\n{Style.BRIGHT}{Fore.YELLOW}Press Enter for next page, or {Fore.CYAN}b{Style.RESET_ALL}{Style.BRIGHT}{Fore.YELLOW} to go back to the main menu:{Style.RESET_ALL} ").strip().lower()
if nav == 'b':
break
page += 1
else:
input(f"\n{Style.BRIGHT}{Fore.YELLOW}Press Enter to return to the main menu.{Style.RESET_ALL} ")
break
utils.clear_and_print_ascii(BANNER_LINE)
print(f"{Style.BRIGHT}{Fore.BLUE}[Subservient]{Style.RESET_ALL} This is the central script for Subservient subtitle automation.")
print(f"{Style.BRIGHT}{Fore.BLUE}[Subservient]{Style.RESET_ALL} My anchor location is: {Fore.YELLOW}{Path(__file__).resolve().parent}{Style.RESET_ALL}\n")
print(f"{Style.DIM}When unsure how to proceed, you can consult the README file or press option '3' for guidance.{Style.RESET_ALL}")
print_main_menu()
def reconstruct_config():
"""Interactive configuration file reconstruction with user prompts.
Creates a new .config file with default template and prompts user for
confirmation if existing config file is found.
"""
utils.clear_and_print_ascii(BANNER_LINE)
print(f"{Style.BRIGHT}{Fore.YELLOW}You can use this option to reconstruct the .config file if your current config is missing or not working properly.{Style.RESET_ALL}\n")
print(f"{Fore.WHITE}A new .config file will be created in the same directory as this script ({Path(__file__).parent}).{Style.RESET_ALL}")
print(f"{Fore.WHITE}To use it, you must move this .config file back to the main Subservient folder if it is not already there.{Style.RESET_ALL}")
print(f"{Fore.LIGHTRED_EX}All settings in the new .config will need to be re-entered manually!{Style.RESET_ALL}\n")
print(f"{Fore.GREEN}1{Style.RESET_ALL} = Create new .config file now")
print(f"{Fore.RED}2{Style.RESET_ALL} = Return to main menu\n")
choice = input(f"Make a choice [{Fore.GREEN}1{Style.RESET_ALL}/{Fore.RED}2{Style.RESET_ALL}]: ").strip()
if choice != "1":
print(f"{Fore.YELLOW}Config reconstruction cancelled. Returning to main menu.{Style.RESET_ALL}")
input("Press Enter to continue...")
print_full_main_menu()
return
config_path = Path(__file__).parent / '.config'
if config_path.exists():
print(f"{Fore.YELLOW}A .config file already exists at: {config_path}{Style.RESET_ALL}")
confirm = input(f"{Fore.RED}Overwrite existing .config? (y/n): {Style.RESET_ALL}").strip().lower()
if confirm != 'y':
print(f"{Fore.GREEN}Config reconstruction cancelled.{Style.RESET_ALL}")
input("Press Enter to return to the main menu...")
print_full_main_menu()
return
ascii_lines = utils.ASCII_ART.splitlines()
if ascii_lines:
ascii_lines[0] = ' ' + ascii_lines[0].lstrip()
ascii_block = '\n'.join(ascii_lines)
config_template = f'''{ascii_block}
[.CONFIG FILE]
[SETUP]
# === Subtitle Acquisition Script Setup ===
# API_KEY: Your OpenSubtitles consumer API key
# USERNAME: Your OpenSubtitles username
# PASSWORD: Your OpenSubtitles password
# API_URL: OpenSubtitles API endpoint (only rename when OpenSubtitles changed their API URL)
api_key=
username=
password=
api_url= https://api.opensubtitles.com/api/v1
# - LANGUAGES: Comma-separated list of subtitle languages to download (e.g. nl,en).
# These are the languages for which subtitles will be searched and downloaded.
# This setting does NOT decide what happens to extracted languages not in this list, preserve_forced_subtitles and preserve_unwanted_subtitles do.
languages= en
# - AUDIO_TRACK_LANGUAGES: Comma-separated list of audio track languages to keep inside video files (e.g. nl,en,ja). ('undefined' tracks are always kept).
# Tracks with a language not in the list are removed. Highly recommended to keep english in there, as 95% of all mainstream movies have english tracks only.
# Set to 'ALL' to disable all audio track processing and keep all audio tracks unchanged (e.g. audio_track_languages = ALL)
audio_track_languages= en,ja
# - ACCEPT_OFFSET_THRESHOLD: If a subtitle synchronisation is below this threshold, then the subtitle will be accepted without needing further manual user verification.
# Generally speaking: A higher setting saves time, but may result in poorer syncs being accepted unconditionally.
# A lower setting leads to only very excellently synced subtittles getting through.
# Try finding your ideal balance by testing it on videos. I personally find that somewhere between 0.05 and 0.1 strikes a good balance
accept_offset_threshold= 0.05
# - REJECT_OFFSET_THRESHOLD: If a subtitle synchronisation is above this threshold, then the subtitle will be rejected, meaning it will be marked as DRIFT and will be discarded later.
# Generally speaking: Higher settings will lead to less rejections, but more manual checkups for you to go through.
# Lower settings will lead to very fast rejections, making videos run out of subtitle candidates very quickly.
# NOTE: Increasing the threshold is usually recommended when you notice that many movies can't find good subtitle candidates anymore.
# I personally find that around 2 to 2.5 seconds strikes a good balance.
# You could try up to 4 seconds if you want to be more lenient, but I would not recommend going any higher, unless some videos are consistently rejected.
reject_offset_threshold= 2.5
# - SERIES_MODE: If true, treat all videos in the same folder as episodes of a TV series.
# If false, only the largest video file in each folder is processed (movie mode).
series_mode= false
# - DELETE_EXTRA_VIDEOS: If true, all extra video files in a folder will be permanently deleted.
# If false, extra video files will be moved to a folder named by EXTRAS_FOLDER_NAME.
# This setting is ignored if series_mode is true (in series mode, all videos are kept).
# - EXTRAS_FOLDER_NAME: Name of the folder where extra video files are moved if DELETE_EXTRA_VIDEOS is false.
delete_extra_videos= false
extras_folder_name= extras
# - PRESERVE_FORCED_SUBTITLES: If true, forced subtitle tracks will be preserved and not replaced by full subtitles.
# Forced subtitles are typically used for foreign dialogue in otherwise native-language movies.
# If false, forced subtitles will be treated like regular subtitles and may be replaced.
# - PRESERVE_UNWANTED_SUBTITLES: If true, all internal and external subtitle tracks will be kept, even those not in the wanted languages list.
# If false, subtitle tracks not in the wanted languages will be removed during cleanup.
# This only affects cleanup behavior - the languages list still controls which subtitles are downloaded and synchronized.
preserve_forced_subtitles= false
preserve_unwanted_subtitles= false
# - PAUSE_SECONDS: Number of seconds to pause between phases, breaks, and other script waits.
# If you don't mind about reading what happens in the terminal, a lower value can be set. Example: 5 means a 5 second pause between phases and after summaries. Average speed = 5.
pause_seconds= 5
# - MAX_SEARCH_RESULTS: Maximum number of subtitle search results to consider per movie (e.g. 10).
# Increasing MAX_SEARCH_RESULTS can help find more options, but may slow down processing.
# When having a low download limit and many videos to sync, it's strongly recommended to not go higher than 12. As a VIP you can easily go for 20 or more.
max_search_results= 10
# - TOP_DOWNLOADS: Number of subtitles to download and test per batch.
# Keeping TOP_DOWNLOADS low preserves your daily download limit by first testing one batch before downloading another batch.
# If you need to sync many videos, take 2 to 4 as a maximum. When you have 1000 downloads a day, you could set this to, say, 5-10, for significantly faster processing.
top_downloads= 3
# - DOWNLOAD_RETRY_503: Number of retry attempts for HTTP 503 Service Unavailable errors during subtitle downloads.
# 503 errors typically indicate OpenSubtitles servers are temporarily overloaded. Higher values increase chance of success but slow down processing.
# Recommended: 6 for good balance between success rate and speed. Set to 3 for faster processing, 10 for maximum persistence.
download_retry_503= 6
# - SKIP_DIRS: Comma-separated list of directory names to skip when scanning for videos (e.g. extras,trailers,samples).
# These directories will be ignored during video discovery in both movie and series mode. Use lowercase names, matching is case-insensitive.
# Common examples: extras, trailers, samples, bonus.
skip_dirs= new folder,nieuwe map,extra,extra's,extras,featurettes,bonus,bonusmaterial,bonus_material,behindthescenes,behind_the_scenes,deletedscenes,deleted_scenes,interviews,makingof,making_of,scenes,trailer,trailers,sample,samples,other,misc,specials,special_features,documentary,docs,docu,promo,promos,bloopers,outtakes
# - UNWANTED_TERMS: Comma-separated list of words/terms that should be filtered from subtitle search results.
# For example, a search can be 'Lord of the Rings 2001 [h.265 HEVC 10 bit]'.
# The whole latter part would then be removed, so that 'The lord of the Rings 2001' remains, giving a good search query.
# Legal disclaimer: These filters clean technical metadata from filenames regardless of source.
# Subservient is designed for use with content you legally own or have rights to process.
# The inclusion of various format and distribution tags serves technical interoperability purposes only.
UNWANTED_TERMS= sample,cam,ts,workprint,unrated,uncut,720p,1080p,2160p,480p,4k,uhd,imax,eng,ita,jap,hindi,web,webrip,web-dl,bluray,brrip,bdrip,dvdrip,hdrip,hdtv,remux,x264,x265,h.264,h.265,hevc,avc,hdr,hdr10,hdr10+,dv,dolby.vision,sdr,10bit,8bit,ddp,dd+,dts,aac,ac3,eac3,truehd,atmos,flac,5.1,7.1,2.0,yts,yts.mx,yify,rarbg,fgt,galaxyrg,cm8,evo,sparks,drones,amiable,kingdom,tigole,chd,ddr,hdchina,cinefile,ettv,eztv,aXXo,maven,fitgirl,skidrow,reloaded,codex,cpy,conspir4cy,hoodlum,hive-cm8,extras,final.cut,open.matte,hybrid,version,v2,proper,limited,dubbed,subbed,multi,dual.audio,complete.series,complete.season,Licdom,ac,sub,nl,en,ita,eng,subs,rip,h265,xvid,mp3,mp4,avi,Anime Time,[Anime Time]
# - RUN_COUNTER: used to count how many full runs have been made. Also used to organize logfiles
# Don't change if you don't need to, as it may result in overwriting existing logs
run_counter= 0
# === END OF SETUP ===
# ------------------------------------------------------------
# Everything below is managed automatically by the application.
# Only change this if you know what you are doing!
[RUNTIME]
'''
with open(config_path, "w", encoding="utf-8") as f:
f.write(config_template)
print(f"{Fore.GREEN}New .config file created at: {config_path}{Style.RESET_ALL}\n")
input("Press Enter to return to the main menu...")
print_full_main_menu()
def import_utils():
"""Import utils module and handle missing file error gracefully.
Dynamically imports the utils module from the registered path and handles
cases where utils.py cannot be found via pathfile. Also handles location mismatches.
"""
config_dir = Path(user_config_dir()) / "Subservient"
pathfile = config_dir / "Subservient_pathfiles"
utils_path = None
if pathfile.exists():
try:
with open(pathfile, encoding="utf-8") as f:
for line in f:
if line.startswith("utils_path="):
utils_path = line.strip().split("=", 1)[1]
break
except Exception:
pass
if utils_path and Path(utils_path).exists():
try:
spec = importlib.util.spec_from_file_location("utils", utils_path)
utils = importlib.util.module_from_spec(spec)
spec.loader.exec_module(utils)
return utils
except Exception:
pass
current_dir_utils = Path(__file__).parent / "utils.py"
if current_dir_utils.exists():
try:
spec = importlib.util.spec_from_file_location("utils", str(current_dir_utils))
utils = importlib.util.module_from_spec(spec)
spec.loader.exec_module(utils)
return utils
except Exception:
pass
print(f"{Fore.RED}{Style.BRIGHT}[SETUP ERROR]{Style.RESET_ALL} Cannot continue - required files are missing.\n")
print(f"{Fore.YELLOW}Could not locate utils.py in the expected locations:{Style.RESET_ALL}")
print(f" - Pathfile location: {utils_path if utils_path else 'Not found in configuration'}")
print(f" - Current directory: {current_dir_utils}")
print(f"\n{Fore.WHITE}This usually happens when:{Style.RESET_ALL}")
print(f" 1. subordinate.py was moved without the other Subservient files")
print(f" 2. The Subservient installation is incomplete or corrupted")
print(f"\n{Fore.WHITE}To resolve this issue:{Style.RESET_ALL}")
print(f" 1. Ensure subordinate.py is in the main Subservient folder")
print(f" 2. Verify all required files are present and intact")
print(f" 3. Run subordinate.py from the main folder to complete setup")
print(f"\n{Fore.WHITE}If the problem persists, consider re-downloading Subservient from the official repository.{Style.RESET_ALL}")
input("\nPress Enter to exit...")
sys.exit(1)
def ensure_initial_setup():
"""Ensure initial Subservient setup is complete with pathfiles and config.
Verifies that all required Subservient scripts are present and registers their paths.
Creates pathfile with script locations for cross-module access and exits with error if required scripts are missing.
Also detects if subordinate.py has been moved and requires re-setup.
"""
required_keys = ["subservient_anchor", "subordinate_path", "extraction_path", "acquisition_path", "synchronisation_path", "utils_path"]
required_scripts = ["subordinate.py", "extraction.py", "acquisition.py", "synchronisation.py", "utils.py"]
config_dir = Path(user_config_dir()) / "Subservient"
config_dir.mkdir(parents=True, exist_ok=True)
pathfile = config_dir / "Subservient_pathfiles"
current_subordinate_path = str(Path(__file__).resolve())
def valid_pathfile():
"""Check if pathfile exists and contains all required keys."""
if not pathfile.exists():
return False
lines = pathfile.read_text(encoding="utf-8").splitlines()
kv = {k.strip(): v.strip() for l in lines if '=' in l for k, v in [l.split('=', 1)]}
return all(k in kv and kv[k] for k in required_keys)
def check_subservient_files_location():
"""Check if the other Subservient files are still in their expected locations."""
if not pathfile.exists():
return True
try:
lines = pathfile.read_text(encoding="utf-8").splitlines()
essential_files = ["extraction_path", "acquisition_path", "synchronisation_path", "utils_path"]
for line in lines:
for file_key in essential_files:
if line.startswith(f"{file_key}="):
expected_path = Path(line.split("=", 1)[1].strip())
if not expected_path.exists():
return False
return True
except Exception:
return False
if pathfile.exists() and not check_subservient_files_location():
print(f"{Fore.RED}{Style.BRIGHT}[SETUP ERROR]{Style.RESET_ALL} Subservient files location mismatch detected!\n")
print(f"{Fore.YELLOW}It appears that the Subservient folder has been moved or some files are missing.{Style.RESET_ALL}")
try:
lines = pathfile.read_text(encoding="utf-8").splitlines()
essential_files = ["extraction_path", "acquisition_path", "synchronisation_path", "utils_path"]
missing_files = []
for line in lines:
for file_key in essential_files:
if line.startswith(f"{file_key}="):
expected_path = Path(line.split("=", 1)[1].strip())
if not expected_path.exists():
missing_files.append(f"{file_key.replace('_path', '.py')}: {expected_path}")
if missing_files:
print(f"{Fore.YELLOW}Missing files:{Style.RESET_ALL}")
for missing in missing_files:
print(f" - {Fore.WHITE}{missing}{Style.RESET_ALL}")
except Exception:
pass
print(f"\n{Fore.WHITE}{Style.BRIGHT}SOLUTION:{Style.RESET_ALL}")
print(f"{Fore.GREEN}🔧 If you moved the entire Subservient folder:{Style.RESET_ALL}")
print(f" 1. Put subordinate.py back in the main Subservient folder (where all other .py files are)")
print(f" 2. Run subordinate.py once from that location to complete re-setup")
print(f" 3. After setup completes, you can move subordinate.py anywhere again for video processing")
print(f"\n{Fore.YELLOW}🔍 If individual files are missing or corrupted:{Style.RESET_ALL}")
print(f" 1. Remove the current Subservient folder. If need be, you can make a backup of your .config file.")
print(f" 2. Re-download Subservient from the official GitHub repository")
print(f" 3. Ensure all required .py files are present in the main folder")
print(f"\n{Fore.LIGHTBLUE_EX}📂 Current subordinate.py location: {Fore.WHITE}{Path(__file__).resolve().parent}{Style.RESET_ALL}")
try:
pathfile.unlink()
print(f"\n{Fore.CYAN}✅ Old pathfile removed - fresh setup will run when you restart from main folder.{Style.RESET_ALL}")
except Exception:
pass
input("\nPress Enter to exit...")