-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmain.py
6415 lines (5208 loc) · 248 KB
/
main.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 sys
import random
import os
import contextlib
import re
import sqlite3
import ssl
import torch
import requests
import json
import logging
import numpy as np
import threading
import asyncio
import aiohttp
import time
import tempfile
import traceback
from datetime import datetime
from typing import Optional, Dict, Any, Tuple, List, Union, Set
from collections import defaultdict, deque
from logging.handlers import RotatingFileHandler
from plexapi.server import PlexServer
from aiohttp import ClientTimeout, ClientSession, TCPConnector, ClientError
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GCNConv, GATConv, GraphSAGE
import nltk
from sentence_transformers import SentenceTransformer
import shiboken6
from PySide6.QtWidgets import (
QApplication, QMainWindow, QTabWidget, QWidget, QVBoxLayout, QHBoxLayout, QLabel,
QTextEdit, QPushButton, QGroupBox, QFormLayout, QLineEdit, QListWidget,
QListWidgetItem, QMessageBox, QAbstractItemView, QDialog, QRadioButton,
QDialogButtonBox, QButtonGroup, QToolButton, QCheckBox
)
from PySide6.QtCore import (
Qt, QTimer, QThread, Signal, QUrl, QObject, QEventLoop, QSize, QMutex, QRegularExpression
)
from PySide6.QtGui import (
QPalette, QColor, QPixmap, QPainter, QFont, QIcon, QCloseEvent, QRegularExpressionValidator
)
from PySide6.QtNetwork import (
QNetworkAccessManager, QNetworkRequest, QNetworkReply
)
class Database:
_instance = None
@staticmethod
def get_instance():
if Database._instance is None:
Database._instance = Database()
return Database._instance
def __init__(self):
self.conn = None
self.write_lock = threading.Lock()
self._connect()
self._optimize_connection()
self._create_tables()
self._create_indices()
self.logger = logging.getLogger(__name__)
def _connect(self):
try:
self.conn = sqlite3.connect('recommender.db', check_same_thread=False)
except sqlite3.Error as e:
self.logger.error(f"Database connection error: {e}")
raise
def _optimize_connection(self):
cursor = None
try:
cursor = self.conn.cursor()
pragmas = [
'PRAGMA journal_mode = WAL',
'PRAGMA synchronous = NORMAL',
'PRAGMA cache_size = -4000000',
'PRAGMA mmap_size = 60000000000',
'PRAGMA temp_store = MEMORY',
'PRAGMA page_size = 4096',
'PRAGMA foreign_keys = ON',
'PRAGMA read_uncommitted = 1'
]
for pragma in pragmas:
cursor.execute(pragma)
self.conn.commit()
except sqlite3.Error as e:
if self.conn:
self.conn.rollback()
raise
finally:
if cursor:
cursor.close()
def _create_tables(self):
with self.write_lock:
cursor = self.conn.cursor()
try:
cursor.execute('''
CREATE TABLE IF NOT EXISTS media_items (
id INTEGER PRIMARY KEY,
title TEXT,
type TEXT,
year INTEGER,
runtime TEXT,
summary TEXT,
genres TEXT,
poster_url TEXT,
tvdb_id TEXT,
tmdb_id TEXT,
original_title TEXT,
overview TEXT,
popularity REAL,
vote_average REAL,
vote_count INTEGER,
status TEXT,
tagline TEXT,
backdrop_path TEXT,
release_date TEXT,
content_rating TEXT,
network TEXT,
credits TEXT,
keywords TEXT,
videos TEXT,
language TEXT,
production_companies TEXT,
reviews TEXT,
episodes TEXT,
season_count INTEGER,
episode_count INTEGER,
first_air_date TEXT,
last_air_date TEXT,
is_blocked INTEGER DEFAULT 0,
last_recommended TIMESTAMP
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS genre_preferences (
genre TEXT PRIMARY KEY,
rating_sum REAL,
rating_count INTEGER
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS user_feedback (
id INTEGER PRIMARY KEY,
media_id INTEGER,
rating INTEGER,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (media_id) REFERENCES media_items (id)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS embedding_cache (
media_id INTEGER PRIMARY KEY,
embedding BLOB,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (media_id) REFERENCES media_items (id)
)
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS similarity_matrix (
item1_id INTEGER,
item2_id INTEGER,
similarity REAL,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (item1_id, item2_id),
FOREIGN KEY (item1_id) REFERENCES media_items (id),
FOREIGN KEY (item2_id) REFERENCES media_items (id)
)
''')
cursor.execute('''
SELECT COUNT(*) FROM pragma_table_info('media_items')
WHERE name='last_recommended'
''')
if cursor.fetchone()[0] == 0:
cursor.execute('''
ALTER TABLE media_items
ADD COLUMN last_recommended TIMESTAMP
''')
cursor.execute('''
CREATE TABLE IF NOT EXISTS plex_metadata (
media_id INTEGER PRIMARY KEY,
plex_rating INTEGER,
watch_progress REAL,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (media_id) REFERENCES media_items (id)
)
''')
cursor.execute('''
SELECT COUNT(*) FROM pragma_table_info('media_items')
WHERE name='is_blocked'
''')
if cursor.fetchone()[0] == 0:
cursor.execute('''
ALTER TABLE media_items
ADD COLUMN is_blocked INTEGER DEFAULT 0
''')
self.conn.commit()
finally:
cursor.close()
def _create_indices(self):
cursor = self.conn.cursor()
try:
indices = [
'CREATE INDEX IF NOT EXISTS idx_media_type_year ON media_items (type, year)',
'CREATE INDEX IF NOT EXISTS idx_media_vote_popularity ON media_items (vote_average, vote_count, popularity)',
'CREATE INDEX IF NOT EXISTS idx_feedback_timestamp ON user_feedback (timestamp)',
'CREATE INDEX IF NOT EXISTS idx_embedding_last_updated ON embedding_cache (last_updated)',
'CREATE INDEX IF NOT EXISTS idx_similarity_last_updated ON similarity_matrix (last_updated)',
'CREATE INDEX IF NOT EXISTS idx_media_recommendations ON media_items (type, vote_average, vote_count, popularity, id, title, genres)',
'CREATE INDEX IF NOT EXISTS idx_feedback_analysis ON user_feedback (media_id, rating, timestamp)',
'CREATE INDEX IF NOT EXISTS idx_media_title_search ON media_items(title COLLATE NOCASE)',
'CREATE INDEX IF NOT EXISTS idx_genre_preferences_rating ON genre_preferences(rating_sum, rating_count)',
'CREATE INDEX IF NOT EXISTS idx_active_media ON media_items(id, type) WHERE status != "Ended" AND status != "Cancelled"',
'CREATE INDEX IF NOT EXISTS idx_embedding_cleanup ON embedding_cache(last_updated)',
'CREATE INDEX IF NOT EXISTS idx_media_items_title_year ON media_items (title, year)',
'CREATE INDEX IF NOT EXISTS idx_user_feedback_media_id ON user_feedback (media_id)',
'CREATE INDEX IF NOT EXISTS idx_feedback_media_rating ON user_feedback (media_id, rating)',
'CREATE INDEX IF NOT EXISTS idx_items_type ON media_items (type)',
'CREATE INDEX IF NOT EXISTS idx_media_genres ON media_items (genres)',
'CREATE INDEX IF NOT EXISTS idx_media_embedding_join ON media_items (id)',
'CREATE INDEX IF NOT EXISTS idx_feedback_media_join ON user_feedback (media_id)',
'CREATE INDEX IF NOT EXISTS idx_sim_item1 ON similarity_matrix (item1_id)',
'CREATE INDEX IF NOT EXISTS idx_sim_item2 ON similarity_matrix (item2_id)',
'CREATE INDEX IF NOT EXISTS idx_feedback_quick ON user_feedback (media_id, rating)',
'CREATE INDEX IF NOT EXISTS idx_media_quick ON media_items (type, year, popularity, vote_average)',
'CREATE INDEX IF NOT EXISTS idx_genres_quick ON media_items (genres)',
'CREATE INDEX IF NOT EXISTS idx_recommendations_combined ON media_items (type, is_blocked, last_recommended)',
'CREATE INDEX IF NOT EXISTS idx_embedding_lookup ON embedding_cache (media_id, last_updated)'
]
for index in indices:
cursor.execute(index)
cursor.execute('ANALYZE media_items')
cursor.execute('ANALYZE user_feedback')
cursor.execute('ANALYZE embedding_cache')
cursor.execute('ANALYZE similarity_matrix')
cursor.execute('ANALYZE genre_preferences')
self.conn.commit()
except sqlite3.Error as e:
self.conn.rollback()
raise
finally:
cursor.close()
@contextlib.contextmanager
def get_cursor(self):
cursor = None
try:
cursor = self.conn.cursor()
yield cursor
finally:
if cursor:
cursor.close()
def execute_write(self, query, params=None):
if not self.write_lock.acquire(timeout=10):
raise TimeoutError("Could not acquire database write lock")
try:
with self.get_cursor() as cursor:
cursor.execute(query, params or ())
self.conn.commit()
except sqlite3.Error as e:
if self.conn:
self.conn.rollback()
raise
finally:
self.write_lock.release()
def execute_read(self, query, params=None):
with self.get_cursor() as cursor:
cursor.execute(query, params or ())
return cursor.fetchall()
def save_embedding(self, media_id, embedding):
with self.write_lock:
cursor = self.conn.cursor()
try:
cursor.execute('''
INSERT OR REPLACE INTO embedding_cache (media_id, embedding, last_updated)
VALUES (?, ?, CURRENT_TIMESTAMP)
''', (media_id, embedding))
self.conn.commit()
except sqlite3.Error as e:
self.conn.rollback()
raise
finally:
cursor.close()
def load_embedding(self, media_id):
try:
with self.get_cursor() as cursor:
cursor.execute('SELECT embedding FROM embedding_cache WHERE media_id = ?', (media_id,))
result = cursor.fetchone()
return result[0] if result and result[0] else None
except sqlite3.Error as e:
self.logger.error(f"Error loading embedding for media_id {media_id}: {e}")
return None
def save_feedback(self, media_id, rating):
with self.write_lock:
cursor = self.conn.cursor()
try:
cursor.execute('''
INSERT INTO user_feedback (media_id, rating)
VALUES (?, ?)
''', (media_id, rating))
self.conn.commit()
except sqlite3.Error as e:
self.conn.rollback()
raise
finally:
cursor.close()
def get_feedback(self):
with self.get_cursor() as cursor:
cursor.execute('SELECT media_id, AVG(rating) as avg_rating FROM user_feedback GROUP BY media_id')
return cursor.fetchall()
def get_media_items(self, filters=None):
filters = filters or {}
query = "SELECT id, title, genres FROM media_items"
conditions = []
params = []
if 'type' in filters:
conditions.append("type = ?")
params.append(filters['type'])
if conditions:
query += " WHERE " + " AND ".join(conditions)
try:
with self.get_cursor() as cursor:
cursor.execute(query, params)
rows = cursor.fetchall()
return [{'id': row[0], 'title': row[1], 'genres': row[2]} for row in rows]
except sqlite3.Error as e:
self.logger.error(f"Error retrieving media items: {e}")
return []
def cleanup_old_cache(self):
try:
self.execute_write('DELETE FROM embedding_cache WHERE last_updated < datetime("now", "-30 days")')
except sqlite3.Error as e:
self.logger.error(f"Error cleaning up cache: {e}")
def optimize_database(self):
cursor = self.conn.cursor()
try:
cursor.execute('VACUUM')
cursor.execute('ANALYZE')
cursor.execute('ANALYZE media_items')
cursor.execute('ANALYZE user_feedback')
cursor.execute('ANALYZE embedding_cache')
cursor.execute('ANALYZE similarity_matrix')
cursor.execute('ANALYZE genre_preferences')
self.conn.commit()
except sqlite3.Error as e:
self.logger.error(f"Error optimizing database: {e}")
raise
finally:
cursor.close()
def close(self):
if not self.write_lock.acquire(timeout=5):
self.logger.warning("Could not acquire lock for database closing")
return False
success = False
try:
if self.conn:
try:
if self.conn:
self.conn.commit()
self.conn.close()
success = True
except sqlite3.Error as e:
self.logger.error(f"Error closing database: {e}")
try:
self.conn.rollback()
except Exception:
pass
finally:
self.conn = None
finally:
self.write_lock.release()
return success
def __del__(self):
if hasattr(self, 'conn') and self.conn is not None:
self.close()
class APIClient:
def __init__(self):
self.session = requests.Session()
self.session.mount('https://', requests.adapters.HTTPAdapter(
max_retries=3,
pool_connections=10,
pool_maxsize=10
))
self._lock = threading.Lock()
self.logger = logging.getLogger(__name__)
def close(self):
with self._lock:
if self.session:
self.session.close()
class TVDBClient(APIClient):
def __init__(self, api_key: str):
super().__init__()
self.api_key = api_key
self.base_url = "https://api4.thetvdb.com/v4"
self.token = None
self.token_lock = threading.Lock()
self.logger = logging.getLogger(__name__)
async def ensure_token(self):
with self.token_lock:
try:
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
async with aiohttp.ClientSession() as session:
async with session.post(
f"{self.base_url}/login",
json={"apikey": self.api_key},
timeout=10,
ssl=ssl_context
) as response:
if response.status != 200:
raise ValueError(f"TVDB authentication failed: {await response.text()}")
data = await response.json()
self.token = data.get('data', {}).get('token')
if not self.token:
raise ValueError("No authentication token received")
self.session.headers.update({
"Authorization": f"Bearer {self.token}"
})
except Exception as e:
self.logger.error(f"Token refresh failed: {str(e)}")
raise
async def search(self, title: str) -> Optional[List[Dict[str, Any]]]:
await self.ensure_token()
try:
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
async with aiohttp.ClientSession() as session:
url = f"{self.base_url}/search"
params = {"query": title, "type": "series"}
headers = {"Authorization": f"Bearer {self.token}"}
async with session.get(url, params=params, headers=headers, ssl=ssl_context) as response:
if response.status == 200:
data = await response.json()
return data.get("data", [])
return None
except Exception as e:
self.logger.error(f"TVDB search error: {str(e)}")
return None
async def fetch_series_data(self, tvdb_id: str) -> Dict:
tvdb_id = tvdb_id.replace('series-', '')
await self.ensure_token()
try:
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
async with aiohttp.ClientSession() as session:
headers = {"Authorization": f"Bearer {self.token}"}
if not tvdb_id.isdigit():
raise ValueError(f"Invalid TVDB ID format: {tvdb_id}")
series_url = f"{self.base_url}/series/{tvdb_id}/extended"
async with session.get(series_url, headers=headers, ssl=ssl_context) as response:
if response.status != 200:
raise ValueError(f"Failed to fetch series data: {response.status}")
series_data = await response.json()
episodes_url = f"{self.base_url}/series/{tvdb_id}/episodes/default"
async with session.get(episodes_url, headers=headers, ssl=ssl_context) as response:
if response.status == 200:
episodes_data = await response.json()
else:
episodes_data = {"data": []}
artwork_url = f"{self.base_url}/series/{tvdb_id}/artworks"
async with session.get(artwork_url, headers=headers, ssl=ssl_context) as response:
if response.status == 200:
artwork_data = await response.json()
else:
artwork_data = {"data": []}
return {
"id": tvdb_id,
"name": series_data.get("data", {}).get("name"),
"overview": series_data.get("data", {}).get("overview"),
"first_aired": series_data.get("data", {}).get("firstAired"),
"network": series_data.get("data", {}).get("network"),
"status": series_data.get("data", {}).get("status"),
"genres": series_data.get("data", {}).get("genres", []),
"episodes": episodes_data.get("data", []),
"artworks": artwork_data.get("data", []),
"image_url": series_data.get("data", {}).get("image"),
"rating": series_data.get("data", {}).get("rating"),
"runtime": series_data.get("data", {}).get("runtime"),
"language": series_data.get("data", {}).get("originalLanguage"),
"aliases": series_data.get("data", {}).get("aliases", []),
}
except Exception as e:
self.logger.error(f"Error fetching TVDB data: {str(e)}")
raise
async def fetch_episode_data(self, episode_id: str) -> Optional[Dict]:
await self.ensure_token()
try:
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
async with aiohttp.ClientSession() as session:
url = f"{self.base_url}/episodes/{episode_id}/extended"
headers = {"Authorization": f"Bearer {self.token}"}
async with session.get(url, headers=headers, ssl=ssl_context) as response:
if response.status == 200:
data = await response.json()
return data.get("data")
return None
except Exception as e:
self.logger.error(f"Error fetching episode data: {str(e)}")
return None
async def fetch_artwork(self, series_id: str) -> Optional[List[Dict]]:
await self.ensure_token()
try:
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
async with aiohttp.ClientSession() as session:
url = f"{self.base_url}/series/{series_id}/artworks"
headers = {"Authorization": f"Bearer {self.token}"}
async with session.get(url, headers=headers, ssl=ssl_context) as response:
if response.status == 200:
data = await response.json()
return data.get("data", [])
return None
except Exception as e:
self.logger.error(f"Error fetching artwork: {str(e)}")
return None
async def fetch_translations(self, series_id: str, language: str) -> Optional[Dict]:
await self.ensure_token()
try:
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
async with aiohttp.ClientSession() as session:
url = f"{self.base_url}/series/{series_id}/translations/{language}"
headers = {"Authorization": f"Bearer {self.token}"}
async with session.get(url, headers=headers, ssl=ssl_context) as response:
if response.status == 200:
data = await response.json()
return data.get("data")
return None
except Exception as e:
self.logger.error(f"Error fetching translations: {str(e)}")
return None
async def close(self):
try:
if isinstance(self.session, aiohttp.ClientSession) and not self.session.closed:
await self.session.close()
except Exception as e:
self.logger.error(f"Error closing session: {str(e)}")
finally:
self.session = None
class TMDBClient:
def __init__(self, access_token: str):
self.access_token = access_token
self.base_url = "https://api.themoviedb.org/3"
self.session = None
self.logger = logging.getLogger(__name__)
self.configuration = None
self.image_base_url = None
async def __aenter__(self):
await self._initialize_session()
return self
async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.close()
async def fetch_configuration(self) -> bool:
try:
if not self.session:
await self._initialize_session()
data = await self._make_request('GET', '/configuration')
if not data:
raise ValueError("Failed to fetch configuration")
self.configuration = data
if "images" in self.configuration:
self.image_base_url = self.configuration["images"].get("secure_base_url")
return True
except Exception as e:
self.logger.error(f"Failed to fetch TMDB configuration: {str(e)}")
raise
async def _initialize_session(self) -> None:
if self.session is None or self.session.closed:
timeout = ClientTimeout(total=30, connect=10, sock_read=10)
ssl_context = ssl.create_default_context()
ssl_context.check_hostname = False
ssl_context.verify_mode = ssl.CERT_NONE
self.session = aiohttp.ClientSession(
timeout=timeout,
connector=aiohttp.TCPConnector(
limit=10,
force_close=True,
enable_cleanup_closed=True,
ssl=ssl_context
)
)
async def close(self) -> None:
try:
if isinstance(self.session, aiohttp.ClientSession) and not self.session.closed:
await self.session.close()
await asyncio.sleep(0.25)
except Exception as e:
self.logger.error(f"Error closing session: {str(e)}")
finally:
self.session = None
async def _make_request(self, method: str, endpoint: str, **kwargs) -> Dict:
if not self.session:
await self._initialize_session()
headers = {
"Authorization": f"Bearer {self.access_token}",
"accept": "application/json"
}
if 'headers' in kwargs:
kwargs['headers'].update(headers)
else:
kwargs['headers'] = headers
url = f"{self.base_url}{endpoint}"
self.logger.debug(f"Making request to {url}")
retries = 3
for attempt in range(retries):
try:
async with self.session.request(method, url, **kwargs) as response:
if response.status == 401:
error_text = await response.text()
self.logger.error(f"Authentication error. URL: {url}, Response: {error_text}")
raise ValueError(f"Invalid TMDB access token. Error: {error_text}")
if response.status == 404:
return {}
if response.status == 429:
retry_after = int(response.headers.get('Retry-After', 1))
await asyncio.sleep(retry_after)
continue
response.raise_for_status()
return await response.json()
except aiohttp.ClientError as e:
if attempt == retries - 1:
raise
await asyncio.sleep(2 ** attempt)
raise RuntimeError("Max retries exceeded")
async def get_list(self, list_id: int, language: str = "en-US", page: int = 1) -> Dict:
params = {
"language": language,
"page": page
}
return await self._make_request('GET', f'/list/{list_id}', params=params)
async def update_list(self, list_id: int, updates: Dict) -> Dict:
return await self._make_request('PUT', f'/list/{list_id}', json=updates)
async def create_list(self, name: str, description: str = "",
iso_639_1: str = "en", iso_3166_1: str = "US",
public: bool = True) -> Dict:
data = {
"name": name,
"description": description,
"iso_639_1": iso_639_1,
"iso_3166_1": iso_3166_1,
"public": public
}
return await self._make_request('POST', '/list', json=data)
async def clear_list(self, list_id: int) -> Dict:
return await self._make_request('GET', f'/list/{list_id}/clear')
async def delete_list(self, list_id: int) -> Dict:
return await self._make_request('DELETE', f'/list/{list_id}')
async def add_items(self, list_id: int, items: List[Dict]) -> Dict:
return await self._make_request('POST', f'/list/{list_id}/items', json={"items": items})
async def update_items(self, list_id: int, items: List[Dict]) -> Dict:
return await self._make_request('PUT', f'/list/{list_id}/items', json={"items": items})
async def remove_items(self, list_id: int, items: List[Dict]) -> Dict:
return await self._make_request('DELETE', f'/list/{list_id}/items', json={"items": items})
async def check_item_status(self, list_id: int, media_id: int, media_type: str) -> Dict:
params = {
"media_id": media_id,
"media_type": media_type
}
return await self._make_request('GET', f'/list/{list_id}/item_status', params=params)
async def get_account_lists(self, account_id: str, page: int = 1) -> Dict:
params = {"page": page}
return await self._make_request('GET', f'/account/{account_id}/lists', params=params)
async def get_account_favorite_movies(self, account_id: str, page: int = 1,
language: str = "en-US",
sort_by: str = "created_at.asc") -> Dict:
params = {
"page": page,
"language": language,
"sort_by": sort_by
}
return await self._make_request('GET', f'/account/{account_id}/movie/favorites', params=params)
async def get_account_favorite_tv(self, account_id: str, page: int = 1,
language: str = "en-US",
sort_by: str = "created_at.asc") -> Dict:
params = {
"page": page,
"language": language,
"sort_by": sort_by
}
return await self._make_request('GET', f'/account/{account_id}/tv/favorites', params=params)
async def get_account_movie_recommendations(self, account_id: str, page: int = 1,
language: str = "en-US") -> Dict:
params = {
"page": page,
"language": language
}
return await self._make_request(
'GET',
f'/account/{account_id}/movie/recommendations',
params=params
)
async def get_account_tv_recommendations(self, account_id: str, page: int = 1,
language: str = "en-US") -> Dict:
params = {
"page": page,
"language": language
}
return await self._make_request(
'GET',
f'/account/{account_id}/tv/recommendations',
params=params
)
async def get_movie_watchlist(self, account_id: str, page: int = 1,
language: str = "en-US",
sort_by: str = "created_at.asc") -> Dict:
params = {
"page": page,
"language": language,
"sort_by": sort_by
}
return await self._make_request(
'GET',
f'/account/{account_id}/movie/watchlist',
params=params
)
async def get_tv_watchlist(self, account_id: str, page: int = 1,
language: str = "en-US",
sort_by: str = "created_at.asc") -> Dict:
params = {
"page": page,
"language": language,
"sort_by": sort_by
}
return await self._make_request(
'GET',
f'/account/{account_id}/tv/watchlist',
params=params
)
async def get_rated_movies(self, account_id: str, page: int = 1,
language: str = "en-US",
sort_by: str = "created_at.asc") -> Dict:
params = {
"page": page,
"language": language,
"sort_by": sort_by
}
return await self._make_request(
'GET',
f'/account/{account_id}/movie/rated',
params=params
)
async def get_rated_tv(self, account_id: str, page: int = 1,
language: str = "en-US",
sort_by: str = "created_at.asc") -> Dict:
params = {
"page": page,
"language": language,
"sort_by": sort_by
}
return await self._make_request(
'GET',
f'/account/{account_id}/tv/rated',
params=params
)
async def fetch_media_data(self, title: str, year: Optional[int], media_type: str) -> Dict:
try:
search_results = await self._search_media(title, year, media_type)
if not search_results:
self.logger.warning(f"No results found for {title} ({year})")
return {}
media_id = search_results[0]['id']
details = await self._fetch_details(media_id, media_type)
if not details:
return {}
return self._process_media_data(details, media_type)
except Exception as e:
self.logger.error(f"Error fetching media data for {title}: {str(e)}")
raise
async def _search_media(self, title: str, year: Optional[int], media_type: str) -> List[Dict]:
search_type = 'tv' if media_type.lower() in ['show', 'tv'] else media_type
params = {
"query": title,
"language": "en-US",
"include_adult": "false"
}
if year:
params["year" if search_type == "movie" else "first_air_date_year"] = str(year)
try:
self.logger.debug(f"TMDB search params: {params}")
results = await self._make_request('GET', f'/search/{search_type}', params=params)
return results.get('results', [])
except Exception as e:
self.logger.error(f"TMDB fetch failed for {title}: {str(e)}")
raise
async def _fetch_details(self, media_id: int, media_type: str) -> Dict:
params = {
"append_to_response": (
"credits,keywords,videos,reviews,similar,recommendations,"
"watch/providers,external_ids,content_ratings,images,"
"aggregate_credits"
),
"language": "en-US"
}
try:
data = await self._make_request('GET', f'/{media_type}/{media_id}', params=params)
if media_type == "tv" and data.get("number_of_seasons", 0) > 0:
seasons_data = await self._fetch_all_seasons(media_id, data["number_of_seasons"])
data["seasons_data"] = seasons_data
return data
except Exception as e:
self.logger.error(f"Error fetching details for {media_id}: {str(e)}")
raise
async def _fetch_all_seasons(self, series_id: int, num_seasons: int) -> List[Dict]:
seasons = []
for season_num in range(1, num_seasons + 1):
try:
params = {
"append_to_response": "credits,videos,images",
"language": "en-US"
}
season_data = await self._make_request(
'GET',
f'/tv/{series_id}/season/{season_num}',
params=params
)
if season_data:
seasons.append(season_data)
except Exception as e:
self.logger.error(f"Error fetching season {season_num}: {str(e)}")
continue
return seasons
def _process_media_data(self, data: Dict, media_type: str) -> Dict:
processed = {
'tmdb_id': data.get('id'),
'title': data.get('title' if media_type == 'movie' else 'name'),
'original_title': data.get('original_title' if media_type == 'movie' else 'original_name'),
'overview': data.get('overview'),
'popularity': data.get('popularity'),
'vote_average': data.get('vote_average'),
'vote_count': data.get('vote_count'),
'release_date': data.get('release_date' if media_type == 'movie' else 'first_air_date'),
'genres': [genre['name'] for genre in data.get('genres', [])],
'runtime': data.get('runtime') if media_type == 'movie' else data.get('episode_run_time', [None])[0],
'status': data.get('status'),
'tagline': data.get('tagline'),
'poster_path': data.get('poster_path'),
'backdrop_path': data.get('backdrop_path'),
'budget': data.get('budget') if media_type == 'movie' else None,
'revenue': data.get('revenue') if media_type == 'movie' else None,
'keywords': [kw['name'] for kw in data.get('keywords', {}).get('keywords', [])],
'videos': self._process_videos(data.get('videos', {}).get('results', [])),
'credits': self._process_credits(data.get('credits', {})),
'reviews': self._process_reviews(data.get('reviews', {}).get('results', [])),
'similar': self._process_similar(data.get('similar', {}).get('results', [])),
'recommendations': self._process_recommendations(data.get('recommendations', {}).get('results', [])),
'watch_providers': data.get('watch/providers', {}).get('results', {}),
'images': self._process_images(data.get('images', {}))
}
if media_type == "tv":
processed.update({
'created_by': data.get('created_by', []),
'episode_run_time': data.get('episode_run_time', []),
'first_air_date': data.get('first_air_date'),
'last_air_date': data.get('last_air_date'),
'networks': data.get('networks', []),
'number_of_episodes': data.get('number_of_episodes'),
'number_of_seasons': data.get('number_of_seasons'),
'seasons': data.get('seasons_data', []),
'type': data.get('type'),
'origin_country': data.get('origin_country', [])
})
return processed
def _process_videos(self, videos: List[Dict]) -> List[Dict]:
return [{
'key': video['key'],
'name': video['name'],
'site': video['site'],
'type': video['type'],
'official': video.get('official', True)
} for video in videos if video.get('site') == 'YouTube']
def _process_credits(self, credits: Dict) -> Dict:
return {
'cast': [{
'id': person['id'],