-
Notifications
You must be signed in to change notification settings - Fork 0
/
jellyfin-renamer.py
1428 lines (1102 loc) · 44.1 KB
/
jellyfin-renamer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import json
import os
import pickle
import re
import requests
import shutil
import signal
import subprocess
import sys
import time
import atexit
import Levenshtein
from pathlib import Path
from dataclasses import dataclass, field
from typing import *
from enum import Enum
TMDB_API_KEY_FILE = os.getenv("TMDB_API_KEY_FILE") or "./.tmdb-api-key"
def read_auth_file_or_default():
if TMDB_API_KEY_FILE == "" or TMDB_API_KEY_FILE is None:
return os.getenv("TMDB_API_KEY")
try:
with open(TMDB_API_KEY_FILE, "r") as f:
return f.read().strip()
except:
return os.getenv("TMDB_API_KEY")
auth_key = read_auth_file_or_default()
auth_header = {"Authorization": f"Bearer {auth_key}"}
re._MAXCACHE = 4096
re_redact_api_key = re.compile("(?<=api_key=)[^&]+")
last_request_time = 0
def do_authed_get_and_handle_err(url: str):
import time
global last_request_time
if last_request_time > 0:
time_since_last_request = time.time() - last_request_time
if time_since_last_request < 0.02:
time.sleep(0.01)
last_request_time = time.time()
print(f"do_authed_get_and_handle_err: {re_redact_api_key.sub('***', url)}")
try:
obj = json.loads(requests.get(url, headers=auth_header).content)
if "error" in obj or "errors" in obj:
return None
return obj
except requests.exceptions.ConnectionError:
print("do_authed_get_and_handle_err: connection error", file=sys.stderr)
return None
except requests.exceptions.HTTPError as err:
print(
f"do_authed_get_and_handle_err: HTTP error {err.response.status_code}",
file=sys.stderr,
)
return None
except requests.exceptions.Timeout:
print("do_authed_get_and_handle_err: HTTP timeout", file=sys.stderr)
return None
except requests.exceptions.RequestException:
print("do_authed_get_and_handle_err: request exception", file=sys.stderr)
return None
except json.JSONDecodeError:
print("do_authed_get_and_handle_err: could not parse JSON", file=sys.stderr)
return None
except:
print("do_authed_get_and_handle_err: unhandled error", file=sys.stderr)
return None
tmdb_genres: Dict[int, str] = {}
def query_all_genres():
global tmdb_genres
if len(tmdb_genres) > 0:
return
movie_genres = do_authed_get_and_handle_err(
"https://api.themoviedb.org/3/genre/movie/list"
)
show_genres = do_authed_get_and_handle_err(
"https://api.themoviedb.org/3/genre/tv/list"
)
if movie_genres is None or show_genres is None:
return
if "genres" not in movie_genres or "genres" not in show_genres:
return
# just merge them together, seems the id's are the same
tmdb_genres = {
genre["id"]: genre["name"]
for genre in [*movie_genres["genres"], *show_genres["genres"]]
}
has_ffprobe = subprocess.run(["which", "ffprobe"], capture_output=True).returncode == 0
def ffprobe_width_and_height(path: Path) -> Optional[Tuple[int, int]]:
if not has_ffprobe:
return None
result = subprocess.run(
[
"ffprobe",
"-v",
"error",
"-select_streams",
"v:0",
"-show_entries",
"stream=width,height",
"-of",
"csv=s=x:p=0",
str(path),
],
capture_output=True,
text=True,
)
if result.returncode != 0:
return None
width, height = result.stdout.strip().split("x")
return int(width), int(height)
def get_resolution_from_ffprobe(
widthheight: Optional[Tuple[int, int]]
) -> Optional[str]:
if widthheight is None:
return None
width, _ = widthheight
if width >= 15360:
return "16K"
elif width >= 7680:
return "8K"
elif width >= 3840:
return "4K"
elif width >= 1920:
return "1080p"
elif width >= 1280:
return "720p"
elif width >= 854:
return "480p"
else:
return "SD"
no_interact = False
no_caches = False
tmdb_not_found: Set[str] = set()
@dataclass
class TmdbShow:
name: str
id: int
genre_ids: List[int]
genres: List[str]
first_air_date: str
tmdb_show_name_cache: Dict[str, List[TmdbShow]] = {}
def query_show(name: str, year: Optional[int]) -> List[TmdbShow]:
global tmdb_not_found
global tmdb_show_name_cache
if name in tmdb_not_found:
return []
if name in tmdb_show_name_cache:
return tmdb_show_name_cache[name]
year = f"&first_air_date_year={year:04d}" if year is not None else ""
url = f"https://api.themoviedb.org/3/search/tv?query={name}{year}&include_adult=true&api_key={auth_key}"
obj = do_authed_get_and_handle_err(url)
if obj is None:
tmdb_not_found.add(name)
return []
if "results" not in obj:
tmdb_not_found.add(name)
return []
results = obj["results"]
ret = []
for result in results:
id = result["id"] if "id" in result else None
name = result["name"] if "name" in result else None
genre_ids = result["genre_ids"] if "genre_ids" in result else None
first_air_date = (
result["first_air_date"] if "first_air_date" in result else None
)
if id is None or name is None or genre_ids is None or first_air_date is None:
continue
genres = [tmdb_genres[genre_id] for genre_id in genre_ids]
ret.append(TmdbShow(name, id, genre_ids, genres, first_air_date))
tmdb_show_name_cache[name] = ret
return ret
@dataclass
class TmdbMovie:
title: str
id: int
genre_ids: List[int]
genres: List[str]
release_date: str
tmdb_movie_name_cache: Dict[str, List[TmdbMovie]] = {}
def query_movie(title: str, year: Optional[int]) -> List[TmdbMovie]:
global tmdb_not_found
if title in tmdb_not_found:
return []
if title in tmdb_movie_name_cache:
return tmdb_movie_name_cache[title]
year = f"&primary_release_year={year:04d}" if year is not None else ""
url = f"https://api.themoviedb.org/3/search/movie?query={title}{year}&include_adult=true&api_key={auth_key}"
obj = do_authed_get_and_handle_err(url)
if obj is None:
tmdb_not_found.add(title)
return []
if "results" not in obj:
tmdb_not_found.add(title)
return []
results = obj["results"]
ret = []
for result in results:
id = result["id"] if "id" in result else None
title = result["title"] if "title" in result else None
genre_ids = result["genre_ids"] if "genre_ids" in result else None
release_date = result["release_date"] if "release_date" in result else None
if id is None or title is None or genre_ids is None or release_date is None:
continue
genres = [tmdb_genres[genre_id] for genre_id in genre_ids]
ret.append(TmdbMovie(title, id, genre_ids, genres, release_date))
tmdb_movie_name_cache[title] = ret
return ret
cache_time: Dict[str, int] = {}
def write_caches():
if no_caches:
return
global cache_time
global tmdb_genres
global tmdb_show_id_cache
global tmdb_movie_id_cache
global tmdb_details_tv_season_cache
global tmdb_details_movie_cache
global tmdb_movie_name_cache
global tmdb_show_name_cache
def write_cache(name: str, obj: object, ignore_time=False):
if not ignore_time:
cache_time[name] = int(time.time())
with open(name, "wb") as f:
pickle.dump(obj, f)
write_cache("all_genres.cache.pickle", tmdb_genres)
write_cache("tmdb_show_id.cache.pickle", tmdb_show_id_cache)
write_cache("tmdb_movie_id.cache.pickle", tmdb_movie_id_cache)
write_cache("tmdb_details_tv_season.cache.pickle", tmdb_details_tv_season_cache)
write_cache("tmdb_details_movie.cache.pickle", tmdb_details_movie_cache)
write_cache("tmdb_movie_name.cache.pickle", tmdb_movie_name_cache)
write_cache("tmdb_show_name.cache.pickle", tmdb_show_name_cache)
write_cache("cache_time.cache.pickle", cache_time, ignore_time=True)
def load_caches():
global cache_time
global tmdb_genres
global tmdb_show_id_cache
global tmdb_movie_id_cache
global tmdb_details_tv_season_cache
global tmdb_details_movie_cache
global tmdb_movie_name_cache
global tmdb_show_name_cache
def read_cache(name: str, ignore_time=False):
if not ignore_time:
if name not in cache_time:
return {}
if int(time.time()) - cache_time[name] > 86400:
return {}
try:
with open(name, "rb") as f:
return pickle.load(f)
except:
return {}
cache_time = read_cache("cache_time.cache.pickle", ignore_time=True)
tmdb_genres = read_cache("all_genres.cache.pickle")
tmdb_show_id_cache = read_cache("tmdb_show_id.cache.pickle")
tmdb_movie_id_cache = read_cache("tmdb_movie_id.cache.pickle")
tmdb_details_tv_season_cache = read_cache("tmdb_details_tv_season.cache.pickle")
tmdb_details_movie_cache = read_cache("tmdb_details_movie.cache.pickle")
tmdb_movie_name_cache = read_cache("tmdb_movie_name.cache.pickle")
tmdb_show_name_cache = read_cache("tmdb_show_name.cache.pickle")
class MediaType(Enum):
MOVIE = "movie"
SHOW = "show"
class ShowType(Enum):
FEATURETTE = "Featurette"
SHOW = "Show"
SAMPLE = "Sample"
class FeaturetteTag(Enum):
BEHIND_THE_SCENES = "Behind the Scenes"
INTERVIEW = "Interview"
MAKING_OF = "Making Of"
PROMO = "Promo"
TRAILER = "Trailer"
TEASER = "Teaser"
WEBISODE = "Webisode" # only really for parks n rec
DELETED_SCENE = "Deleted Scene"
EXTRA = "Extra"
@dataclass
class Show:
media_type: MediaType = MediaType.SHOW
title: Optional[str] = None
name: Optional[str] = None
extension: str = ""
show_type: Optional[ShowType] = None
featurette_tags: List[FeaturetteTag] = field(default_factory=list)
season: Optional[int] = None
episode: Optional[int] = None
episode_end: Optional[int] = None
resolution: Optional[str] = None
year: Optional[int] = None
fullpath: Optional[str] = None
subtitle_paths: List[str] = field(default_factory=list)
tmdb_id: Optional[int] = None
remove_parts: List[str] = []
def parse_show_or_movie_path(path: Path, media_type: MediaType) -> Optional[Show]:
global remove_parts
show = Show()
show.media_type = media_type
show.show_type = ShowType.SHOW
show.fullpath = str(path)
extension = path.suffix[1:]
path: str = str(path)[: -len(extension)]
show.extension = extension
if extension not in [
"mp4",
"mkv",
"avi",
"webm",
"flv",
"mov",
"wmv",
"m4v",
"3gp",
"3g2",
]:
return None
def replace_separators_with_spaces(s: str) -> str:
return re.sub(r"[._\s]+", " ", s)
def remove_disallowed_chars(s: str) -> str:
return re.sub(r"[^a-zA-Z0-9åäöũỹẽß\s\(\)\[\]\-]", "", s)
def exec_regex(regex: re.Pattern, s: str) -> Tuple[str, Optional[str]]:
match = regex.search(s)
if match is None:
return s, None
s = re.compile(r"\s+").sub(" ", s[: match.start()] + s[match.end() :])
return s, match.group(0)
if len(remove_parts) == 0:
try:
with open("extra_disallowed.txt", "r") as f:
remove_parts = f.read().split("\n")
except:
pass
removed_parts = []
parts = path.split("/")
first = True
while len(parts) > 0:
part = parts.pop(0)
part = replace_separators_with_spaces(part)
part = remove_disallowed_chars(part)
subparts = re.compile(r"\b-\b").split(part)
if len(subparts) > 1:
parts = subparts + parts
continue
for removed_part in removed_parts:
part = part.replace(removed_part, "")
for disallowed in remove_parts:
part = re.compile(r"\b" + disallowed + r"\b", re.IGNORECASE).sub("", part)
if part == "":
continue
part, featurette = exec_regex(re.compile(r"featurettes?", re.IGNORECASE), part)
if featurette is not None:
show.show_type = ShowType.FEATURETTE
removed_parts.append(featurette)
part, sample = exec_regex(re.compile(r"sample", re.IGNORECASE), part)
if sample is not None:
show.show_type = ShowType.SAMPLE
removed_parts.append(sample)
if show.year is None:
part, year = exec_regex(re.compile(r"[\[\(]?\d{4}[^p][\]\)]?"), part)
if year is not None:
removed_parts.append(year)
try:
show.year = int(year.strip("()[] "))
except:
pass
if show.season is None or show.episode is None:
part, season_episode_episode_end = exec_regex(
re.compile(r"S\d+E\d+\-E\d+", re.IGNORECASE), part
)
if season_episode_episode_end is not None:
removed_parts.append(season_episode_episode_end)
try:
season_episode_episode_end = season_episode_episode_end[1:]
season_episode, episode_end = season_episode_episode_end.split("-E")
season, episode = season_episode.upper().split("E")
show.season = int(season)
show.episode = int(episode)
show.episode_end = int(episode_end)
except:
pass
if show.season is None or show.episode is None:
part, season_episode = exec_regex(
re.compile(r"S\d+E\d+", re.IGNORECASE), part
)
if season_episode is not None:
removed_parts.append(season_episode)
try:
season_episode = season_episode[1:]
season, episode = season_episode.upper().split("E")
show.season = int(season)
show.episode = int(episode)
except:
pass
if show.season is None:
part, season = exec_regex(re.compile(r"season \d+", re.IGNORECASE), part)
if season is not None:
removed_parts.append(season)
try:
show.season = int(season[7:])
except:
pass
if show.resolution is None:
part, resolution = exec_regex(
re.compile(r"8k|4k|4320p|2160p|1080p|720p|480p", re.IGNORECASE), part
)
if resolution is not None:
removed_parts.append(resolution)
if resolution.lower() == "4k":
show.resolution = "2160p"
elif resolution.lower() == "8k":
show.resolution = "4320p"
else:
show.resolution = resolution
if first:
first = False
# removed_parts.append(part) # not adding this since its the show name, and sometimes an episode is called the same
show.title = part.strip()
continue
if len(parts) == 0:
if part.find("(") != -1:
last_paren = part.rfind("(")
name, part = part[:last_paren], part[last_paren:]
show.name = name.strip()
else:
found = False
for disallowed in remove_parts:
if (
re.compile(r"\b" + disallowed + r"\b", re.IGNORECASE).match(
part
)
is not None
):
found = True
break
if not found:
show.name = part.strip()
if show.show_type == ShowType.FEATURETTE:
_, tag = exec_regex(re.compile(r"behind the", re.IGNORECASE), path)
if tag is not None:
show.featurette_tags.append(FeaturetteTag.BEHIND_THE_SCENES)
_, tag = exec_regex(re.compile(r"interview", re.IGNORECASE), path)
if tag is not None:
show.featurette_tags.append(FeaturetteTag.INTERVIEW)
_, tag = exec_regex(re.compile(r"making of", re.IGNORECASE), path)
if tag is not None:
show.featurette_tags.append(FeaturetteTag.MAKING_OF)
_, tag = exec_regex(re.compile(r"promo", re.IGNORECASE), path)
if tag is not None:
show.featurette_tags.append(FeaturetteTag.PROMO)
_, tag = exec_regex(re.compile(r"trailer", re.IGNORECASE), path)
if tag is not None:
show.featurette_tags.append(FeaturetteTag.TRAILER)
_, tag = exec_regex(re.compile(r"teaser", re.IGNORECASE), path)
if tag is not None:
show.featurette_tags.append(FeaturetteTag.TEASER)
_, tag = exec_regex(re.compile(r"webisode", re.IGNORECASE), path)
if tag is not None:
show.featurette_tags.append(FeaturetteTag.WEBISODE)
_, tag = exec_regex(re.compile(r"deleted scene", re.IGNORECASE), path)
if tag is not None:
show.featurette_tags.append(FeaturetteTag.DELETED_SCENE)
_, tag = exec_regex(re.compile(r"extra", re.IGNORECASE), path)
if tag is not None:
show.featurette_tags.append(FeaturetteTag.EXTRA)
return show
tmdb_show_id_cache: Dict[str, int] = {}
tmdb_movie_id_cache: Dict[str, int] = {}
tmdb_details_tv_season_cache: Dict[str, object] = {}
tmdb_details_movie_cache: Dict[str, object] = {}
def query_tmdb_id(show: Show) -> Optional[int]:
global tmdb_show_id_cache
global tmdb_not_found
if show.title in tmdb_show_id_cache:
return tmdb_show_id_cache[show.title]
if show.media_type == MediaType.SHOW:
if show.title in tmdb_not_found:
return None
tmdb_shows = query_show(show.title, show.year)
if len(tmdb_shows) == 0:
return None
id = -1
found = 0
for tmdb_movie in tmdb_shows:
if show.year is not None and tmdb_movie.first_air_date[:4] == str(
show.year
):
id = tmdb_movie.id
found += 1
if no_interact and len(tmdb_shows) > 1:
print("no interact: selecting first movie")
id = tmdb_shows[0].id
found = 0
if (id == -1 or found > 1) and len(tmdb_shows) > 1:
print(f"Multiple shows found for {show.title} ({show.year})")
print("Please select one of the following:")
for i, tmdb_movie in enumerate(tmdb_shows):
print(
f"{i + 1}: {tmdb_movie.name} ({tmdb_movie.first_air_date}) id={tmdb_movie.id} [{', '.join(tmdb_movie.genres)}]"
)
while True:
try:
selection = int(input("Selection: ")) - 1
if selection < 0 or selection >= len(tmdb_shows):
raise ValueError()
id = tmdb_shows[selection].id
break
except ValueError:
print("Invalid selection")
else:
id = tmdb_shows[0].id
tmdb_show_id_cache[show.title] = id
else:
if show.title in tmdb_not_found:
return None
tmdb_movies = query_movie(show.title, show.year)
if len(tmdb_movies) == 0:
return None
id = -1
found = 0
for tmdb_movie in tmdb_movies:
if show.year is not None and tmdb_movie.release_date[:4] == str(show.year):
id = tmdb_movie.id
found += 1
if no_interact and len(tmdb_movies) > 1:
print("no interact: selecting first movie")
id = tmdb_movies[0].id
found = 0
if (id == -1 or found > 1) and len(tmdb_movies) > 1:
print(f"Multiple movies found for {show.title} ({show.year})")
print("Please select one of the following:")
for i, tmdb_movie in enumerate(tmdb_movies):
print(
f"{i + 1}: {tmdb_movie.title} ({tmdb_movie.release_date}) id={tmdb_movie.id} [{', '.join(tmdb_movie.genres)}]"
)
while True:
try:
selection = int(input("Selection: ")) - 1
if selection < 0 or selection >= len(tmdb_movies):
raise ValueError()
id = tmdb_movies[selection].id
break
except ValueError:
print("Invalid selection")
else:
id = tmdb_movies[0].id
tmdb_movie_id_cache[show.title] = id
if id == -1:
return None
return id
def query_tmdb_details(show: Show) -> Optional[object]:
global tmdb_details_tv_season_cache
global tmdb_details_movie_cache
global tmdb_not_found
if show.media_type == MediaType.SHOW:
key = ""
if show.season is None:
key = f"{show.title} noseason"
else:
key = f"{show.title} S{show.season}"
if show.title in tmdb_not_found:
return None
if key in tmdb_details_tv_season_cache:
return tmdb_details_tv_season_cache[key]
show_id = query_tmdb_id(show)
if show_id is None:
return None
show_obj = do_authed_get_and_handle_err(
f"https://api.themoviedb.org/3/tv/{show_id}?api_key={auth_key}"
)
season_obj: object = None
if show.season is None:
season_obj = do_authed_get_and_handle_err(
f"https://api.themoviedb.org/3/tv/{show_id}/season/{show.season}?api_key={auth_key}"
)
else:
season_obj = do_authed_get_and_handle_err(
f"https://api.themoviedb.org/3/tv/{show_id}/season/{show.season}?api_key={auth_key}"
)
if season_obj is None:
tmdb_not_found.add(show.title)
return None
if show_obj is not None and "first_air_date" in show_obj:
season_obj["first_air_date"] = show_obj["first_air_date"]
if show_obj is not None and "id" in show_obj:
season_obj["show_id"] = show_obj["id"]
tmdb_details_tv_season_cache[key] = season_obj
return season_obj
else:
if show.title in tmdb_details_movie_cache:
return tmdb_details_movie_cache[show.title]
if show.title in tmdb_not_found:
return None
movie_id = query_tmdb_id(show)
if movie_id is None:
return None
movie_obj = do_authed_get_and_handle_err(
f"https://api.themoviedb.org/3/movie/{movie_id}?api_key={auth_key}"
)
if movie_obj is None:
tmdb_not_found.add(show.title)
return None
tmdb_details_movie_cache[show.title] = movie_obj
return movie_obj
LANGUAGES: Dict[str, List[str]] = {
# iso639 language codes, set 1, 2/t, 2/b, 3
"abkhazian": ["ab", "abk", "abk", "abk"],
"afar": ["aa", "aar", "aar", "aar"],
"afrikaans": ["af", "afr", "afr", "afr"],
"akan": ["ak", "aka", "aka", "aka"],
"albanian": ["sq", "sqi", "alb", "sqi"],
"amharic": ["am", "amh", "amh", "amh"],
"arabic": ["ar", "ara", "ara", "ara"],
"aragonese": ["an", "arg", "arg", "arg"],
"armenian": ["hy", "hye", "arm", "hye"],
"assamese": ["as", "asm", "asm", "asm"],
"avaric": ["av", "ava", "ava", "ava"],
"avestan": ["ae", "ave", "ave", "ave"],
"aymara": ["ay", "aym", "aym", "aym"],
"azerbaijani": ["az", "aze", "aze", "aze"],
"bambara": ["bm", "bam", "bam", "bam"],
"bashkir": ["ba", "bak", "bak", "bak"],
"basque": ["eu", "eus", "baq", "eus"],
"belarusian": ["be", "bel", "bel", "bel"],
"bengali": ["bn", "ben", "ben", "ben"],
"bislama": ["bi", "bis", "bis", "bis"],
"bosnian": ["bs", "bos", "bos", "bos"],
"breton": ["br", "bre", "bre", "bre"],
"bulgarian": ["bg", "bul", "bul", "bul"],
"burmese": ["my", "mya", "bur", "mya"],
"cambodian": ["K", "kuyu", "ki", "kik"],
"catalan": ["ca", "cat", "cat", "cat"],
"centralKhmer": ["km", "khm", "khm", "khm"],
"chamorro": ["ch", "cha", "cha", "cha"],
"chechen": ["ce", "che", "che", "che"],
"chichewa": ["ny", "nya", "nya", "nya"],
"chinese": ["zh", "zho", "chi", "zho"],
"churchSlavonic": ["cu", "chu", "chu", "chu"],
"chuvash": ["cv", "chv", "chv", "chv"],
"cornish": ["kw", "cor", "cor", "cor"],
"corsican": ["co", "cos", "cos", "cos"],
"cree": ["cr", "cre", "cre", "cre"],
"croatian": ["hr", "hrv", "hrv", "hrv"],
"czech": ["cs", "ces", "cze", "ces"],
"danish": ["da", "dan", "dan", "dan"],
"divehi": ["dv", "div", "div", "div"],
"dutch": ["nl", "nld", "dut", "nld"],
"dzongkha": ["dz", "dzo", "dzo", "dzo"],
"english": ["en", "eng", "eng", "eng"],
"esperanto": ["eo", "epo", "epo", "epo"],
"estonian": ["et", "est", "est", "est"],
"ewe": ["ee", "ewe", "ewe", "ewe"],
"faroese": ["fo", "fao", "fao", "fao"],
"fijian": ["fj", "fij", "fij", "fij"],
"finnish": ["fi", "fin", "fin", "fin"],
"french": ["fr", "fra", "fre", "fra"],
"fulah": ["ff", "ful", "ful", "ful"],
"gaelic": ["gd", "gla", "gla", "gla"],
"galician": ["gl", "glg", "glg", "glg"],
"ganda": ["lg", "lug", "lug", "lug"],
"georgian": ["ka", "kat", "geo", "kat"],
"german": ["de", "deu", "ger", "deu"],
"greek": ["el", "ell", "gre", "ell"],
"guarani": ["gn", "grn", "grn", "grn"],
"gujarati": ["gu", "guj", "guj", "guj"],
"haitian": ["ht", "hat", "hat", "hat"],
"hausa": ["ha", "hau", "hau", "hau"],
"hebrew": ["he", "heb", "heb", "heb"],
"herero": ["hz", "her", "her", "her"],
"hindi": ["hi", "hin", "hin", "hin"],
"hiriMotu": ["ho", "hmo", "hmo", "hmo"],
"hungarian": ["hu", "hun", "hun", "hun"],
"icelandic": ["is", "isl", "ice", "isl"],
"ido": ["io", "ido", "ido", "ido"],
"igbo": ["ig", "ibo", "ibo", "ibo"],
"indonesian": ["id", "ind", "ind", "ind"],
"interlingua": ["ia", "ina", "ina", "ina"],
"interlingue": ["ie", "ile", "ile", "ile"],
"inuktitut": ["iu", "iku", "iku", "iku"],
"inupiaq": ["ik", "ipk", "ipk", "ipk"],
"irish": ["ga", "gle", "gle", "gle"],
"italian": ["it", "ita", "ita", "ita"],
"japanese": ["ja", "jpn", "jpn", "jpn"],
"javanese": ["jv", "jav", "jav", "jav"],
"kalaallisut": ["kl", "kal", "kal", "kal"],
"kannada": ["kn", "kan", "kan", "kan"],
"kanuri": ["kr", "kau", "kau", "kau"],
"kashmiri": ["ks", "kas", "kas", "kas"],
"kazakh": ["kk", "kaz", "kaz", "kaz"],
"kikuyu": ["rw", "kin", "kin", "kin"],
"kirghiz": ["ky", "kir", "kir", "kir"],
"komi": ["kv", "kom", "kom", "kom"],
"kongo": ["kg", "kon", "kon", "kon"],
"korean": ["ko", "kor", "kor", "kor"],
"kuanyama": ["kj", "kua", "kua"],
"kurdish": ["ku", "kur", "kur", "kur"],
"lao": ["lo", "lao", "lao", "lao"],
"latin": ["la", "lat", "lat", "lat"],
"latvian": ["lv", "lav", "lav", "lav"],
"limburgan": ["li", "lim", "lim", "lim"],
"lingala": ["ln", "lin", "lin", "lin"],
"lithuanian": ["lt", "lit", "lit", "lit"],
"lubaKatanga": ["lu", "lub", "lub", "lub"],
"luxembourgish": ["lb", "ltz", "ltz", "ltz"],
"macedonian": ["mk", "mkd", "mac", "mkd"],
"malagasy": ["mg", "mlg", "mlg", "mlg"],
"malay": ["ms", "msa", "may", "msa"],
"malayalam": ["ml", "mal", "mal", "mal"],
"maltese": ["mt", "mlt", "mlt", "mlt"],
"manx": ["gv", "glv", "glv", "glv"],
"maori": ["mi", "mri", "mao", "mri"],
"marathi": ["mr", "mar", "mar", "mar"],
"marshallese": ["mh", "mah", "mah", "mah"],
"mongolian": ["mn", "mon", "mon", "mon"],
"nauru": ["na", "nau", "nau", "nau"],
"navajo": ["nv", "nav", "nav", "nav"],
"ndonga": ["ng", "ndo", "ndo", "ndo"],
"nepali": ["ne", "nep", "nep", "nep"],
"northernSami": ["se", "sme", "sme", "sme"],
"northNdebele": ["nd", "nde", "nde", "nde"],
"norwegian": ["no", "nor", "nor", "nor"],
"occitan": ["oc", "oci", "oci", "oci"],
"ojibwa": ["oj", "oji", "oji", "oji"],
"oriya": ["or", "ori", "ori", "ori"],
"oromo": ["om", "orm", "orm", "orm"],
"ossetian": ["os", "oss", "oss", "oss"],
"pali": ["pi", "pli", "pli", "pli"],
"pashto": ["ps", "pus", "pus", "pus"],
"persian": ["fa", "fas", "per", "fas"],
"polish": ["pl", "pol", "pol", "pol"],
"portuguese": ["pt", "por", "por", "por"],
"punjabi": ["pa", "pan", "pan", "pan"],
"quechua": ["qu", "que", "que", "que"],
"romanian": ["ro", "ron", "rum", "ron"],
"romansh": ["rm", "roh", "roh", "roh"],
"rundi": ["rn", "run", "run", "run"],
"russian": ["ru", "rus", "rus", "rus"],
"samoan": ["sm", "smo", "smo", "smo"],
"sango": ["sg", "sag", "sag", "sag"],
"sanskrit": ["sa", "san", "san", "san"],
"sardinian": ["sc", "srd", "srd", "srd"],
"serbian": ["sr", "srp", "srp", "srp"],
"shona": ["sn", "sna", "sna", "sna"],
"sichuanYi": ["ii", "iii", "iii", "iii"],
"sindhi": ["sd", "snd", "snd", "snd"],
"sinhala": ["si", "sin", "sin", "sin"],
"slovak": ["sk", "slk", "slo", "slk"],
"slovenian": ["sl", "slv", "slv", "slv"],
"somali": ["so", "som", "som", "som"],
"southernSotho": ["st", "sot", "sot", "sot"],
"southNdebele": ["nr", "nbl", "nbl", "nbl"],
"spanish": ["es", "spa", "spa", "spa"],
"sundanese": ["su", "sun", "sun", "sun"],
"swahili": ["sw", "swa", "swa", "swa"],
"swati": ["ss", "ssw", "ssw", "ssw"],
"swedish": ["sv", "swe", "swe", "swe"],
"tagalog": ["tl", "tgl", "tgl", "tgl"],
"tahitian": ["ty", "tah", "tah", "tah"],
"tajik": ["tg", "tgk", "tgk", "tgk"],
"tamil": ["ta", "tam", "tam", "tam"],
"tatar": ["tt", "tat", "tat", "tat"],
"telugu": ["te", "tel", "tel", "tel"],
"thai": ["th", "tha", "tha", "tha"],
"tibetan": ["bo", "bod", "tib", "bod"],
"tigrinya": ["ti", "tir", "tir", "tir"],
"tonga": ["to", "ton", "ton", "ton"],
"tsonga": ["ts", "tso", "tso", "tso"],
"tswana": ["tn", "tsn", "tsn", "tsn"],
"turkish": ["tr", "tur", "tur", "tur"],
"turkmen": ["tk", "tuk", "tuk", "tuk"],
"twi": ["tw", "twi", "twi", "twi"],
"uighur": ["ug", "uig", "uig", "uig"],
"ukrainian": ["uk", "ukr", "ukr", "ukr"],
"urdu": ["ur", "urd", "urd", "urd"],
"uzbek": ["uz", "uzb", "uzb", "uzb"],
"venda": ["ve", "ven", "ven", "ven"],
"vietnamese": ["vi", "vie", "vie", "vie"],
"volapuk": ["vo", "vol", "vol", "vol"],
"walloon": ["wa", "wln", "wln", "wln"],
"welsh": ["cy", "cym", "wel", "cym"],
"westernfrisian": ["fy", "fry", "fry", "fry"],
"wolof": ["wo", "wol", "wol", "wol"],
"xhosa": ["xh", "xho", "xho", "xho"],
"yiddish": ["yi", "yid", "yid", "yid"],
"yoruba": ["yo", "yor", "yor", "yor"],
"zhuang": ["za", "zha", "zha", "zha"],
"zulu": ["zu", "zul", "zul", "zul"],
}