|
import streamlit as st |
|
import pandas as pd |
|
import requests |
|
import pickle |
|
|
|
|
|
with open('movie_data.pkl', 'rb') as file: |
|
movies, cosine_sim = pickle.load(file) |
|
|
|
|
|
def get_recommendations(title, cosine_sim=cosine_sim): |
|
idx = movies[movies['title'] == title].index[0] |
|
sim_scores = list(enumerate(cosine_sim[idx])) |
|
sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True) |
|
sim_scores = sim_scores[1:11] |
|
movie_indices = [i[0] for i in sim_scores] |
|
return movies[['title', 'movie_id']].iloc[movie_indices] |
|
|
|
|
|
def fetch_movie_data(movie_id): |
|
api_key = "5c1c27e14a6a61a873db79d82528056f" |
|
url = f'https://api.themoviedb.org/3/movie/{movie_id}?api_key={api_key}&append_to_response=videos,images' |
|
|
|
try: |
|
response = requests.get(url) |
|
response.raise_for_status() |
|
data = response.json() |
|
|
|
|
|
poster_path = data.get('poster_path') |
|
poster_url = f"https://image.tmdb.org/t/p/w500{poster_path}" if poster_path else \ |
|
"https://via.placeholder.com/500x750?text=No+Image+Available" |
|
|
|
|
|
videos = data.get('videos', {}).get('results', []) |
|
trailer = next((v for v in videos if v.get('type') == 'Trailer'), None) |
|
|
|
|
|
backdrops = data.get('images', {}).get('backdrops', []) |
|
backdrop_path = backdrops[0].get('file_path') if backdrops else '' |
|
|
|
|
|
overview = data.get('overview', 'No description available')[:100] + "..." |
|
|
|
return { |
|
'poster': poster_url, |
|
'trailer_key': trailer.get('key') if trailer else None, |
|
'backdrop': backdrop_path, |
|
'overview': overview |
|
} |
|
|
|
except requests.exceptions.RequestException as e: |
|
st.error(f"API Error: {str(e)}") |
|
return { |
|
'poster': "https://via.placeholder.com/500x750?text=No+Image+Available", |
|
'trailer_key': None, |
|
'backdrop': '', |
|
'overview': 'No description available' |
|
} |
|
|
|
|
|
st.title("Movie Recommendation System") |
|
|
|
selected_movie = st.selectbox("Select a movie:", movies['title'].values) |
|
|
|
if st.button('Recommend'): |
|
recommendations = get_recommendations(selected_movie) |
|
st.write("Top 10 recommended movies:") |
|
|
|
|
|
for i in range(0, 10, 5): |
|
cols = st.columns(5) |
|
for col, j in zip(cols, range(i, i+5)): |
|
if j < len(recommendations): |
|
movie_title = recommendations.iloc[j]['title'] |
|
movie_id = recommendations.iloc[j]['movie_id'] |
|
movie_data = fetch_movie_data(movie_id) |
|
|
|
with col: |
|
st.image(movie_data['poster'], width=130, caption=movie_title) |
|
if movie_data['trailer_key']: |
|
st.markdown(f"[Watch Trailer](https://www.youtube.com/watch?v={movie_data['trailer_key']})") |
|
st.write(movie_data['overview'][:100] + "...") |