import requests
import json
from typing import List, Dict, Optional
class MovieRecommender:
def __init__(self, api_key: str):
"""
Initialize the MovieRecommender with TMDb API key.
Get your free API key from: https://www.themoviedb.org/settings/api
"""
self.api_key = api_key
self.base_url = "https://api.themoviedb.org/3"
self.image_base_url = "https://image.tmdb.org/t/p/w500"
def search_movie(self, query: str) -> Optional[Dict]:
"""
Search for a movie by title and return the first matching result.
"""
params = {
"api_key": self.api_key,
"query": query,
"language": "en-US"
}
response = requests.get(f"{self.base_url}/search/movie", params=params)
if response.status_code == 200:
data = response.json()
if data["results"]:
return data["results"][0] # Return the top match
return None
def get_movie_recommendations(self, movie_id: int, page: int = 1) -> List[Dict]:
"""
Get recommended movies for a given movie ID.
"""
params = {
"api_key": self.api_key,
"language": "en-US",
"page": page
}
response = requests.get(f"{self.base_url}/movie/{movie_id}/recommendations", params=params)
if response.status_code == 200:
return response.json()["results"]
return []
def get_movie_details(self, movie_id: int) -> Optional[Dict]:
"""
Get detailed info for a movie.
"""
params = {"api_key": self.api_key, "language": "en-US"}
response = requests.get(f"{self.base_url}/movie/{movie_id}", params=params)
if response.status_code == 200:
return response.json()
return None
def recommend(self, liked_movie_title: str, num_recs: int = 10) -> List[Dict]:
"""
Main recommendation function: Find a movie by title, then get recommendations.
"""
print(f"Searching for movie: '{liked_movie_title}'...")
movie = self.search_movie(liked_movie_title)
if not movie:
print("Movie not found. Try a different title.")
return []
movie_id = movie["id"]
movie_title = movie["title"]
print(f"Found: {movie_title} ({movie['release_date'][:4]})")
print("Fetching recommendations...")
recs = self.get_movie_recommendations(movie_id)
# Fetch more pages if needed
while len(recs) < num_recs and "next_page" in locals():
next_page = 2 # Simple pagination
more_recs = self.get_movie_recommendations(movie_id, next_page)
recs.extend(more_recs)
next_page += 1
# Filter and sort by popularity/vote average
recs = [r for r in recs if r["vote_average"] > 6.0][:num_recs]
recs.sort(key=lambda x: x["vote_average"], reverse=True)
return recs
def main():
print("=== Movie Recommender using TMDb API ===")
print("This script uses The Movie Database (TMDb) API for ethical data access.")
print("Sign up for a free API key: https://www.themoviedb.org/settings/api")
api_key = input("Enter your TMDb API key: ").strip()
if not api_key:
print("API key required. Exiting.")
return
recommender = MovieRecommender(api_key)
while True:
liked_movie = input("\nEnter a movie you like (or 'quit' to exit): ").strip()
if liked_movie.lower() == 'quit':
break
recs = recommender.recommend(liked_movie, num_recs=10)
if recs:
print("\nTop Recommendations:")
print("-" * 80)
for i, rec in enumerate(recs, 1):
title = rec["title"]
year = rec["release_date"][:4] if rec["release_date"] else "N/A"
rating = rec["vote_average"]
overview = rec["overview"][:100] + "..." if rec["overview"] else "No overview."
poster = recommender.image_base_url + rec["poster_path"] if rec["poster_path"] else "No poster."
print(f"{i}. {title} ({year}) - Rating: {rating}/10")
print(f" {overview}")
print(f" Poster: {poster}")
print()
else:
print("No recommendations found.")
if __name__ == "__main__":
main()