-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathacquisition.py
More file actions
2726 lines (2490 loc) · 155 KB
/
acquisition.py
File metadata and controls
2726 lines (2490 loc) · 155 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
def check_required_packages():
"""Check if all required packages are installed and show install instructions if missing."""
required_packages = ["colorama", "platformdirs", "requests"]
missing = []
for package in required_packages:
try:
__import__(package)
except ImportError:
missing.append(package)
if missing:
print("\n" + "="*60)
print(" SUBSERVIENT ACQUISITION - 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 acquisition.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 pathlib import Path
import requests
import re
import json
import time
from colorama import Fore, Style
import datetime
from platformdirs import user_config_dir
from utils import ASCII_ART, clear_and_print_ascii, get_skip_dirs_from_config, has_strict_series_naming_pattern, extract_sxxexx_code
from opensubtitles_hash import calculate_hash
SNAPSHOT_DIR = Path(__file__).parent.resolve()
BANNER_LINE = f" {Style.BRIGHT}{Fore.RED}[Phase 3/4]{Style.RESET_ALL} Subtitle Acquisition"
CONFIG_PATH = SNAPSHOT_DIR / '.config'
run_counter = 1
if CONFIG_PATH.exists():
with CONFIG_PATH.open(encoding='utf-8') as f:
for line in f:
if line.strip().lower().startswith('run_counter') and '=' in line:
try:
run_counter = int(line.split('=', 1)[1].strip())
except Exception:
run_counter = 1
break
LOGS_DIR = SNAPSHOT_DIR / 'logs' / f'Subservient-run-{run_counter}'
LOGS_DIR.mkdir(exist_ok=True)
existing_log = None
for fname in LOGS_DIR.iterdir():
if fname.name.startswith('acquisition_log') and fname.name.endswith('.txt'):
existing_log = fname
break
if existing_log:
LOG_FILE = existing_log
with LOG_FILE.open('r+', encoding='utf-8') as f:
content = f.read()
part_count = content.count('Acquisition - part') + 1
if f.tell() > 0:
f.write('\n')
f.write(f'Acquisition - part {part_count}\n')
else:
log_time = datetime.datetime.now().strftime('%d-%m-%Y_%H.%M.%S')
LOG_FILE = LOGS_DIR / f"acquisition_log_{log_time}.txt"
with LOG_FILE.open('a', encoding='utf-8') as f:
f.write(f'Acquisition - part 1\n')
ANSI_ESCAPE = re.compile(r'\x1b\[[0-9;]*m|\033\[[0-9;]*m')
def strip_ansi(text):
"""Remove ANSI color codes from text."""
return ANSI_ESCAPE.sub('', text)
def acq_tag():
"""Return formatted acquisition tag for console output."""
return f"{Style.BRIGHT}{Fore.BLUE}[Acquisition]{Style.RESET_ALL}"
def exit_with_prompt(message="Press any key to exit..."):
"""Display message and wait for user input before exiting."""
try:
input(f"{acq_tag()} {message}")
except EOFError:
os.system("pause")
sys.exit(1)
with LOG_FILE.open('a+', encoding='utf-8') as f:
f.write(strip_ansi(ASCII_ART) + '\n')
banner = BANNER_LINE.replace('[Phase 3/4]', f'{Style.BRIGHT}{Fore.RED}[Phase 3/4]{Style.RESET_ALL}{Style.BRIGHT}')
f.write(strip_ansi(banner) + '\n\n')
def print_and_log(msg, end='\n'):
"""Print message to console and write to log file."""
print(msg, end=end)
with LOG_FILE.open('a', encoding='utf-8') as f:
f.write(strip_ansi(msg) + ('' if end == '' else end))
def print_and_log_colored(msg, color=Fore.WHITE, end='\n'):
"""Print colored message to console and log plain text to file."""
print(f"{color}{msg}{Style.RESET_ALL}", end=end)
with open(LOG_FILE, 'a', encoding='utf-8') as f:
f.write(strip_ansi(msg) + ('' if end == '' else end))
clear_and_print_ascii(BANNER_LINE)
def get_subservient_anchor():
"""Get the Subservient anchor directory from pathfiles config."""
config_dir = Path(user_config_dir()) / "Subservient"
pathfile = config_dir / "Subservient_pathfiles"
if not pathfile.exists():
clear_and_print_ascii(BANNER_LINE)
print_and_log(f"\033[1;31m[ERROR]\033[0m Subservient_pathfiles not found in your user config directory. Please run subordinate.py first.")
exit_with_prompt()
with open(pathfile, "r", encoding="utf-8") as f:
for line in f:
if line.startswith("subservient_anchor="):
return Path(line.split("=", 1)[1].strip())
clear_and_print_ascii(BANNER_LINE)
print_and_log(f"\033[1;31m[ERROR]\033[0m subservient_anchor not found in Subservient_pathfiles. Please run subordinate.py again.")
exit_with_prompt()
clear_and_print_ascii(BANNER_LINE)
anchor_dir = get_subservient_anchor()
os.chdir(anchor_dir)
__file__ = str((anchor_dir / Path(__file__).name).resolve())
CONFIG_PATH = SNAPSHOT_DIR / '.config'
missing_queries = []
REQUIRED_SETUP_KEYS = [
'api_url',
'api_key',
'username',
'password',
'languages',
'top_downloads',
'series_mode',
]
def parse_bool(val):
"""Convert string value to boolean."""
return str(val).strip().lower() in ("true", "1", "yes", "on")
def read_setup_from_config():
"""Read configuration settings from .config file and validate required keys."""
if not CONFIG_PATH.exists():
clear_and_print_ascii(BANNER_LINE)
print_and_log(f"\033[1;31m[ERROR]\033[0m .config not found!\n\nCreate a valid config or reset it via subordinate.py.")
exit_with_prompt()
lines = CONFIG_PATH.read_text(encoding='utf-8').splitlines()
setup = {}
in_setup = False
for line in lines:
if line.strip().lower() == '[setup]':
in_setup = True
continue
if in_setup:
if line.strip().startswith('[') and line.strip().lower() != '[setup]':
break
if line.strip() and not line.strip().startswith('#'):
if '=' in line:
key, value = line.split('=', 1)
setup[key.strip()] = value.strip().strip('"')
missing = [k for k in REQUIRED_SETUP_KEYS if k not in setup or not setup[k]]
if missing:
clear_and_print_ascii(BANNER_LINE)
print_and_log(f"\033[1;31m[ERROR]\033[0m The following variables are missing or have no value in the [SETUP] section of .config:\n")
for k in missing:
print_and_log(f" - {k}")
print_and_log("\nPlease fix the config file or reconstruct the whole config using subordinate.py.")
exit_with_prompt()
setup['series_mode'] = parse_bool(setup['series_mode'])
return setup
setup = read_setup_from_config()
PAUSE_SECONDS = float(setup.get("pause_seconds", 3))
API_URL = setup['api_url']
API_KEY = setup['api_key']
USERNAME = setup['username']
PASSWORD = setup['password']
LANGUAGES = [lang.strip() for lang in setup['languages'].split(',') if lang.strip()]
MAX_SEARCH_RESULTS = int(setup.get('max_search_results', 50))
TOP_DOWNLOADS = int(setup['top_downloads'])
DOWNLOAD_RETRY_503 = int(setup.get('download_retry_503', 6))
SERIES_MODE = setup['series_mode']
USE_MOVIE_HASH = setup.get('use_movie_hash', 'true').lower() in ('true', '1', 'yes', 'on')
LAST_RESORT_SEARCH = setup.get('last_resort_search', 'false').lower() in ('true', '1', 'yes', 'on')
def detect_subtitle_folder(video_folder: Path, season_code: str, language: str):
"""
Detect subtitle folder for specific season and language (SUBTITLES.Sxx.LANG format).
Returns folder path or None.
"""
if not video_folder.exists():
return None
# Look for SUBTITLES.Sxx.LANG folders or ZIP files (case insensitive)
target_folder_name = f"subtitles.{season_code}.{language}".lower()
target_zip_name = f"subtitles.{season_code}.{language}.zip".lower()
for item in video_folder.iterdir():
if item.is_dir() and item.name.lower() == target_folder_name:
return item
elif item.is_file() and item.name.lower() == target_zip_name:
return item
return None
def validate_season_episodes_match(video_folder: Path, season_code: str):
"""
Validate that video files match the detected season code.
Returns True if valid, False if mismatch found.
"""
# Get all video files in the folder
video_extensions = {'.mkv', '.mp4', '.avi', '.m4v', '.mov', '.wmv'}
video_files = [f for f in video_folder.iterdir()
if f.is_file() and f.suffix.lower() in video_extensions]
if not video_files:
return True # No videos to validate
mismatched_files = []
for video_file in video_files:
# Check if file has series naming pattern
if has_strict_series_naming_pattern(video_file.name):
# Extract season code from video filename (returns SxxExx format)
video_sxxexx_code = extract_sxxexx_code(video_file.name)
if video_sxxexx_code:
# Extract just the season part (first 3 characters: "S01" from "S01E01")
video_season_part = video_sxxexx_code[:3] # "S01E01" -> "S01"
# Compare season parts only (case insensitive)
if video_season_part.upper() != season_code.upper():
mismatched_files.append((video_file.name, video_season_part, season_code))
if mismatched_files:
# Display detailed error message
clear_and_print_ascii(BANNER_LINE)
print_and_log(f"{Fore.RED}{Style.BRIGHT}[ERROR] Season Code Mismatch Detected!{Style.RESET_ALL}\n")
print_and_log(f"A subtitle download folder was found, but the video files don't match the season code:\n")
print_and_log(f" {Fore.YELLOW}Season folder detected:{Style.RESET_ALL} SUBTITLES.{season_code}")
print_and_log(f" {Fore.YELLOW}Expected video pattern:{Style.RESET_ALL} *{season_code}E*\n")
print_and_log(f"{Fore.RED}Mismatched files found:{Style.RESET_ALL}")
for filename, video_season, expected_season in mismatched_files:
print_and_log(f" - {filename}")
print_and_log(f" {Fore.RED}Found season:{Style.RESET_ALL} {video_season} {Fore.RED}Expected:{Style.RESET_ALL} {expected_season}")
print_and_log(f"\n{Fore.YELLOW}Possible solutions:{Style.RESET_ALL}")
print_and_log(f" 1. Rename the SUBTITLES folder to match your video files")
print_and_log(f" 2. Move video files to the correct season folder")
print_and_log(f" 3. Remove the SUBTITLES folder if not needed\n")
print_and_log(f"{Fore.RED}Subservient in TV-Series mode cannot proceed with mismatched season codes.{Style.RESET_ALL}")
exit_with_prompt("Press Enter to exit...")
return False
return True
def check_for_language_mismatch_error(video_folder: Path, season_code: str, requested_language: str):
"""
Check if there are SUBTITLES folders that are improperly configured.
If found, show error and exit.
"""
# Look for ANY SUBTITLES folders or ZIP files
subtitle_pattern = f"subtitles.{season_code}.".lower()
old_pattern_exact = f"subtitles.{season_code}".lower() # Exact match for season without language
found_folders = []
incomplete_folders = []
wrong_season_folders = []
for item in video_folder.iterdir():
item_name_lower = item.name.lower()
if (item.is_dir() or item.name.lower().endswith('.zip')):
# Check if this is any SUBTITLES folder
if item_name_lower.startswith('subtitles.s') and ('s01' in item_name_lower or 's02' in item_name_lower or 's03' in item_name_lower or 's04' in item_name_lower or 's05' in item_name_lower):
# Extract season from folder name
season_match = re.search(r'subtitles\\.(s\\d{2})', item_name_lower)
if season_match:
folder_season = season_match.group(1).upper()
if folder_season != season_code.upper():
# Wrong season detected
wrong_season_folders.append((item.name, folder_season))
else:
# Correct season, check language
if item.is_dir() and item_name_lower == old_pattern_exact:
incomplete_folders.append(item.name)
elif item.is_file() and item_name_lower == f"{old_pattern_exact}.zip":
incomplete_folders.append(item.name)
elif item_name_lower.startswith(subtitle_pattern):
# Extract language part
if item.is_dir():
lang_part = item.name[len(f"SUBTITLES.{season_code}."):]
else: # ZIP file
lang_part = item.name[len(f"SUBTITLES.{season_code}."):-4] # Remove .zip
if lang_part and lang_part.upper() != requested_language.upper():
found_folders.append((item.name, lang_part.upper()))
if wrong_season_folders or incomplete_folders or found_folders:
# Display error message
clear_and_print_ascii(BANNER_LINE)
print_and_log(f"{Fore.RED}{Style.BRIGHT}[ERROR] Subtitle Folder Configuration Error!{Style.RESET_ALL}\\n")
if wrong_season_folders:
print_and_log(f"Subtitle folder(s) found with wrong season code:\\n")
print_and_log(f"{Fore.RED}Wrong season folders:{Style.RESET_ALL}")
for folder_name, folder_season in wrong_season_folders:
print_and_log(f" - {folder_name} (Found: {folder_season}, Expected: {season_code})")
print_and_log(f"\\n{Fore.YELLOW}Expected season:{Style.RESET_ALL} {season_code}")
print_and_log(f"{Fore.YELLOW}Video files contain:{Style.RESET_ALL} {season_code}E01, {season_code}E02, etc.\\n")
if incomplete_folders:
print_and_log(f"Subtitle folder(s) found without language specification:\\n")
print_and_log(f"{Fore.YELLOW}Incomplete folders:{Style.RESET_ALL}")
for folder_name in incomplete_folders:
print_and_log(f" - {folder_name} (Missing language specification)")
print_and_log(f"\\n{Fore.YELLOW}Required format:{Style.RESET_ALL} SUBTITLES.{season_code}.LANGUAGE")
print_and_log(f"{Fore.YELLOW}Example:{Style.RESET_ALL} SUBTITLES.{season_code}.{requested_language.upper()}\\n")
if found_folders:
print_and_log(f"Subtitle folder(s) found for season {season_code}, but not for language '{requested_language.upper()}':\\n")
print_and_log(f"{Fore.YELLOW}Found folders:{Style.RESET_ALL}")
for folder_name, lang in found_folders:
print_and_log(f" - {folder_name} (Language: {lang})")
print_and_log(f"\\n{Fore.YELLOW}Requested language:{Style.RESET_ALL} {requested_language.upper()}")
print_and_log(f"{Fore.YELLOW}Expected folder name:{Style.RESET_ALL} SUBTITLES.{season_code}.{requested_language.upper()}\\n")
print_and_log(f"{Fore.YELLOW}Possible solutions:{Style.RESET_ALL}")
print_and_log(f" 1. Rename subtitle folder(s) to match the correct season and language")
print_and_log(f" 2. Create a subtitle folder for season {season_code} and language '{requested_language.upper()}'")
print_and_log(f" 3. Remove the subtitle folders if not needed\\n")
print_and_log(f"{Fore.RED}Subservient in TV-Series mode cannot proceed with improper folder configuration.{Style.RESET_ALL}")
exit_with_prompt("Press Enter to exit...")
def check_subtitle_folder_coverage(video_file: Path, language: str):
"""
Check if video is covered by pre-downloaded subtitle folder for specific language.
Returns True if covered (skip download), False if not covered (proceed with download).
"""
video_folder = video_file.parent
# Extract season code from video filename
sxxexx_code = extract_sxxexx_code(video_file.name)
if not sxxexx_code:
return False # Not a series file
season_code = sxxexx_code[:3] # "S01E01" -> "S01"
episode_code = sxxexx_code[3:] # "S01E01" -> "E01"
print_and_log(f"{acq_tag()} {Fore.CYAN}Searching for pre-downloaded subtitle folder...{Style.RESET_ALL}")
# Look for subtitle folder for this season and language
subtitle_folder = detect_subtitle_folder(video_folder, season_code, language)
if not subtitle_folder:
print_and_log(f"{acq_tag()} {Fore.YELLOW}No subtitle folder found for '{video_file.stem}' [{season_code}] [{language.upper()}]{Style.RESET_ALL}")
return False # No folder found, proceed with normal download
print_and_log(f"{acq_tag()} {Fore.GREEN}Subtitle folder found for '{video_file.stem}' [{season_code}] [{language.upper()}]{Style.RESET_ALL}")
# Validate season consistency first
if not validate_season_episodes_match(video_folder, season_code):
return False # Validation failed, function exits the program
print_and_log(f"{acq_tag()} {Fore.CYAN}Checking if all episodes are covered...{Style.RESET_ALL}")
# Get all episodes in this season from video files
all_episodes = get_all_season_episodes(video_folder, season_code)
# Check coverage for all episodes
covered_episodes = []
missing_episodes = []
for ep_code in all_episodes:
if check_episode_coverage_in_folder(subtitle_folder, ep_code, language):
covered_episodes.append(ep_code)
else:
missing_episodes.append(ep_code)
# Log results
if missing_episodes:
print_and_log(f"{acq_tag()} {Fore.YELLOW}Episodes found for [{season_code}] [{language.upper()}], but some are still missing:{Style.RESET_ALL}")
for missing in missing_episodes:
print_and_log(f"{acq_tag()} {Fore.YELLOW} - {missing}{Style.RESET_ALL}")
print_and_log(f"{acq_tag()} {Fore.YELLOW}These episodes will still be manually downloaded.{Style.RESET_ALL}")
# Return True only if THIS episode is covered
return sxxexx_code in covered_episodes
else:
print_and_log(f"{acq_tag()} {Fore.GREEN}All episodes covered for [{season_code}] [{language.upper()}]{Style.RESET_ALL}")
return True
def get_all_season_episodes(video_folder: Path, season_code: str) -> list:
"""
Get all episode codes (S01E01, S01E02, etc.) for a given season from video files.
"""
video_extensions = {'.mkv', '.mp4', '.avi', '.m4v', '.mov', '.wmv'}
episodes = []
for video_file in video_folder.iterdir():
if video_file.is_file() and video_file.suffix.lower() in video_extensions:
if has_strict_series_naming_pattern(video_file.name):
sxxexx_code = extract_sxxexx_code(video_file.name)
if sxxexx_code and sxxexx_code.startswith(season_code):
episodes.append(sxxexx_code)
return sorted(list(set(episodes))) # Remove duplicates and sort
def check_episode_coverage_in_folder(subtitle_folder: Path, sxxexx_code: str, language: str) -> bool:
"""
Check if a specific episode has subtitle coverage.
After extraction process, we check for extracted subtitles in the video folder instead.
"""
# If it's a ZIP file, we can't check inside it easily, so skip the check
# Our extraction process will have already handled ZIP files
if subtitle_folder.is_file() and subtitle_folder.name.lower().endswith('.zip'):
# For ZIP files, check if extracted subtitles exist in parent directory
parent_dir = subtitle_folder.parent
extracted_pattern = f"*.{language.lower()}.number*.{sxxexx_code}.srt"
extracted_files = list(parent_dir.glob(extracted_pattern))
return len(extracted_files) > 0
# If it's not a directory, skip
if not subtitle_folder.is_dir():
# Check for extracted subtitles in the same directory as the folder
parent_dir = subtitle_folder.parent
extracted_pattern = f"*.{language.lower()}.number*.{sxxexx_code}.srt"
extracted_files = list(parent_dir.glob(extracted_pattern))
return len(extracted_files) > 0
# For directory subtitle folders, first check for extracted subtitles in parent
parent_dir = subtitle_folder.parent
extracted_pattern = f"*.{language.lower()}.number*.{sxxexx_code}.srt"
extracted_files = list(parent_dir.glob(extracted_pattern))
if extracted_files:
return True
# Fallback to checking inside the subtitle folder (original logic)
subtitle_extensions = {'.srt', '.sub', '.vtt', '.ass', '.ssa'}
# Look for subtitle files matching this episode
for item in subtitle_folder.iterdir():
if item.is_file() and item.suffix.lower() in subtitle_extensions:
# Check if filename contains the episode code and language
if (sxxexx_code.lower() in item.name.lower() and
language.lower() in item.name.lower()):
return True
return False
def write_runtime_blocks_to_config(token=None, skipped_entries=None):
"""Write runtime configuration blocks to config file."""
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:
if line.strip().lower() == RUNTIME_TAG.lower():
out.append(line)
break
out.append(line)
if out and out[-1].strip():
out.append('')
runtime_blocks = []
if token is None:
token = get_token_from_config()
runtime_blocks.append(SEP)
runtime_blocks.append(TOKEN_COMMENT)
runtime_blocks.append(TOKEN_TAG)
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]
while out and not out[-1].strip():
out.pop()
if out and out[-1].strip():
out.append('')
out.extend(runtime_blocks)
out.append('')
CONFIG_PATH.write_text('\n'.join(out), encoding='utf-8')
def set_token_in_config(token):
"""Store JWT token in config file."""
write_runtime_blocks_to_config(token=token)
def get_token_from_config():
"""Retrieve JWT token from config file."""
if not CONFIG_PATH.exists():
return None
lines = CONFIG_PATH.read_text(encoding='utf-8').splitlines()
for i, line in enumerate(lines):
if line.strip() == '[token]':
j = i + 1
while j < len(lines):
value = lines[j].strip()
if value and not value.startswith('[') and not value.startswith('--') and not value.startswith('#'):
return value
elif value.startswith('[') or value.startswith('--'):
break
j += 1
elif line.strip().startswith('token ='):
parts = line.split('=', 1)
if len(parts) == 2:
return parts[1].strip()
return None
def get_jwt_token():
"""Obtain JWT token through API authentication."""
token = get_token_from_config()
if token:
return token
print_and_log(f"{acq_tag()} * No valid JWT token in .config. Logging in...")
login_url = f"{API_URL}/login"
login_headers = {
"Api-Key": API_KEY,
"Content-Type": "application/json",
"User-Agent": "Subservient v0.85"
}
login_payload = {
"username": USERNAME,
"password": PASSWORD
}
response = requests.post(
login_url,
headers=login_headers,
json=login_payload
)
time.sleep(0.5)
if response.status_code == 200:
json_data = response.json()
token = json_data.get("token")
if token:
set_token_in_config(token)
print_and_log(f"{acq_tag()} * New JWT token saved to .config.")
return token
elif response.status_code == 429:
print_and_log(f"{acq_tag()} 429: Too many requests. Waiting {int(PAUSE_SECONDS)} seconds...")
time.sleep(PAUSE_SECONDS)
return get_jwt_token()
elif response.status_code == 403:
handle_api_error(response, {
"URL": login_url,
"Headers": login_headers,
"Payload": login_payload
})
return None
else:
print_and_log(f"{acq_tag()} OpenSubtitles login error: {response.status_code}")
print_and_log(f"{acq_tag()} Response:")
print_and_log(response.text)
return None
def get_unwanted_terms_from_config():
"""Read unwanted_terms setting from config file."""
if not CONFIG_PATH.exists():
return []
lines = CONFIG_PATH.read_text(encoding='utf-8').splitlines()
for line in lines:
if line.strip().lower().startswith('unwanted_terms') and '=' in line:
_, value = line.split('=', 1)
return [term.strip().strip('"') for term in value.split(',') if term.strip()]
return []
UNWANTED_TERMS = get_unwanted_terms_from_config()
def clean_title(raw_title: str) -> str:
"""Clean and normalize video title for subtitle searching."""
UNWANTED_TERMS = get_unwanted_terms_from_config()
UNWANTED_CHARS = r"[\[\]\(\)\{\}_\+\.-]"
WHITELIST = {"a", "i", "z", "o", "u"}
cleaned = raw_title.replace('.', ' ')
pattern = r"\\b(" + "|".join(re.escape(term) for term in UNWANTED_TERMS) + r")\\b"
cleaned = re.sub(pattern, "", cleaned, flags=re.IGNORECASE)
cleaned = re.sub(r"[\[\(\{][^\]\)\}]*[\]\)\}]", "", cleaned)
cleaned = re.sub(r"\\b(?!(?:19|20)\\d{2})\\d+\\b", "", cleaned)
cleaned = re.sub(UNWANTED_CHARS, " ", cleaned)
cleaned = re.sub(r"[^a-zA-Z ]", "", cleaned)
cleaned = re.sub(r"\\s+", " ", cleaned)
words = cleaned.split()
result = []
for i, word in enumerate(words):
if len(word) == 1 and word.lower() not in WHITELIST:
left = words[i-1] if i > 0 else ''
right = words[i+1] if i < len(words)-1 else ''
if (len(left) > 1 or len(right) > 1):
result.append(word)
else:
result.append(word)
cleaned = ' '.join(result)
cleaned = re.sub(r"([a-zA-Z])\1{2,}", r"\1", cleaned)
cleaned = re.sub(r"\\s+", " ", cleaned)
return cleaned.strip()
def check_existing_subtitles_silent(mkv_path: Path) -> dict:
"""Check which subtitle languages already exist for video file (no logging)."""
base = mkv_path.with_suffix('')
result = {}
for lang in LANGUAGES:
# Check standard naming: filename.lang.srt
standard_srt = base.with_name(f"{base.name}.{lang}.srt")
# Check series naming if in series mode
series_srt = None
if SERIES_MODE:
sxxexx_code = extract_sxxexx_code(mkv_path.name)
if sxxexx_code:
# Check if video filename already contains the episode code
if sxxexx_code.lower() in base.name.lower():
# Video already has SxxExx in name, subtitle should use standard naming
series_srt = base.with_name(f"{base.name}.{lang}.srt")
else:
# Video doesn't have SxxExx, subtitle should have SxxExx before language
series_srt = base.with_name(f"{base.name}.{sxxexx_code}.{lang}.srt")
# Check if we have any good subtitles (not DRIFT/FAILED)
has_standard = standard_srt.exists()
has_series = series_srt.exists() if series_srt else False
result[lang] = has_standard or has_series
return result
def check_existing_subtitles(mkv_path: Path) -> dict:
"""Check which subtitle languages already exist for video file."""
base = mkv_path.with_suffix('')
result = {}
print_and_log(f"{acq_tag()} {Fore.CYAN} - Checking existing subtitles for:{Style.RESET_ALL} {mkv_path.name}")
for lang in LANGUAGES:
# Check standard naming: filename.lang.srt
standard_srt = base.with_name(f"{base.name}.{lang}.srt")
# Check series naming if in series mode
series_srt = None
if SERIES_MODE:
sxxexx_code = extract_sxxexx_code(mkv_path.name)
if sxxexx_code:
# Check if video filename already contains the episode code
if sxxexx_code.lower() in base.name.lower():
# Video already has SxxExx in name, subtitle should use standard naming
series_srt = base.with_name(f"{base.name}.{lang}.srt")
else:
# Video doesn't have SxxExx, subtitle should have SxxExx before language
series_srt = base.with_name(f"{base.name}.{sxxexx_code}.{lang}.srt")
# Check if we have any good subtitles (not DRIFT/FAILED)
has_standard = standard_srt.exists()
has_series = series_srt.exists() if series_srt else False
# CRITICAL FIX: Only count as "complete" if we have a FINAL subtitle
# Having only DRIFT files means we need MORE downloads, not skip!
result[lang] = has_standard or has_series
if has_standard or has_series:
print_and_log(f"{acq_tag()} {Fore.GREEN} ✓ {lang.upper()}:{Style.RESET_ALL} subtitle found")
else:
print_and_log(f"{acq_tag()} {Fore.YELLOW} - {lang.upper()}:{Style.RESET_ALL} no subtitle found")
return result
def extract_sxxexx_code(name: str) -> str | None:
"""Extract season/episode code from filename."""
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
unknown_sxxexx_files = []
def download_top_subtitles(subs, lang, dest_folder, jwt_token, mkv_path=None, candidate_index=None, force_download=False):
"""Download the top-rated subtitles for specified language and video."""
global unknown_sxxexx_files
headers = {
"Api-Key": API_KEY,
"User-Agent": "NexigenSubtitleBot v1.0",
"Authorization": f"Bearer {jwt_token}"
}
sxxexx_from_mkv = None
if SERIES_MODE and mkv_path is not None:
sxxexx_from_mkv = extract_sxxexx_code(mkv_path.name)
for i, sub in enumerate(subs[:TOP_DOWNLOADS], 1):
idx = candidate_index if candidate_index is not None else i
drift_exists = any(f"number{idx}.DRIFT" in f.name for f in get_subtitle_files_by_pattern(dest_folder, lang, ".DRIFT"))
failed_exists = any(f"number{idx}.FAILED" in f.name for f in get_subtitle_files_by_pattern(dest_folder, lang, ".FAILED"))
if not force_download and (drift_exists or failed_exists):
print_and_log(f"{acq_tag()} Skipping candidate index {idx}: already marked as DRIFT or FAILED.")
continue
try:
files = sub.get('attributes', {}).get('files', [])
if not files:
print_and_log(f"{acq_tag()} {Fore.RED}No files for sub {idx}. Skipping.{Style.RESET_ALL}")
continue
file_id = files[0].get('file_id')
if not file_id:
print_and_log(f"{acq_tag()} {Fore.RED}No file_id for sub {idx}. Skipping.{Style.RESET_ALL}")
continue
downloads = sub['attributes'].get('download_count', 0)
orig_sub_name = files[0].get('file_name', '')
base_name = f"{downloads}.{lang}.number{idx}"
if SERIES_MODE:
sxxexx = sxxexx_from_mkv or extract_sxxexx_code(orig_sub_name)
if sxxexx:
file_name = f"{base_name}.{sxxexx}.srt"
else:
file_name = f"{base_name}.UNKNOWN.srt"
print_and_log(f"{acq_tag()} {Fore.YELLOW}Warning: Could not determine SxxExx code for subtitle '{orig_sub_name}'. Naming as '{file_name}'.{Style.RESET_ALL}")
unknown_sxxexx_files.append(str(dest_folder / file_name))
else:
file_name = f"{base_name}.srt"
url = f"{API_URL}/download"
max_retries_503 = DOWNLOAD_RETRY_503
for attempt in range(1, max_retries_503 + 1):
try:
resp = requests.post(url, headers=headers, json={"file_id": file_id})
except Exception as e:
print_and_log_colored(f"{acq_tag()} {Fore.RED}HTTP POST error: {e}{Style.RESET_ALL}", Fore.RED)
resp = None
time.sleep(0.5)
if resp is None or resp.status_code >= 400:
if resp and resp.status_code == 503:
if attempt < max_retries_503:
delay = min(5 * attempt, 30)
print_and_log_colored(f"{acq_tag()} {Fore.YELLOW}503 Service Unavailable (server overloaded). Retrying in {delay}s... (attempt {attempt}/{max_retries_503}){Style.RESET_ALL}", Fore.YELLOW)
time.sleep(delay)
continue
else:
print_and_log_colored(f"{acq_tag()} {Fore.RED}Failed to download after {max_retries_503} attempts (503 Service Unavailable). OpenSubtitles servers are overloaded. Skipping.{Style.RESET_ALL}", Fore.RED)
break
elif attempt < max_retries_503:
print_and_log_colored(f"{acq_tag()} {Fore.YELLOW}HTTP error (status {getattr(resp, 'status_code', 'N/A')}). Retrying in {int(PAUSE_SECONDS)}s... (attempt {attempt}/{max_retries_503}){Style.RESET_ALL}", Fore.YELLOW)
time.sleep(PAUSE_SECONDS)
continue
else:
print_and_log_colored(f"{acq_tag()} {Fore.RED}Failed to download after {max_retries_503} attempts (HTTP error). Skipping.{Style.RESET_ALL}", Fore.RED)
break
elif resp.status_code == 200:
download_link = resp.json().get("link")
if download_link:
for srt_attempt in range(1, max_retries_503 + 1):
try:
srt_resp = requests.get(download_link)
except Exception as e:
print_and_log_colored(f"{acq_tag()} {Fore.RED}HTTP GET error: {e}{Style.RESET_ALL}", Fore.RED)
srt_resp = None
time.sleep(0.5)
if srt_resp is None or srt_resp.status_code >= 400:
if srt_resp and srt_resp.status_code == 503:
if srt_attempt < max_retries_503:
delay = min(5 * srt_attempt, 30)
print_and_log_colored(f"{acq_tag()} {Fore.YELLOW}SRT 503 Service Unavailable. Retrying in {delay}s... (attempt {srt_attempt}/{max_retries_503}){Style.RESET_ALL}", Fore.YELLOW)
time.sleep(delay)
continue
else:
print_and_log_colored(f"{acq_tag()} {Fore.RED}Failed to download SRT after {max_retries_503} attempts (503 Service Unavailable). Skipping.{Style.RESET_ALL}", Fore.RED)
break
elif srt_attempt < max_retries_503:
print_and_log_colored(f"{acq_tag()} {Fore.YELLOW}SRT HTTP error (status {getattr(srt_resp, 'status_code', 'N/A')}). Retrying in {int(PAUSE_SECONDS)}s... (attempt {srt_attempt}/{max_retries_503}){Style.RESET_ALL}", Fore.YELLOW)
time.sleep(PAUSE_SECONDS)
continue
else:
print_and_log_colored(f"{acq_tag()} {Fore.RED}Failed to download SRT after {max_retries_503} attempts (HTTP error). Skipping.{Style.RESET_ALL}", Fore.RED)
break
elif srt_resp.status_code == 200:
srt_data = srt_resp.content
dest_path = dest_folder / file_name
with open(dest_path, 'wb') as f:
f.write(srt_data)
print_and_log_colored(f"Stored as: {os.path.basename(dest_path)}", Fore.GREEN)
for failed_file in get_subtitle_files_by_pattern(dest_folder, lang, ".FAILED"):
drift_file = failed_file.with_name(failed_file.name.replace(".FAILED.srt", ".DRIFT.srt"))
failed_file.rename(drift_file)
print_and_log_colored(
f"{acq_tag()} {Fore.CYAN}Restored to DRIFT: {drift_file.name}{Style.RESET_ALL}",
Fore.CYAN
)
break
else:
print_and_log_colored(f"{acq_tag()} {Fore.RED}No valid SRT download after retries.{Style.RESET_ALL}", Fore.RED)
else:
print_and_log_colored(f"{acq_tag()} {Fore.RED}No download link in response.{Style.RESET_ALL}", Fore.RED)
break
elif resp.status_code == 403:
print_and_log_colored(f"{acq_tag()} {Fore.RED}403 Forbidden: Download denied by OpenSubtitles API.{Style.RESET_ALL}", Fore.RED)
break
else:
print_and_log_colored(f"{acq_tag()} {Fore.RED}Download endpoint error: HTTP {resp.status_code}{Style.RESET_ALL}", Fore.RED)
break
except Exception as e:
print_and_log_colored(f"{acq_tag()} {Fore.RED}Download error: {e}{Style.RESET_ALL}", Fore.RED)
def print_subtitle_list(subs, lang, color=Fore.LIGHTBLUE_EX):
"""Display formatted list of available subtitles."""
for i, item in enumerate(subs, 1):
file_name = item['attributes']['files'][0]['file_name']
downloads = item['attributes']['download_count']
line = f" {color}{i}.{Style.RESET_ALL} {file_name} (" \
f"{Fore.CYAN}{downloads}{Style.RESET_ALL} downloads) " \
f"[{Fore.LIGHTYELLOW_EX}{lang.upper()}{Style.RESET_ALL}]"
print_and_log(line)
print_and_log("")
def filter_subtitles_by_query(subs, query):
"""Filter subtitle results by search query terms."""
match = re.search(r'(.*?)([\s._-]?)(19|20)\\d{2}', query)
if match:
left = match.group(1).strip().split()
year = match.group(3) + match.group(0)[-2:]
filter_words = [w.lower() for w in left if w] + [year]
else:
filter_words = [w.lower() for w in query.strip().split() if w]
filtered = []
for sub in subs:
# Skip subtitles without file information
if not sub.get('attributes', {}).get('files') or len(sub['attributes']['files']) == 0:
continue
file_name = sub['attributes']['files'][0]['file_name'].lower()
if all(word in file_name for word in filter_words):
filtered.append(sub)
return filtered
def handle_api_error(response, request_details=None):
"""Handle and display API error responses with detailed information."""
if response.status_code == 403:
print_and_log(f"{acq_tag()} {Fore.RED}403 Forbidden: Access denied by OpenSubtitles API.{Style.RESET_ALL}")
print_and_log(f"{acq_tag()} This is usually due to account, content, or region restrictions.")
print_and_log(f"{acq_tag()} Please check your OpenSubtitles account status, try a different account, or contact OpenSubtitles support.")
if request_details:
print_and_log(f"{acq_tag()} --- REQUEST DETAILS ---")
for key, value in request_details.items():
print_and_log(f"{key}: {value}")
print_and_log(f"{acq_tag()} --- RESPONSE DETAILS ---")
print_and_log(f"Status: {response.status_code}")
print_and_log(f"Headers: {dict(response.headers)}")
print_and_log(f"Body: {response.text}")
return True
elif response.status_code == 401:
print_and_log(f"{acq_tag()} JWT token invalid or expired. Fetching new token...")
return False
return False
def get_subtitle_files_by_pattern(folder: Path, lang: str, pattern_suffix: str = "") -> list[Path]:
pattern = f"*.{lang}.number*{pattern_suffix}.srt"
return list(folder.glob(pattern))
def count_existing_subtitles(movie_path: Path, lang: str) -> tuple[set, int]:
existing_counts = set()
# For series mode, only count episode-specific subtitles
if SERIES_MODE:
sxxexx_code = extract_sxxexx_code(movie_path.name)
if sxxexx_code:
# Count episode-specific candidates
episode_pattern = f"*.{lang}.number*.{sxxexx_code}.srt"
episode_drift_pattern = f"*.{lang}.number*.{sxxexx_code}.DRIFT.srt"
episode_failed_pattern = f"*.{lang}.number*.{sxxexx_code}.FAILED.srt"
episode_files = list(movie_path.parent.glob(episode_pattern))
episode_drift_files = list(movie_path.parent.glob(episode_drift_pattern))
episode_failed_files = list(movie_path.parent.glob(episode_failed_pattern))
# Extract existing download counts for this episode
for f in episode_files:
if f.name.endswith('.DRIFT.srt') or f.name.endswith('.FAILED.srt'):
continue
m = re.match(rf"^(P?\d+)\.{re.escape(lang)}\.number\d+\.{re.escape(sxxexx_code)}\.srt$", f.name)
if m:
number_str = m.group(1)
# Skip P-prefixed files in normal counting (they're pre-downloaded)
if not number_str.startswith('P'):
existing_counts.add(int(number_str))
for f in episode_drift_files:
m = re.match(rf"^(P?\d+)\.{re.escape(lang)}\.number\d+\.{re.escape(sxxexx_code)}\.DRIFT\.srt$", f.name)
if m:
number_str = m.group(1)
# Handle P-prefix: if highest number is P-prefixed, start downloads at 1
if number_str.startswith('P'):
# P-prefixed DRIFT found - this triggers the special logic later
existing_counts.add(-1) # Special marker for P-prefix detection
else:
existing_counts.add(int(number_str))
for f in episode_failed_files:
m = re.match(rf"^(P?\d+)\.{re.escape(lang)}\.number\d+\.{re.escape(sxxexx_code)}\.FAILED\.srt$", f.name)
if m:
number_str = m.group(1)
# Same logic as DRIFT files
if number_str.startswith('P'):
existing_counts.add(-1) # Special marker for P-prefix detection
else:
existing_counts.add(int(number_str))
# Count total for this episode only
normal_count = len([f for f in episode_files if not (f.name.endswith('.DRIFT.srt') or f.name.endswith('.FAILED.srt'))])
total_existing = normal_count + len(episode_drift_files) + len(episode_failed_files)
return existing_counts, total_existing
# Original movie logic for non-series mode
for f in get_subtitle_files_by_pattern(movie_path.parent, lang):
if f.name.endswith('.DRIFT.srt') or f.name.endswith('.FAILED.srt'):
continue
m = re.match(r"^(P?\d+)\." + re.escape(lang) + r"\.number\d+\.srt$", f.name)
if m:
number_str = m.group(1)
# Skip P-prefixed files in normal counting (they're pre-downloaded)
if not number_str.startswith('P'):
existing_counts.add(int(number_str))
for f in get_subtitle_files_by_pattern(movie_path.parent, lang, ".DRIFT"):
m = re.match(r"^(P?\d+)\." + re.escape(lang) + r"\.number\d+\.DRIFT\.srt$", f.name)
if m:
number_str = m.group(1)
# Handle P-prefix: if highest number is P-prefixed, start downloads at 1
if number_str.startswith('P'):
existing_counts.add(-1) # Special marker for P-prefix detection
else:
existing_counts.add(int(number_str))
for f in get_subtitle_files_by_pattern(movie_path.parent, lang, ".FAILED"):
m = re.match(r"^(P?\d+)\." + re.escape(lang) + r"\.number\d+\.FAILED\.srt$", f.name)
if m:
number_str = m.group(1)
# Same logic as DRIFT files
if number_str.startswith('P'):
existing_counts.add(-1) # Special marker for P-prefix detection
else:
existing_counts.add(int(number_str))
all_srt_files = get_subtitle_files_by_pattern(movie_path.parent, lang)
normal_count = len([f for f in all_srt_files if not (f.name.endswith('.DRIFT.srt') or f.name.endswith('.FAILED.srt'))])
total_existing = normal_count + \
len(get_subtitle_files_by_pattern(movie_path.parent, lang, ".DRIFT")) + \
len(get_subtitle_files_by_pattern(movie_path.parent, lang, ".FAILED"))
return existing_counts, total_existing
def build_search_query(raw_title: str) -> str:
# For series mode, truncate everything after SxxExx pattern
if SERIES_MODE:
series_match = re.search(r'([sS](\d{1,2})[eE](\d{1,2}))', raw_title)
if series_match:
# Find the end of the SxxExx pattern
series_end_pos = series_match.end()
# Keep everything up to and including SxxExx, remove everything after
truncated_title = raw_title[:series_end_pos]
# Simple cleaning for series: only remove brackets and their contents
# Example: [TorrentCouch.com].13.Reasons.Why.S02E04 -> .13.Reasons.Why.S02E04
cleaned = re.sub(r'\[[^\]]*\]', '', truncated_title)
# Replace dots with spaces and clean up
cleaned = cleaned.replace('.', ' ')
# Clean up multiple spaces
cleaned = re.sub(r'\s+', ' ', cleaned)
return cleaned.strip()
# Original movie logic for non-series mode
year_match = re.search(r'(19|20)\d{2}', raw_title)
if year_match:
year = year_match.group(0)
idx = year_match.end()
left = raw_title[:idx].rstrip(" ._-()[]")
query = left.strip()
else:
query = clean_title(raw_title)
return clean_query(query)
def clean_query(query):
query = re.sub(r'\s*\[[A-Z]{2}\]?$', '', query, flags=re.IGNORECASE).strip()
query = re.sub(r'\[[A-Z]{2}\]', '', query, flags=re.IGNORECASE)
query = re.sub(r'[\[\](){}]', '', query)
query = query.replace('.', ' ')
query = re.sub(r'(19|20)\d{2}$', lambda m: m.group(0), query)
query = re.sub(r'(?<!\d)(\d{1,2})$', '', query).strip()
return query
def remove_all_short_numbers(query):
years = re.findall(r'(19|20)\d{2}', query)
year_placeholders = []
for i, year in enumerate(years):
placeholder = f'__YEAR{i}__'