-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
1725 lines (1421 loc) · 75.1 KB
/
Copy pathmain.py
File metadata and controls
1725 lines (1421 loc) · 75.1 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 argparse
import os
import torch
import whisper
from tvdb_v4_official import TVDB
import tmdbsimple as tmdb
import re
import subprocess
import tempfile
import pysubs2
import warnings
import numpy as np
from scipy.optimize import linear_sum_assignment
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity
import time
import json
from pathlib import Path
from platformdirs import user_cache_dir
try:
from subliminal import download_best_subtitles, save_subtitles
from subliminal.video import Episode
from subliminal.core import provider_manager
SUBLIMINAL_AVAILABLE = True
except ImportError:
SUBLIMINAL_AVAILABLE = False
# ANSI color codes
class Colors:
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
MAGENTA = '\033[95m'
CYAN = '\033[96m'
WHITE = '\033[97m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
END = '\033[0m'
def colorize_similarity(similarity):
"""Return colored similarity score based on confidence level"""
if similarity >= 0.7:
return f"{Colors.GREEN}{similarity:.3f}{Colors.END}"
elif similarity >= 0.5:
return f"{Colors.YELLOW}{similarity:.3f}{Colors.END}"
elif similarity >= 0.3:
return f"{Colors.CYAN}{similarity:.3f}{Colors.END}"
else:
return f"{Colors.RED}{similarity:.3f}{Colors.END}"
def is_correctly_named(video_path, episode_info):
"""Check if video file is already correctly named"""
current_name = os.path.splitext(os.path.basename(video_path))[0]
target_name = re.sub(r'[<>:"/\|?*]', '', episode_info)
# Normalize both names for comparison (remove extra spaces, case insensitive)
current_normalized = re.sub(r'\s+', ' ', current_name.lower().strip())
target_normalized = re.sub(r'\s+', ' ', target_name.lower().strip())
# Check exact match first
if current_normalized == target_normalized:
return True
# Also check if current name ends with the target (for cases like "Show Name - S01E01 - Episode" vs "S01E01 - Episode")
if current_normalized.endswith(target_normalized):
return True
# Check if they match after removing common show name prefixes
# Look for patterns like "Show Name - " at the beginning
show_prefix_pattern = r'^[^-]+ - '
current_without_show = re.sub(show_prefix_pattern, '', current_normalized).strip()
target_without_show = re.sub(show_prefix_pattern, '', target_normalized).strip()
return current_without_show == target_without_show
# Suppress the FP16 warning from Whisper
warnings.filterwarnings("ignore", message="FP16 is not supported on CPU; using FP32 instead")
def get_cache_dir():
"""Get or create cache directory for subtitles using OS-appropriate location"""
cache_dir = Path(user_cache_dir("episcan", "episcan"))
cache_dir.mkdir(parents=True, exist_ok=True)
return cache_dir
def get_cache_key(show_name, season, episode_number):
"""Generate cache key for episode subtitles"""
# Normalize show name for filename safety
safe_show = re.sub(r'[<>:"/\|?*]', '', show_name).strip()
return f"{safe_show}_S{season:02d}E{episode_number:02d}"
def save_subtitle_to_cache(show_name, season, episode_number, subtitle_content, subtitle_text, provider_name):
"""Save subtitle content and metadata to cache"""
try:
cache_dir = get_cache_dir()
cache_key = get_cache_key(show_name, season, episode_number)
# Save raw subtitle content
subtitle_file = cache_dir / f"{cache_key}.srt"
with open(subtitle_file, 'w', encoding='utf-8') as f:
f.write(subtitle_content)
# Save metadata
metadata = {
'show_name': show_name,
'season': season,
'episode': episode_number,
'provider': provider_name,
'cached_at': time.time(),
'text_length': len(subtitle_text)
}
metadata_file = cache_dir / f"{cache_key}.json"
with open(metadata_file, 'w', encoding='utf-8') as f:
json.dump(metadata, f, indent=2)
return True
except Exception as e:
return False
def load_subtitle_from_cache(show_name, season, episode_number, verbose=False):
"""Load subtitle from cache if available"""
try:
cache_dir = get_cache_dir()
cache_key = get_cache_key(show_name, season, episode_number)
subtitle_file = cache_dir / f"{cache_key}.srt"
metadata_file = cache_dir / f"{cache_key}.json"
if subtitle_file.exists() and metadata_file.exists():
# Load metadata
with open(metadata_file, 'r', encoding='utf-8') as f:
metadata = json.load(f)
# Load subtitle content
with open(subtitle_file, 'r', encoding='utf-8') as f:
subtitle_content = f.read()
# Parse subtitle text
subtitle_text = parse_subtitle_content(subtitle_content)
if subtitle_text and verbose:
provider = metadata.get('provider', 'unknown')
print(f" ✓ Found cached subtitles ({len(subtitle_text)} chars) from {provider}")
return subtitle_content, subtitle_text, metadata
except Exception as e:
if verbose:
print(f" Cache load error: {e}")
return None, None, None
def clear_subtitle_cache(verbose=False):
"""Clear all cached subtitles"""
try:
cache_dir = get_cache_dir()
count = 0
for file in cache_dir.glob("*"):
if file.suffix in ['.srt', '.json']:
file.unlink()
count += 1
if verbose:
print(f"Cleared {count} cached files")
return count
except Exception as e:
if verbose:
print(f"Error clearing cache: {e}")
return 0
def main():
args = get_args()
# Handle cache management
if args.clear_cache:
print("Clearing subtitle cache...")
cleared = clear_subtitle_cache(args.verbose)
print(f"Cleared {cleared} cached files")
if not args.video_dir or args.video_dir == ".":
return # If only clearing cache, exit
# Auto-enable subtitle comparison unless descriptions are explicitly requested
if not args.use_descriptions:
args.use_subtitles_comparison = True
if args.verbose and not args.subtitles_dir and not args.use_subliminal:
print("Defaulting to subtitle comparison using subliminal (use --use-descriptions to compare against episode descriptions)")
# Adjust transcription defaults based on comparison method
if args.use_descriptions and args.max_duration == 180:
# For description comparison, use full episode by default
args.max_duration = None
if args.verbose:
print("Using full episode transcription for description comparison")
elif args.use_subtitles_comparison and args.max_duration == 180:
# Keep the shorter default for subtitle comparison
if args.verbose:
print(f"Using {args.max_duration}s transcription starting at {args.start_offset}s for subtitle comparison")
# Determine which API to use based on available keys and preferences
tmdb_key = args.tmdb_api_key or os.getenv('TMDB_API_KEY')
tvdb_key = args.tvdb_api_key or os.getenv('TVDB_API_KEY')
use_tmdb = False
api_key = None
if args.force_tvdb and tvdb_key:
# Force TVDB if explicitly requested and available
use_tmdb = False
api_key = tvdb_key
print("Using TVDB API (forced)")
elif tmdb_key:
# Default to TMDB if available
use_tmdb = True
api_key = tmdb_key
print("Using TMDB API")
elif tvdb_key:
# Fall back to TVDB
use_tmdb = False
api_key = tvdb_key
print("Using TVDB API")
else:
print("Error: Either TMDB or TVDB API key is required.")
print("Set TMDB_API_KEY or TVDB_API_KEY environment variable, or use --tmdb-api-key or --tvdb-api-key arguments.")
return
# Load SBERT model for text similarity
device = "cuda" if torch.cuda.is_available() else "cpu"
if args.verbose:
print(f"Loading sentence transformer model ({args.sbert_model}) on {device}...")
model = SentenceTransformer(args.sbert_model, device=device)
# Whisper model will be loaded on-demand when needed
# Get video files
video_paths = get_video_files(args.video_dir)
print(f"Found {len(video_paths)} video files")
# Parse show/season from directory structure
show_info = parse_plex_structure(video_paths[0] if video_paths else args.video_dir)
print(f"Detected: {show_info['show']} Season {show_info['season']}")
# Get episode data from selected API
if use_tmdb:
episodes_data, proper_show_name = get_tmdb_episodes(show_info, api_key, args.verbose)
else:
episodes_data, proper_show_name = get_tvdb_episodes(show_info, api_key, args.verbose)
if proper_show_name:
show_info['show'] = proper_show_name # Use the proper name from API
# Get subtitle comparison data (default behavior)
if args.use_subtitles_comparison:
if args.subtitles_dir:
# Use local subtitle files
print(f"Loading subtitles from directory: {args.subtitles_dir}")
episodes_data = load_local_episode_subtitles(show_info, episodes_data, args.subtitles_dir, args.verbose)
elif SUBLIMINAL_AVAILABLE:
# Use subliminal to download subtitles
print(f"Fetching episode subtitles using subliminal...")
episodes_data = get_subliminal_episode_subtitles(show_info, episodes_data, args.verbose, args.no_cache)
else:
# No subtitle source available
print("Warning: Subliminal library not available and no local subtitles provided. Install subliminal with: uv add subliminal")
print("Falling back to episode descriptions.")
args.use_subtitles_comparison = False
print(f"Found {len(episodes_data)} episodes for {show_info['show']} Season {show_info['season']}")
# Check subtitle coverage if using subtitle comparison
if args.use_subtitles_comparison:
episodes_with_subtitles = sum(1 for ep in episodes_data if 'subtitle_text' in ep and ep['subtitle_text'])
total_episodes = len(episodes_data)
if episodes_with_subtitles < total_episodes:
missing_count = total_episodes - episodes_with_subtitles
print(f"\n{Colors.YELLOW}⚠ Warning: Only {episodes_with_subtitles}/{total_episodes} episodes have subtitles ({missing_count} missing){Colors.END}")
# Retry with specified number of attempts
max_retries = args.subtitle_retries
if max_retries > 0:
print(f"{Colors.CYAN}Retrying subtitle download with {max_retries} attempts...{Colors.END}")
episodes_data = retry_missing_subtitles(show_info, episodes_data, max_retries, args.verbose, args.no_cache)
# Check coverage again after retries
final_episodes_with_subtitles = sum(1 for ep in episodes_data if 'subtitle_text' in ep and ep['subtitle_text'])
final_missing = total_episodes - final_episodes_with_subtitles
if final_missing == 0:
print(f"{Colors.GREEN}✓ All episodes now have subtitles after retries!{Colors.END}")
elif final_missing < missing_count:
print(f"{Colors.YELLOW}✓ Found subtitles for {missing_count - final_missing} more episodes. {final_missing} still missing.{Colors.END}")
else:
print(f"{Colors.YELLOW}⚠ {final_missing} episodes still missing subtitles after {max_retries} retries.{Colors.END}")
# Update missing count for final action decision
missing_count = final_missing
# Handle remaining missing subtitles based on failure action
if missing_count > 0:
if args.on_subtitle_failure == 'exit':
print(f"{Colors.RED}Exiting due to missing subtitles. Use --on-subtitle-failure=continue to proceed anyway.{Colors.END}")
return
elif args.on_subtitle_failure == 'prompt':
response = input(f"\n{Colors.YELLOW}Continue with {missing_count} missing subtitles? (y/n): {Colors.END}").strip().lower()
if response not in ['y', 'yes']:
print(f"{Colors.YELLOW}Operation cancelled{Colors.END}")
return
else:
print(f"{Colors.GREEN}Continuing with available subtitles...{Colors.END}")
elif args.on_subtitle_failure == 'continue':
print(f"{Colors.YELLOW}Continuing with {missing_count} missing subtitles...{Colors.END}")
else:
print(f"{Colors.GREEN}✓ All episodes have subtitles{Colors.END}")
# Process each video file and collect all transcripts
video_transcripts = {}
print(f"Processing {len(video_paths)} video files...")
start_time = time.time()
for i, video_path in enumerate(video_paths, 1):
video_start = time.time()
if args.verbose:
print(f"\n{Colors.BLUE}Processing ({i}/{len(video_paths)}): {Colors.BOLD}{os.path.basename(video_path)}{Colors.END}")
else:
# Calculate ETA
if i > 1:
elapsed = time.time() - start_time
avg_time_per_video = elapsed / (i - 1)
remaining_videos = len(video_paths) - i + 1
eta_seconds = avg_time_per_video * remaining_videos
eta_minutes = int(eta_seconds // 60)
eta_secs = int(eta_seconds % 60)
eta_str = f" (ETA: {eta_minutes:02d}:{eta_secs:02d})"
else:
eta_str = ""
print(f" {i}/{len(video_paths)}: {os.path.basename(video_path)}{eta_str}", end="")
# Try to extract subtitles first if requested, otherwise use Whisper
transcript = None
if args.try_subtitles:
# Pass episodes_data and model for potential similarity matching
transcript = extract_subtitles(video_path, args.verbose, episodes_data, model, args)
if not transcript:
if args.verbose:
if args.try_subtitles:
print(" No subtitles found, transcribing with Whisper...")
else:
print(" Transcribing with Whisper...")
transcript = transcribe_audio(video_path, args.whisper_model, args.max_duration, args.start_offset, args.verbose, device)
else:
if args.verbose:
print(" Using extracted subtitles")
if transcript:
video_transcripts[video_path] = transcript
if args.verbose:
print(" Transcript extracted successfully")
else:
video_time = time.time() - video_start
print(f" ✓ ({video_time:.1f}s)")
else:
if args.verbose:
print(" Failed to get transcript")
else:
video_time = time.time() - video_start
print(f" ✗ ({video_time:.1f}s)")
# Find best matches ensuring no episode is matched to multiple videos
print(f"\nCalculating optimal matches...")
matches = find_unique_episode_matches(video_transcripts, episodes_data, model, args, args.verbose)
# Print results for each video
for video_path in video_paths:
if video_path in matches:
match = matches[video_path]
is_correct = is_correctly_named(video_path, match['episode'])
if is_correct:
status_color = Colors.GREEN
status_icon = "✓"
status_text = "(correctly named)"
else:
status_color = Colors.RED
status_icon = "→"
status_text = "(needs renaming)"
similarity_colored = colorize_similarity(match['similarity'])
print(f" {status_color}{status_icon} Best match: {match['episode']} {status_text}{Colors.END}")
print(f" Similarity: {similarity_colored}")
else:
print(f" {Colors.RED}✗ No good match found for {os.path.basename(video_path)}{Colors.END}")
# Print final results
print(f"\n{Colors.BOLD}{Colors.UNDERLINE}=== FINAL MATCHES ==={Colors.END}")
for video_path, match in matches.items():
is_correct = is_correctly_named(video_path, match['episode'])
if is_correct:
filename_color = Colors.GREEN
status_icon = "✓"
else:
filename_color = Colors.RED
status_icon = "→"
similarity_colored = colorize_similarity(match['similarity'])
print(f"{filename_color}{status_icon} {os.path.basename(video_path)} -> {match['episode']}{Colors.END}")
print(f" Similarity: {similarity_colored}")
print()
# Handle file renaming based on user preference
if matches and args.rename != 'none':
rename_files(matches, args.rename, show_info)
def get_video_files(video_dir):
"""Get all video files from directory"""
video_extensions = {'.mp4', '.m4v', '.avi', '.mov', '.mkv', '.wmv', '.flv', '.webm'}
video_paths = []
for name in os.listdir(video_dir):
file_path = os.path.join(video_dir, name)
if os.path.isfile(file_path) and any(name.lower().endswith(ext) for ext in video_extensions):
video_paths.append(file_path)
return video_paths
def parse_plex_structure(video_path):
"""Parse Plex-style directory structure to extract show and season info"""
# Normalize path separators
path = os.path.normpath(video_path)
parts = path.split(os.sep)
show_name = None
season_num = None
# Look for show name and season in path
for i, part in enumerate(parts):
# Look for "Season X" pattern
season_match = re.search(r'Season\s+(\d+)', part, re.IGNORECASE)
if season_match:
season_num = int(season_match.group(1))
# Show name is usually the parent directory
if i > 0:
show_name = parts[i-1]
break
# If no season found, try to get show from parent directories
if not show_name and len(parts) >= 2:
show_name = parts[-2] # Parent directory of the file
season_num = 1 # Default to season 1
return {
'show': show_name or 'Unknown Show',
'season': season_num or 1
}
def get_tvdb_episodes(show_info, api_key, verbose=False):
"""Get episode data (descriptions) from TVDB API"""
tvdb = TVDB(api_key)
try:
# Search for the show
search_results = tvdb.search(show_info['show'])
if not search_results:
print(f"No results found for '{show_info['show']}'")
return [], None
series_id = search_results[0]['tvdb_id']
proper_show_name = search_results[0]['name']
if verbose:
print(f"Found series: {proper_show_name} (ID: {series_id})")
# Get all episodes for the series
episodes_response = tvdb.get_series_episodes(series_id)
# Handle different response formats
if isinstance(episodes_response, dict) and 'episodes' in episodes_response:
all_episodes = episodes_response['episodes']
elif isinstance(episodes_response, dict) and 'data' in episodes_response:
all_episodes = episodes_response['data']
else:
all_episodes = episodes_response
# Filter episodes for the specific season and extract relevant data
episodes_data = []
for ep in all_episodes:
season_num = ep.get('seasonNumber') or ep.get('season')
if season_num == show_info['season']:
episode_data = {
'number': ep.get('number', 0),
'name': ep.get('name', 'Unknown'),
'overview': ep.get('overview', ''),
'episode_id': f"S{show_info['season']:02d}E{ep.get('number', 0):02d} - {ep.get('name', 'Unknown')}"
}
episodes_data.append(episode_data)
return episodes_data, proper_show_name
except Exception as e:
print(f"TVDB API error: {e}")
return [], None
def get_tmdb_episodes(show_info, api_key, verbose=False):
"""Get episode data (descriptions) from TMDB API"""
tmdb.API_KEY = api_key
try:
# Search for the show
search = tmdb.Search()
response = search.tv(query=show_info['show'])
if not response['results']:
print(f"No results found for '{show_info['show']}'")
return [], None
# Get the first result
show = response['results'][0]
show_id = show['id']
proper_show_name = show['name']
if verbose:
print(f"Found series: {proper_show_name} (ID: {show_id})")
# Get season details to get episodes
tv_seasons = tmdb.TV_Seasons(show_id, show_info['season'])
season_details = tv_seasons.info()
# Extract episode data
episodes_data = []
for ep in season_details.get('episodes', []):
episode_data = {
'number': ep.get('episode_number', 0),
'name': ep.get('name', 'Unknown'),
'overview': ep.get('overview', ''),
'episode_id': f"S{show_info['season']:02d}E{ep.get('episode_number', 0):02d} - {ep.get('name', 'Unknown')}"
}
episodes_data.append(episode_data)
return episodes_data, proper_show_name
except Exception as e:
print(f"TMDB API error: {e}")
return [], None
def get_subliminal_episode_subtitles(show_info, episodes_data, verbose=False, no_cache=False):
"""Get episode subtitles using subliminal library with caching support"""
import tempfile
from pathlib import Path
subtitles_data = []
cache_hits = 0
downloads = 0
if verbose:
print(f" Attempting to get subtitles for {len(episodes_data)} episodes (checking cache first)...")
for episode in episodes_data:
if verbose:
print(f" Processing Episode {episode['number']}...")
# Check cache first (unless disabled)
cached_content, cached_text, metadata = None, None, None
if not no_cache:
cached_content, cached_text, metadata = load_subtitle_from_cache(
show_info['show'], show_info['season'], episode['number'], verbose
)
if cached_content and cached_text:
# Use cached subtitles
episode_with_subtitles = episode.copy()
episode_with_subtitles['subtitle_text'] = cached_text
episode_with_subtitles['subtitle_content'] = cached_content
subtitles_data.append(episode_with_subtitles)
cache_hits += 1
continue
# Not in cache, download with subliminal
if verbose:
print(f" No cache found, downloading...")
# Not in cache, download with subliminal
if verbose:
print(f" No cache found, downloading...")
# Create temporary directory for video simulation
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
try:
# Create a fake video file for subliminal to work with
episode_name = f"{show_info['show']}.S{show_info['season']:02d}E{episode['number']:02d}.mkv"
fake_video_path = temp_path / episode_name
fake_video_path.touch()
# Create Episode object for subliminal
video = Episode(
name=str(fake_video_path),
series=show_info['show'],
season=show_info['season'],
episodes=[episode['number']] # Pass as list of episode numbers
)
# Try different provider strategies to increase success rate
# Let subliminal manage available providers instead of hardcoding lists
try:
# Get all available providers from subliminal
all_providers = list(provider_manager.names())
reliable_providers = ['opensubtitles', 'podnapisi', 'addic7ed']
# Filter reliable providers to only those actually available
reliable_providers = [p for p in reliable_providers if p in all_providers]
except Exception:
# Fallback if provider discovery fails
all_providers = None
reliable_providers = ['opensubtitles', 'podnapisi']
provider_strategies = [
# First try: Just the most reliable providers
reliable_providers,
# Second try: All available providers (let subliminal decide)
all_providers,
# Last try: OpenSubtitles only
['opensubtitles']
]
subtitles = None
for providers in provider_strategies:
# Skip None strategies (in case provider discovery failed)
if providers is None:
continue
try:
if verbose:
if providers == all_providers:
print(f" Trying all available providers ({len(providers) if providers else 0} total)")
else:
print(f" Trying providers: {', '.join(providers)}")
# Download best subtitles (tries multiple providers automatically)
subtitles = download_best_subtitles(
[video],
languages={'en'},
providers=providers,
provider_configs={
'opensubtitles': {
'username': os.getenv('OPENSUBTITLES_USERNAME', ''),
'password': os.getenv('OPENSUBTITLES_PASSWORD', '')
},
'addic7ed': {
'username': os.getenv('ADDIC7ED_USERNAME', ''),
'password': os.getenv('ADDIC7ED_PASSWORD', '')
}
}
)
# If we got subtitles, break out of the retry loop
if video in subtitles and subtitles[video]:
break
except Exception as provider_error:
if verbose:
strategy_desc = "all providers" if providers == all_providers else f"providers {providers}"
print(f" Strategy '{strategy_desc}' failed: {provider_error}")
# Small delay after failed provider attempts to avoid hammering
time.sleep(0.3)
continue
if subtitles and video in subtitles and subtitles[video]:
# Get the best subtitle
best_subtitle = max(subtitles[video], key=lambda s: getattr(s, 'score', 0))
try:
subtitle_text = best_subtitle.content.decode('utf-8') if best_subtitle.content else ''
except UnicodeDecodeError:
# Try different encodings
try:
subtitle_text = best_subtitle.content.decode('latin-1') if best_subtitle.content else ''
except:
subtitle_text = ''
if subtitle_text:
# Parse subtitle content to extract text
clean_text = parse_subtitle_content(subtitle_text)
if clean_text:
# Save to cache (unless disabled)
if not no_cache:
save_subtitle_to_cache(
show_info['show'],
show_info['season'],
episode['number'],
subtitle_text,
clean_text,
best_subtitle.provider_name
)
episode_with_subtitles = episode.copy()
episode_with_subtitles['subtitle_text'] = clean_text
episode_with_subtitles['subtitle_content'] = subtitle_text # Store raw content for time extraction
subtitles_data.append(episode_with_subtitles)
downloads += 1
if verbose:
print(f" ✓ Downloaded and cached subtitles ({len(clean_text)} chars) from {best_subtitle.provider_name}")
else:
# Failed to extract text, use description
subtitles_data.append(episode)
if verbose:
print(f" ✗ Failed to extract text from subtitle")
else:
# No content, use description
subtitles_data.append(episode)
if verbose:
print(f" ✗ Empty subtitle content")
else:
# No subtitles found, use description
subtitles_data.append(episode)
if verbose:
print(f" ✗ No subtitles found from any provider")
# Clean up the fake file
fake_video_path.unlink()
except Exception as e:
# Error, use description
subtitles_data.append(episode)
if verbose:
print(f" ✗ Error: {e}")
# Rate limiting - be respectful to providers
time.sleep(1.0)
# Summary
subtitle_count = sum(1 for ep in subtitles_data if 'subtitle_text' in ep)
if verbose:
print(f" Results: {cache_hits} from cache, {downloads} downloaded, {subtitle_count}/{len(episodes_data)} total with subtitles")
return subtitles_data
def retry_missing_subtitles(show_info, episodes_data, max_retries, verbose=False, no_cache=False):
"""Retry downloading subtitles for episodes that don't have them, with exponential backoff"""
import tempfile
from pathlib import Path
missing_episodes = [ep for ep in episodes_data if 'subtitle_text' not in ep or not ep['subtitle_text']]
if not missing_episodes:
return episodes_data
if verbose:
print(f"\n{Colors.YELLOW}Retrying subtitle download for {len(missing_episodes)} episodes...{Colors.END}")
for retry_attempt in range(max_retries):
if not missing_episodes:
break
backoff_delay = 2 * (2 ** retry_attempt) # Exponential backoff: 2s, 4s, 8s, 16s...
if verbose:
print(f"\n Retry attempt {retry_attempt + 1}/{max_retries} (delay: {backoff_delay}s)...")
if retry_attempt > 0:
print(f" Waiting {backoff_delay} seconds...")
time.sleep(backoff_delay)
newly_found = []
still_missing = []
for episode in missing_episodes:
if verbose:
print(f" Retrying Episode {episode['number']}...")
# Try again with same logic as original download
with tempfile.TemporaryDirectory() as temp_dir:
temp_path = Path(temp_dir)
try:
# Create enhanced fake video file
clean_episode_name = re.sub(r'[<>:"/\\|?*]', '', episode.get('name', 'Unknown')).strip()
episode_filename = f"{show_info['show']}.S{show_info['season']:02d}E{episode['number']:02d}.{clean_episode_name}.mkv"
fake_video_path = temp_path / episode_filename
fake_video_path.touch()
# Create Episode object
video = Episode(
name=str(fake_video_path),
series=show_info['show'],
season=show_info['season'],
episodes=[episode['number']],
title=episode.get('name', 'Unknown'),
year=episode.get('year'),
imdb_id=episode.get('imdb_id'),
size=0,
)
# Try providers with longer delay
try:
all_providers = list(provider_manager.names())
reliable_providers = ['opensubtitles', 'podnapisi', 'addic7ed']
reliable_providers = [p for p in reliable_providers if p in all_providers]
except Exception:
all_providers = None
reliable_providers = ['opensubtitles', 'podnapisi']
# Only try reliable providers for retries
subtitles = download_best_subtitles(
[video],
languages={'en'},
providers=reliable_providers,
provider_configs={
'opensubtitles': {
'username': os.getenv('OPENSUBTITLES_USERNAME', ''),
'password': os.getenv('OPENSUBTITLES_PASSWORD', '')
},
'addic7ed': {
'username': os.getenv('ADDIC7ED_USERNAME', ''),
'password': os.getenv('ADDIC7ED_PASSWORD', '')
}
}
)
if subtitles and video in subtitles and subtitles[video]:
best_subtitle = max(subtitles[video], key=lambda s: getattr(s, 'score', 0))
try:
subtitle_text = best_subtitle.content.decode('utf-8') if best_subtitle.content else ''
except UnicodeDecodeError:
try:
subtitle_text = best_subtitle.content.decode('latin-1') if best_subtitle.content else ''
except:
subtitle_text = ''
if subtitle_text:
clean_text = parse_subtitle_content(subtitle_text)
if clean_text:
# Save to cache
if not no_cache:
save_subtitle_to_cache(
show_info['show'],
show_info['season'],
episode['number'],
subtitle_text,
clean_text,
best_subtitle.provider_name
)
# Update episode data
episode['subtitle_text'] = clean_text
episode['subtitle_content'] = subtitle_text
newly_found.append(episode)
if verbose:
print(f" ✓ Found subtitles ({len(clean_text)} chars) from {best_subtitle.provider_name}")
continue
# Still no subtitles found
still_missing.append(episode)
if verbose:
print(f" ✗ Still no subtitles found")
except Exception as e:
still_missing.append(episode)
if verbose:
print(f" ✗ Error: {e}")
# Rate limiting between episodes
time.sleep(1.0)
missing_episodes = still_missing
if newly_found:
if verbose:
print(f" Found subtitles for {len(newly_found)} more episodes")
if not missing_episodes:
if verbose:
print(f" ✓ All episodes now have subtitles!")
break
if missing_episodes and verbose:
print(f" ✗ {len(missing_episodes)} episodes still missing subtitles after {max_retries} retries")
return episodes_data
def parse_subtitle_content(content):
"""Parse subtitle content and extract clean text using pysubs2"""
try:
# Use pysubs2 to parse subtitle content (supports SRT, VTT, ASS, etc.)
subs = pysubs2.SSAFile.from_string(content)
text_lines = [event.plaintext for event in subs if event.plaintext.strip()]
return ' '.join(text_lines)
except Exception as e:
# Fallback to manual parsing if pysubs2 fails
lines = content.split('\n')
text_lines = []
for line in lines:
line = line.strip()
# Skip empty lines, numbers, timestamps, and format markers
if (line and
not line.isdigit() and
not re.match(r'\d{2}:\d{2}:\d{2}', line) and
not line.startswith('WEBVTT') and
not line.startswith('NOTE') and
not re.match(r'\d+$', line)):
# Clean HTML tags and formatting
clean_line = re.sub(r'<[^>]+>', '', line)
clean_line = re.sub(r'\{[^}]+\}', '', clean_line)
clean_line = re.sub(r'\\N', ' ', clean_line) # ASS format line breaks
clean_line = clean_line.strip()
if clean_line:
text_lines.append(clean_line)
return ' '.join(text_lines)
def load_local_episode_subtitles(show_info, episodes_data, subtitles_dir, verbose=False):
"""Load episode subtitles from local directory"""
if not os.path.isdir(subtitles_dir):
print(f"Subtitles directory not found: {subtitles_dir}")
return episodes_data
subtitle_extensions = {'.srt', '.vtt', '.ass', '.ssa'}
subtitles_data = []
# Get all subtitle files in directory
subtitle_files = []
for filename in os.listdir(subtitles_dir):
if any(filename.lower().endswith(ext) for ext in subtitle_extensions):
subtitle_files.append(os.path.join(subtitles_dir, filename))
if verbose:
print(f" Found {len(subtitle_files)} subtitle files in directory")
for episode in episodes_data:
episode_with_subtitles = episode.copy()
# Try to find matching subtitle file
matched_file = find_matching_subtitle_file(
episode, show_info, subtitle_files, verbose
)
if matched_file:
subtitle_text = parse_subtitle_file(matched_file, verbose)
if subtitle_text:
episode_with_subtitles['subtitle_text'] = subtitle_text
if verbose:
print(f" ✓ {episode['episode_id']}: {os.path.basename(matched_file)} ({len(subtitle_text)} chars)")
else:
if verbose:
print(f" ✗ {episode['episode_id']}: Failed to parse {os.path.basename(matched_file)}")
else:
if verbose:
print(f" ✗ {episode['episode_id']}: No matching subtitle file found")
subtitles_data.append(episode_with_subtitles)
return subtitles_data
def find_matching_subtitle_file(episode, show_info, subtitle_files, verbose=False):
"""Find subtitle file that matches the episode"""
season_str = f"S{show_info['season']:02d}"
episode_str = f"E{episode['number']:02d}"
episode_patterns = [
f"{season_str}{episode_str}", # S01E05
f"{show_info['season']}x{episode['number']:02d}", # 1x05
f"Season {show_info['season']} Episode {episode['number']}", # Season 1 Episode 5
f"s{show_info['season']:02d}e{episode['number']:02d}", # s01e05
episode['name'].lower().replace(' ', '.'), # episode.name
]
# Score each subtitle file
best_match = None
best_score = 0
for subtitle_file in subtitle_files:
filename = os.path.basename(subtitle_file).lower()
score = 0
# Check for episode patterns
for pattern in episode_patterns:
if pattern.lower() in filename:
score += 10
break
# Check for show name
if show_info['show'].lower().replace(' ', '.') in filename.replace(' ', '.'):
score += 5
# Prefer files with exact season/episode match
if f"{season_str.lower()}{episode_str.lower()}" in filename:
score += 20
if score > best_score:
best_score = score
best_match = subtitle_file
return best_match if best_score > 0 else None