-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimdb_browser.py
2460 lines (2002 loc) · 105 KB
/
imdb_browser.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 os
import sys
import sqlite3
import re
import json
import time
import traceback
import requests
from datetime import datetime
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QLabel, QLineEdit, QPushButton, QComboBox, QTableWidget, QTableWidgetItem, QHeaderView,
QTabWidget, QTextEdit, QMessageBox, QSplitter, QFileDialog,
QProgressBar, QGroupBox, QCheckBox, QProgressDialog)
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QSize, QTimer
from PyQt6.QtGui import QPixmap, QIcon, QFont
class ImageDownloader(QThread):
"""Thread for downloading images to avoid freezing the UI"""
progress_update = pyqtSignal(str)
download_complete = pyqtSignal(bool, str, str)
def __init__(self, tconst, save_path):
super().__init__()
self.tconst = tconst
self.save_path = save_path
self.is_cancelled = False
def run(self):
"""Run the download process"""
try:
# Create directory if it doesn't exist
os.makedirs(os.path.dirname(self.save_path), exist_ok=True)
# Check if file already exists
if os.path.exists(self.save_path):
self.download_complete.emit(True, self.tconst, self.save_path)
return
# Construct IMDB URL
imdb_url = f"https://www.imdb.com/title/{self.tconst}/"
# Download the image
self.progress_update.emit(f"Finding image for {self.tconst}...")
# First, get the IMDB page to find the image URL
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
response = requests.get(imdb_url, headers=headers)
if response.status_code != 200:
self.download_complete.emit(False, self.tconst, f"Failed to access IMDB page: HTTP {response.status_code}")
return
# Try to find the image URL in the page content
self.progress_update.emit(f"Extracting image URL for {self.tconst}...")
# Look for the poster image URL in the HTML
# This is a simplified approach and might need adjustments if IMDB changes their page structure
html_content = response.text
# Try different patterns to find the image URL
image_url = None
# Pattern 1: Look for poster image in JSON-LD data
json_ld_match = re.search(r'"image"\s*:\s*"(https://[^"]+\.jpg)"', html_content)
if json_ld_match:
image_url = json_ld_match.group(1)
# Pattern 2: Look for poster image in meta tags
if not image_url:
meta_match = re.search(r'<meta property="og:image" content="([^"]+)"', html_content)
if meta_match:
image_url = meta_match.group(1)
# Pattern 3: Look for poster image with ipc-lockup-overlay__screen class
if not image_url:
img_match = re.search(r'<div[^>]+class="[^"]*ipc-lockup-overlay__screen[^"]*"[^>]+style="[^"]*background-image:url\(([^)]+)\)', html_content)
if img_match:
image_url = img_match.group(1)
# Remove quotes if present
image_url = image_url.strip('"\'')
# Pattern 4: Look for poster image in the page content with ipc-image class
if not image_url:
img_match = re.search(r'<img[^>]+class="[^"]*ipc-image[^"]*"[^>]+src="([^"]+\.jpg)"', html_content)
if img_match:
image_url = img_match.group(1)
# If we still don't have an image URL, try the old direct URL pattern as a fallback
if not image_url:
image_url = f"https://m.media-amazon.com/images/M/{self.tconst}.jpg"
self.progress_update.emit(f"Using fallback image URL for {self.tconst}...")
# Download the image
self.progress_update.emit(f"Downloading image for {self.tconst}...")
img_response = requests.get(image_url, stream=True, headers=headers)
if img_response.status_code == 200:
with open(self.save_path, 'wb') as f:
for chunk in img_response.iter_content(1024):
if self.is_cancelled:
break
f.write(chunk)
if not self.is_cancelled:
self.download_complete.emit(True, self.tconst, self.save_path)
else:
# Clean up partial download
if os.path.exists(self.save_path):
os.remove(self.save_path)
self.download_complete.emit(False, self.tconst, "Download cancelled")
else:
self.download_complete.emit(False, self.tconst, f"Failed to download image: HTTP {img_response.status_code}")
except Exception as e:
self.download_complete.emit(False, self.tconst, f"Error downloading image: {str(e)}")
def cancel(self):
"""Cancel the download process"""
self.is_cancelled = True
class SearchThread(QThread):
"""Thread for performing searches in the background and updating results progressively"""
result_batch_ready = pyqtSignal(list, int)
search_complete = pyqtSignal(int)
def __init__(self, db_manager, search_params, page_size=20):
super().__init__()
self.db_manager = db_manager
self.search_params = search_params
self.page_size = page_size
self.is_cancelled = False
self.batch_size = 20 # Increased batch size for better performance
def run(self):
"""Run the search process"""
try:
conn = self.db_manager.connect()[0]
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
# Set a timeout for the query to prevent long-running queries
cursor.execute("PRAGMA timeout = 30000") # 30 seconds timeout
# Determine which search method to use based on search type
if self.search_params['search_type'] == "cast":
# Search by cast member name
query, params = self.build_cast_search_query()
elif self.search_params['search_type'] == "director":
# Search by director name
query, params = self.build_director_search_query()
else:
# Regular title search
query, params = self.build_title_search_query()
# Add a limit to the query to prevent excessive results
if "LIMIT" not in query:
query += " LIMIT 1000" # Limit to 1000 results maximum
# Execute the query without pagination to get all results
cursor.execute(query, params)
# Process results in batches
results = []
total_count = 0
while True:
if self.is_cancelled:
break
# Fetch a batch of rows
rows = cursor.fetchmany(self.batch_size)
if not rows:
break
# Convert rows to dictionaries
batch_results = [dict(row) for row in rows]
results.extend(batch_results)
total_count += len(batch_results)
# Emit signal with the current batch of results
self.result_batch_ready.emit(batch_results, total_count)
conn.close()
# Emit signal that search is complete
self.search_complete.emit(total_count)
except Exception as e:
print(f"Error in search thread: {str(e)}")
self.search_complete.emit(-1) # Negative value indicates error
def build_title_search_query(self):
"""Build the SQL query for title search"""
query = """
SELECT tb.tconst, tb.titleType, tb.primaryTitle, tb.originalTitle,
tb.startYear, tb.endYear, tb.runtimeMinutes, tb.genres,
tr.averageRating, tr.numVotes
FROM title_basics tb
LEFT JOIN title_ratings tr ON tb.tconst = tr.tconst
WHERE 1=1
"""
params = []
# Add search conditions
if self.search_params['search_term']:
query += " AND (tb.primaryTitle LIKE ? OR tb.originalTitle LIKE ?)"
params.extend([f"%{self.search_params['search_term']}%", f"%{self.search_params['search_term']}%"])
if self.search_params['title_type']:
query += " AND tb.titleType = ?"
params.append(self.search_params['title_type'])
if self.search_params['genre']:
query += " AND tb.genres LIKE ?"
params.append(f"%{self.search_params['genre']}%")
if self.search_params['year']:
query += " AND tb.startYear = ?"
params.append(self.search_params['year'])
if self.search_params['min_rating']:
query += " AND tr.averageRating >= ?"
params.append(self.search_params['min_rating'])
# Add order by - first by year (latest first), then by rating
query += " ORDER BY CASE WHEN tb.startYear IS NULL THEN 0 ELSE tb.startYear END DESC, CASE WHEN tr.averageRating IS NULL THEN 0 ELSE tr.averageRating END DESC, tb.primaryTitle"
return query, params
def build_cast_search_query(self):
"""Build the SQL query for cast member search"""
# Use a more efficient query with better join order and limiting
query = """
WITH matching_people AS (
SELECT nconst, primaryName
FROM name_basics
WHERE primaryName LIKE ?
LIMIT 100
)
SELECT DISTINCT tb.tconst, tb.titleType, tb.primaryTitle, tb.originalTitle,
tb.startYear, tb.endYear, tb.runtimeMinutes, tb.genres,
tr.averageRating, tr.numVotes
FROM matching_people mp
JOIN title_principals tp ON mp.nconst = tp.nconst
JOIN title_basics tb ON tp.tconst = tb.tconst
LEFT JOIN title_ratings tr ON tb.tconst = tr.tconst
WHERE 1=1
"""
params = [f"%{self.search_params['search_term']}%"]
# Add additional search conditions
if self.search_params['title_type']:
query += " AND tb.titleType = ?"
params.append(self.search_params['title_type'])
if self.search_params['genre']:
query += " AND tb.genres LIKE ?"
params.append(f"%{self.search_params['genre']}%")
if self.search_params['year']:
query += " AND tb.startYear = ?"
params.append(self.search_params['year'])
if self.search_params['min_rating']:
query += " AND tr.averageRating >= ?"
params.append(self.search_params['min_rating'])
# Add order by - first by year (latest first), then by rating
query += " ORDER BY CASE WHEN tb.startYear IS NULL THEN 0 ELSE tb.startYear END DESC, CASE WHEN tr.averageRating IS NULL THEN 0 ELSE tr.averageRating END DESC, tb.primaryTitle"
return query, params
def build_director_search_query(self):
"""Build the SQL query for director search"""
# Use a more efficient query with better join order and limiting
query = """
WITH matching_directors AS (
SELECT nconst, primaryName
FROM name_basics
WHERE primaryName LIKE ?
LIMIT 100
)
SELECT DISTINCT tb.tconst, tb.titleType, tb.primaryTitle, tb.originalTitle,
tb.startYear, tb.endYear, tb.runtimeMinutes, tb.genres,
tr.averageRating, tr.numVotes
FROM matching_directors md
JOIN title_crew tc ON tc.directors LIKE '%' || md.nconst || '%'
JOIN title_basics tb ON tc.tconst = tb.tconst
LEFT JOIN title_ratings tr ON tb.tconst = tr.tconst
WHERE 1=1
"""
params = [f"%{self.search_params['search_term']}%"]
# Add additional search conditions
if self.search_params['title_type']:
query += " AND tb.titleType = ?"
params.append(self.search_params['title_type'])
if self.search_params['genre']:
query += " AND tb.genres LIKE ?"
params.append(f"%{self.search_params['genre']}%")
if self.search_params['year']:
query += " AND tb.startYear = ?"
params.append(self.search_params['year'])
if self.search_params['min_rating']:
query += " AND tr.averageRating >= ?"
params.append(self.search_params['min_rating'])
# Add order by - first by year (latest first), then by rating
query += " ORDER BY CASE WHEN tb.startYear IS NULL THEN 0 ELSE tb.startYear END DESC, CASE WHEN tr.averageRating IS NULL THEN 0 ELSE tr.averageRating END DESC, tb.primaryTitle"
return query, params
def cancel(self):
"""Cancel the search process"""
self.is_cancelled = True
class IMDBDatabaseManager:
"""Class to handle database operations for the IMDB database"""
def __init__(self, db_path):
self.db_path = db_path
# Create tables if they don't exist (won't affect existing data)
self.create_tables()
# Ensure the plots table exists when initializing
self.create_plots_table()
# Create indexes if they don't exist
self.create_indexes()
# TMDB API credentials
self.tmdb_api_key = "5c5f1bfbf6d1e1059cd5604602654454"
self.tmdb_read_token = "eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiI1YzVmMWJmYmY2ZDFlMTA1OWNkNTYwNDYwMjY1NDQ1NCIsIm5iZiI6MTc0MTgwMTUwOC4zMywic3ViIjoiNjdkMWM4MjRkNGY3NDEzNzMyNjBhNjY1Iiwic2NvcGVzIjpbImFwaV9yZWFkIl0sInZlcnNpb24iOjF9.OU2EfCOJSShlG5v62hc5P4-vsxWyPx3oQD7ppi-iYmU"
def create_tables(self):
"""Create the required tables if they don't exist"""
try:
conn, cursor = self.connect()
# Create title_basics table if it doesn't exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS title_basics (
tconst TEXT PRIMARY KEY,
titleType TEXT,
primaryTitle TEXT,
originalTitle TEXT,
isAdult INTEGER,
startYear INTEGER,
endYear INTEGER,
runtimeMinutes INTEGER,
genres TEXT
)
""")
# Create title_ratings table if it doesn't exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS title_ratings (
tconst TEXT PRIMARY KEY,
averageRating REAL,
numVotes INTEGER,
FOREIGN KEY(tconst) REFERENCES title_basics(tconst)
)
""")
# Create title_crew table if it doesn't exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS title_crew (
tconst TEXT PRIMARY KEY,
directors TEXT,
writers TEXT,
FOREIGN KEY(tconst) REFERENCES title_basics(tconst)
)
""")
# Create title_episode table if it doesn't exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS title_episode (
tconst TEXT PRIMARY KEY,
parentTconst TEXT,
seasonNumber INTEGER,
episodeNumber INTEGER,
FOREIGN KEY(parentTconst) REFERENCES title_basics(tconst)
)
""")
# Create title_akas table if it doesn't exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS title_akas (
titleId TEXT,
ordering INTEGER,
title TEXT,
region TEXT,
language TEXT,
types TEXT,
attributes TEXT,
isOriginalTitle INTEGER,
PRIMARY KEY(titleId, ordering),
FOREIGN KEY(titleId) REFERENCES title_basics(tconst)
)
""")
# Create name_basics table if it doesn't exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS name_basics (
nconst TEXT PRIMARY KEY,
primaryName TEXT,
birthYear INTEGER,
deathYear INTEGER,
primaryProfession TEXT,
knownForTitles TEXT
)
""")
# Create title_principals table if it doesn't exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS title_principals (
tconst TEXT,
ordering INTEGER,
nconst TEXT,
category TEXT,
job TEXT,
characters TEXT,
PRIMARY KEY(tconst, ordering),
FOREIGN KEY(tconst) REFERENCES title_basics(tconst),
FOREIGN KEY(nconst) REFERENCES name_basics(nconst)
)
""")
conn.commit()
print("Database tables verified successfully")
except Exception as e:
print(f"Error verifying tables: {str(e)}")
finally:
conn.close()
def connect(self):
"""Connect to the database and return connection and cursor"""
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
return conn, cursor
def create_plots_table(self):
"""Create the plots table if it doesn't exist"""
try:
conn, cursor = self.connect()
cursor.execute("""
CREATE TABLE IF NOT EXISTS plots (
tconst TEXT PRIMARY KEY,
plot_summary TEXT,
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
conn.close()
except Exception as e:
print(f"Error creating plots table: {str(e)}")
def get_plot_from_db(self, tconst):
"""Get plot summary from the database if it exists"""
try:
conn, cursor = self.connect()
cursor.execute("SELECT plot_summary FROM plots WHERE tconst = ?", (tconst,))
result = cursor.fetchone()
conn.close()
if result:
return result[0]
return None
except Exception as e:
print(f"Error retrieving plot from database: {str(e)}")
return None
def save_plot_to_db(self, tconst, plot_summary):
"""Save plot summary to the database"""
try:
conn, cursor = self.connect()
cursor.execute("""
INSERT OR REPLACE INTO plots (tconst, plot_summary, last_updated)
VALUES (?, ?, CURRENT_TIMESTAMP)
""", (tconst, plot_summary))
conn.commit()
conn.close()
return True
except Exception as e:
print(f"Error saving plot to database: {str(e)}")
return False
def get_title_types(self):
"""Get all unique title types from the database"""
conn, cursor = self.connect()
cursor.execute("SELECT DISTINCT titleType FROM title_basics ORDER BY titleType")
types = [row[0] for row in cursor.fetchall()]
conn.close()
return types
def get_genres(self):
"""Get all unique genres from the database"""
conn, cursor = self.connect()
cursor.execute("SELECT DISTINCT value FROM (SELECT DISTINCT genres FROM title_basics) t, json_each(json_array(t.genres)) WHERE value IS NOT NULL ORDER BY value")
genres = [row[0] for row in cursor.fetchall()]
conn.close()
return genres
def search_titles(self, search_term="", title_type=None, genre=None, year=None, min_rating=None, page=1, page_size=20):
"""Search for titles based on various criteria, with pagination"""
conn, cursor = self.connect()
# Base query
query = """
SELECT tb.tconst, tb.titleType, tb.primaryTitle, tb.originalTitle,
tb.startYear, tb.endYear, tb.runtimeMinutes, tb.genres,
tr.averageRating, tr.numVotes
FROM title_basics tb
LEFT JOIN title_ratings tr ON tb.tconst = tr.tconst
WHERE 1=1
"""
params = []
# Add search conditions
if search_term:
query += " AND (tb.primaryTitle LIKE ? OR tb.originalTitle LIKE ?)"
params.extend([f"%{search_term}%", f"%{search_term}%"])
if title_type:
query += " AND tb.titleType = ?"
params.append(title_type)
if genre:
query += " AND tb.genres LIKE ?"
params.append(f"%{genre}%")
if year:
query += " AND tb.startYear = ?"
params.append(year)
if min_rating:
query += " AND tr.averageRating >= ?"
params.append(min_rating)
# Count total results (for pagination)
count_query = f"SELECT COUNT(*) FROM ({query}) as count_query"
cursor.execute(count_query, params)
total_count = cursor.fetchone()[0]
# Add order by and pagination - first by year (latest first), then by rating
query += " ORDER BY CASE WHEN tb.startYear IS NULL THEN 0 ELSE tb.startYear END DESC, CASE WHEN tr.averageRating IS NULL THEN 0 ELSE tr.averageRating END DESC, tb.primaryTitle"
query += " LIMIT ? OFFSET ?"
# Calculate offset
offset = (page - 1) * page_size
params.append(page_size)
params.append(offset)
cursor.execute(query, params)
results = [dict(row) for row in cursor.fetchall()]
conn.close()
return results, total_count
def get_title_details(self, tconst):
"""Get detailed information about a specific title"""
conn, cursor = self.connect()
# Get basic title information
cursor.execute("""
SELECT tb.tconst, tb.titleType, tb.primaryTitle, tb.originalTitle,
tb.isAdult, tb.startYear, tb.endYear, tb.runtimeMinutes, tb.genres,
tr.averageRating, tr.numVotes
FROM title_basics tb
LEFT JOIN title_ratings tr ON tb.tconst = tr.tconst
WHERE tb.tconst = ?
""", (tconst,))
title_info = dict(cursor.fetchone() or {})
if not title_info:
conn.close()
return None
# Get crew information
cursor.execute("""
SELECT tc.directors, tc.writers
FROM title_crew tc
WHERE tc.tconst = ?
""", (tconst,))
crew_info = dict(cursor.fetchone() or {})
title_info.update(crew_info)
# Get director and writer names
if 'directors' in title_info and title_info['directors']:
directors = title_info['directors'].split(',')
director_names = []
for director in directors:
cursor.execute("""
SELECT primaryName FROM name_basics
WHERE nconst = ?
""", (director,))
result = cursor.fetchone()
if result:
director_names.append(result[0])
title_info['director_names'] = director_names
if 'writers' in title_info and title_info['writers']:
writers = title_info['writers'].split(',')
writer_names = []
for writer in writers:
cursor.execute("""
SELECT primaryName FROM name_basics
WHERE nconst = ?
""", (writer,))
result = cursor.fetchone()
if result:
writer_names.append(result[0])
title_info['writer_names'] = writer_names
# Get principal cast
cursor.execute("""
SELECT tp.ordering, tp.nconst, tp.category, tp.job, tp.characters,
nb.primaryName
FROM title_principals tp
JOIN name_basics nb ON tp.nconst = nb.nconst
WHERE tp.tconst = ?
ORDER BY tp.ordering
""", (tconst,))
cast = [dict(row) for row in cursor.fetchall()]
title_info['cast'] = cast
# Get alternative titles
cursor.execute("""
SELECT ordering, title, region, language, types, attributes, isOriginalTitle
FROM title_akas
WHERE titleId = ?
ORDER BY ordering
""", (tconst,))
akas = [dict(row) for row in cursor.fetchall()]
title_info['akas'] = akas
# If it's a TV series, get episodes
if title_info['titleType'] == 'tvSeries':
cursor.execute("""
SELECT te.tconst, te.seasonNumber, te.episodeNumber,
tb.primaryTitle, tb.originalTitle, tb.startYear,
tr.averageRating
FROM title_episode te
JOIN title_basics tb ON te.tconst = tb.tconst
LEFT JOIN title_ratings tr ON te.tconst = tr.tconst
WHERE te.parentTconst = ?
ORDER BY te.seasonNumber, te.episodeNumber
""", (tconst,))
episodes = [dict(row) for row in cursor.fetchall()]
title_info['episodes'] = episodes
conn.close()
return title_info
def get_person_details(self, nconst):
"""Get detailed information about a person"""
conn, cursor = self.connect()
# Get basic person information
cursor.execute("""
SELECT nconst, primaryName, birthYear, deathYear, primaryProfession, knownForTitles
FROM name_basics
WHERE nconst = ?
""", (nconst,))
person_info = dict(cursor.fetchone() or {})
if not person_info:
conn.close()
return None
# Get titles they're known for
if 'knownForTitles' in person_info and person_info['knownForTitles']:
known_for_tconsts = person_info['knownForTitles'].split(',')
known_for_titles = []
placeholders = ','.join(['?'] * len(known_for_tconsts))
cursor.execute(f"""
SELECT tb.tconst, tb.primaryTitle, tb.titleType, tb.startYear,
tr.averageRating
FROM title_basics tb
LEFT JOIN title_ratings tr ON tb.tconst = tr.tconst
WHERE tb.tconst IN ({placeholders})
ORDER BY CASE WHEN tb.startYear IS NULL THEN 0 ELSE tb.startYear END DESC
""", known_for_tconsts)
known_for_titles = [dict(row) for row in cursor.fetchall()]
person_info['known_for_titles'] = known_for_titles
# Get all titles they've worked on
cursor.execute("""
SELECT tp.tconst, tp.category, tp.job, tp.characters,
tb.primaryTitle, tb.titleType, tb.startYear,
tr.averageRating
FROM title_principals tp
JOIN title_basics tb ON tp.tconst = tb.tconst
LEFT JOIN title_ratings tr ON tp.tconst = tr.tconst
WHERE tp.nconst = ?
ORDER BY CASE WHEN tb.startYear IS NULL THEN 0 ELSE tb.startYear END DESC,
CASE WHEN tr.averageRating IS NULL THEN 0 ELSE tr.averageRating END DESC
""", (nconst,))
filmography = [dict(row) for row in cursor.fetchall()]
person_info['filmography'] = filmography
conn.close()
return person_info
def get_image_path(self, tconst):
"""Get the path to the image for a title, if it exists"""
app_dir = os.path.dirname(os.path.abspath(__file__))
image_dir = os.path.join(app_dir, "imdb_images")
# Check for different image extensions
for ext in ['.jpg', '.jpeg', '.png']:
image_path = os.path.join(image_dir, f"{tconst}{ext}")
if os.path.exists(image_path):
return image_path
return None
def get_plot_from_tmdb(self, tconst, title, year, is_tv=False):
"""Get plot summary from TMDB API"""
try:
# First, search for the movie or TV show by title and year
media_type = "tv" if is_tv else "movie"
search_url = f"https://api.themoviedb.org/3/search/{media_type}"
headers = {
"Authorization": f"Bearer {self.tmdb_read_token}",
"Content-Type": "application/json;charset=utf-8"
}
params = {
"api_key": self.tmdb_api_key,
"query": title,
"year": year if year and year.isdigit() else None
}
# Remove None values from params
params = {k: v for k, v in params.items() if v is not None}
print(f"TMDB Search URL: {search_url} with params: {params}")
# Make the search request
search_response = requests.get(search_url, headers=headers, params=params)
if search_response.status_code != 200:
print(f"TMDB search request failed with status code: {search_response.status_code}")
return None
search_data = search_response.json()
# Check if we found any results
if not search_data.get('results') or len(search_data['results']) == 0:
print(f"No results found on TMDB for {title} ({year})")
return None
# Get the ID of the first result
tmdb_id = search_data['results'][0]['id']
print(f"Found TMDB ID: {tmdb_id} for {title}")
# Now get the details for this movie/TV show
details_url = f"https://api.themoviedb.org/3/{media_type}/{tmdb_id}"
details_params = {
"api_key": self.tmdb_api_key,
"language": "en-US"
}
print(f"TMDB Details URL: {details_url}")
details_response = requests.get(details_url, headers=headers, params=details_params)
if details_response.status_code != 200:
print(f"TMDB details request failed with status code: {details_response.status_code}")
return None
details_data = details_response.json()
# Extract the overview (plot summary)
overview = details_data.get('overview', '')
if overview:
print(f"Successfully retrieved overview from TMDB: {overview[:100]}...")
return overview
else:
print("Overview field was empty in TMDB response")
return None
except Exception as e:
print(f"Error retrieving plot from TMDB: {str(e)}")
return None
def get_plot_summary(self, tconst):
"""Get plot summary for a title, first checking the database, then TMDB"""
# First check if we have it in the database
db_plot = self.get_plot_from_db(tconst)
if db_plot:
print(f"Found plot in database for {tconst}")
return db_plot
# If not in database, get from TMDB
try:
# First, get basic title info from our database
conn, cursor = self.connect()
cursor.execute("""
SELECT primaryTitle, titleType, startYear
FROM title_basics
WHERE tconst = ?
""", (tconst,))
title_info = cursor.fetchone()
conn.close()
if title_info:
title = title_info[0]
is_tv = title_info[1] in ['tvSeries', 'tvMiniSeries', 'tvSpecial']
year = str(title_info[2]) if title_info[2] else None
# Get plot from TMDB
print(f"Requesting plot from TMDB for {tconst} ({title}, {year})")
tmdb_plot = self.get_plot_from_tmdb(tconst, title, year, is_tv)
if tmdb_plot:
print(f"Successfully retrieved plot from TMDB for {tconst}")
return tmdb_plot
else:
print(f"No plot found on TMDB for {tconst}")
# If we get here, we couldn't find a plot
return "Plot summary not available from TMDB."
except Exception as e:
print(f"Error retrieving plot from TMDB: {str(e)}")
return f"Error retrieving plot summary: {str(e)}"
def search_titles_by_cast(self, cast_name, title_type=None, genre=None, year=None, min_rating=None, page=1, page_size=20):
"""Search for titles based on cast member name, with pagination"""
conn, cursor = self.connect()
# Base query - join with name_basics and title_principals to search by cast name
query = """
SELECT DISTINCT tb.tconst, tb.titleType, tb.primaryTitle, tb.originalTitle,
tb.startYear, tb.endYear, tb.runtimeMinutes, tb.genres,
tr.averageRating, tr.numVotes
FROM title_basics tb
LEFT JOIN title_ratings tr ON tb.tconst = tr.tconst
JOIN title_principals tp ON tb.tconst = tp.tconst
JOIN name_basics nb ON tp.nconst = nb.nconst
WHERE nb.primaryName LIKE ?
"""
params = [f"%{cast_name}%"]
# Add additional search conditions
if title_type:
query += " AND tb.titleType = ?"
params.append(title_type)
if genre:
query += " AND tb.genres LIKE ?"
params.append(f"%{genre}%")
if year:
query += " AND tb.startYear = ?"
params.append(year)
if min_rating:
query += " AND tr.averageRating >= ?"
params.append(min_rating)
# Count total results (for pagination)
count_query = f"SELECT COUNT(*) FROM ({query}) as count_query"
cursor.execute(count_query, params)
total_count = cursor.fetchone()[0]
# Add order by and pagination - first by year (latest first), then by rating
query += " ORDER BY CASE WHEN tb.startYear IS NULL THEN 0 ELSE tb.startYear END DESC, CASE WHEN tr.averageRating IS NULL THEN 0 ELSE tr.averageRating END DESC, tb.primaryTitle"
query += " LIMIT ? OFFSET ?"
# Calculate offset
offset = (page - 1) * page_size
params.append(page_size)
params.append(offset)
cursor.execute(query, params)
results = [dict(row) for row in cursor.fetchall()]
conn.close()
return results, total_count
def create_indexes(self):
"""Create indexes on the database tables to improve search performance"""
try:
conn, cursor = self.connect()
# Check if indexes already exist
cursor.execute("SELECT name FROM sqlite_master WHERE type='index' AND name='idx_name_basics_primaryName'")
if not cursor.fetchone():
print("Creating indexes on database tables...")
# Index on name_basics.primaryName for faster cast member searches
cursor.execute("CREATE INDEX idx_name_basics_primaryName ON name_basics(primaryName)")
# Index on title_principals.nconst for faster joins
cursor.execute("CREATE INDEX idx_title_principals_nconst ON title_principals(nconst)")
# Index on title_principals.tconst for faster joins
cursor.execute("CREATE INDEX idx_title_principals_tconst ON title_principals(tconst)")
# Index on title_basics.primaryTitle for faster title searches
cursor.execute("CREATE INDEX idx_title_basics_primaryTitle ON title_basics(primaryTitle)")
# Index on title_basics.originalTitle for faster title searches
cursor.execute("CREATE INDEX idx_title_basics_originalTitle ON title_basics(originalTitle)")
# Index on title_basics.startYear for faster year filtering
cursor.execute("CREATE INDEX idx_title_basics_startYear ON title_basics(startYear)")
# Index on title_ratings.averageRating for faster rating filtering
cursor.execute("CREATE INDEX idx_title_ratings_averageRating ON title_ratings(averageRating)")
# Index on title_crew.directors for faster director searches
cursor.execute("CREATE INDEX idx_title_crew_directors ON title_crew(directors)")
conn.commit()
print("Database indexes created successfully.")
else:
print("Database indexes already exist.")
# Check if we need to add the directors index separately
cursor.execute("SELECT name FROM sqlite_master WHERE type='index' AND name='idx_title_crew_directors'")
if not cursor.fetchone():
print("Adding index on title_crew.directors...")
cursor.execute("CREATE INDEX idx_title_crew_directors ON title_crew(directors)")
conn.commit()
print("Directors index created successfully.")
conn.close()
except Exception as e:
print(f"Error creating indexes: {str(e)}")
def search_titles_by_director(self, director_name, title_type=None, genre=None, year=None, min_rating=None, page=1, page_size=20):
"""Search for titles based on director name, with pagination"""
conn, cursor = self.connect()
# Base query - join with name_basics and title_crew to search by director name
query = """
WITH matching_directors AS (
SELECT nconst, primaryName
FROM name_basics
WHERE primaryName LIKE ?
LIMIT 100
)
SELECT DISTINCT tb.tconst, tb.titleType, tb.primaryTitle, tb.originalTitle,
tb.startYear, tb.endYear, tb.runtimeMinutes, tb.genres,
tr.averageRating, tr.numVotes
FROM matching_directors md
JOIN title_crew tc ON tc.directors LIKE '%' || md.nconst || '%'
JOIN title_basics tb ON tc.tconst = tb.tconst
LEFT JOIN title_ratings tr ON tb.tconst = tr.tconst
WHERE 1=1
"""
params = [f"%{director_name}%"]
# Add additional search conditions
if title_type:
query += " AND tb.titleType = ?"
params.append(title_type)
if genre:
query += " AND tb.genres LIKE ?"
params.append(f"%{genre}%")
if year:
query += " AND tb.startYear = ?"
params.append(year)
if min_rating:
query += " AND tr.averageRating >= ?"
params.append(min_rating)
# Count total results (for pagination)
count_query = f"SELECT COUNT(*) FROM ({query}) as count_query"
cursor.execute(count_query, params)
total_count = cursor.fetchone()[0]
# Add order by and pagination - first by year (latest first), then by rating