A movie recommendation system built in Python using the streamlit
library for interface and TMDB API integration to deliver personalized recommendations with movie posters. The system combines efficient data management with real-time API integration to provide a seamless user experience.
pickle
files to store pre-computed similarity scores for faster retrievalimport pickle import streamlit as st import requests # Load pre-computed data with error handling try: movies = pickle.load(open("movie_list.pkl",'rb')) similarity = pickle.load(open('similarity.pkl','rb')) except FileNotFoundError: st.error("Required data files not found. Please check the data directory.") # Configure movie list with type checking movie_list = movies['title'].values if 'title' in movies else []
def fetch_poster(movie_id): """ Fetches movie poster from TMDB API with error handling and caching """ try: # Construct API URL with movie ID url = "https://api.themoviedb.org/3/movie/{}?api_key=8265bd1679663a7ea12ac168da84d2e8&language=en-US".format(movie_id) # Fetch and process data with timeout data = requests.get(url, timeout=5).json() # Handle missing poster path if 'poster_path' not in data or data['poster_path'] is None: return "default_poster_url" # Return complete poster URL return "https://image.tmdb.org/t/p/w500/" + data['poster_path'] except requests.RequestException as e: st.warning(f"Error fetching poster: {str(e)}") return "default_poster_url"
def recommend(movie, num_recommendations=5): """ Generates movie recommendations based on similarity scores """ try: # Find movie index with validation if movie not in movies['title'].values: return [], [] index = movies[movies['title'] == movie].index[0] # Get and sort similarity scores distances = sorted( list(enumerate(similarity[index])), reverse=True, key=lambda x: x[1] ) # Initialize recommendation lists recommended_movie_names = [] recommended_movie_posters = [] # Process top similar movies for i in distances[1:num_recommendations+1]: movie_id = movies.iloc[i[0]].movie_id # Fetch poster with error handling poster_url = fetch_poster(movie_id) if poster_url != "default_poster_url": recommended_movie_posters.append(poster_url) recommended_movie_names.append(movies.iloc[i[0]].title) return recommended_movie_names, recommended_movie_posters except Exception as e: st.error(f"Error generating recommendations: {str(e)}") return [], []
# Configure page settings st.set_page_config( page_title="Movie Recommender", layout="wide" ) # Create header with styling st.markdown(""" <style> .title { text-align: center; color: #1E88E5; } </style> """, unsafe_allow_html=True) st.markdown("<h1 class='title'>Movie Recommender System</h1>", unsafe_allow_html=True) # Setup movie selection with search functionality selected_movie = st.selectbox( "Type or select a movie from the dropdown", movie_list, help="Search for a movie by typing its name" ) # Handle recommendation button with loading state if st.button('Show Recommendation'): with st.spinner('Fetching recommendations...'): names, posters = recommend(selected_movie) if not names: st.warning("No recommendations found.") else: # Create responsive column layout cols = st.columns(5) # Display recommendations with error handling for idx, (name, poster) in enumerate(zip(names, posters)): with cols[idx]: st.text(name) try: st.image(poster, use_column_width=True) except Exception: st.error("Error loading poster")
Output:
App Link: https://huggingface.co/spaces/AbhayBhaskar/Personalized-Movie-Recommendation-System