-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
110 lines (80 loc) · 4.11 KB
/
Copy pathapp.py
File metadata and controls
110 lines (80 loc) · 4.11 KB
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
from flask import Flask, request, jsonify, render_template
import pickle
import pandas as pd
import requests
app = Flask(__name__)
# Load pre-trained movie recommendation models
# `movies_list.pkl` contains movie data (titles and IDs)
# `similarity.pkl` is a precomputed similarity matrix for recommendations
movies = pickle.load(open("movies_list.pkl", 'rb'))
similarity = pickle.load(open("similarity.pkl", 'rb'))
# TMDB API Key (for fetching movie posters and ratings)
API_KEY = "c7ec19ffdd3279641fb606d19ceb9bb1"
def fetch_movie_details(movie_id):
"""
Fetch movie details (poster URL and rating) from TMDB using the given movie ID.
:param movie_id: TMDB movie ID
:return: Dictionary containing poster URL and rating
"""
url = f"https://api.themoviedb.org/3/movie/{movie_id}?api_key={API_KEY}&language=en-US"
data = requests.get(url).json()
poster_path = data.get('poster_path', '') # Extract poster path (if available)
rating = data.get('vote_average', 'N/A') # Extract rating, default to 'N/A' if missing
return {
'poster': f"https://image.tmdb.org/t/p/w500/{poster_path}" if poster_path else "", # Full poster URL
'rating': rating
}
@app.route('/')
def home():
"""
Render the homepage (index.html).
:return: Rendered HTML template
"""
return render_template('index.html')
@app.route('/suggest', methods=['GET'])
def suggest():
"""
Suggest movie names based on user input.
:return: JSON response containing up to 10 suggested movie titles
"""
query = request.args.get('query', '').strip().lower() # Get user query, strip whitespace, and convert to lowercase
if not query:
return jsonify({'suggestions': []}) # Return an empty list if query is empty
# Filter movies whose titles start with the query string (case-insensitive search)
suggestions = movies[movies['title'].str.lower().str.startswith(query)]['title'].tolist()
return jsonify({'suggestions': suggestions[:10]}) # Return up to 10 suggestions
@app.route('/recommend', methods=['POST'])
def recommend():
"""
Recommend similar movies based on a given movie title.
:return: JSON response containing recommended movie titles, posters, and ratings
"""
data = request.json # Get JSON data from request
movie_name = data.get('movie', '').strip() # Extract movie name and strip whitespace
if not movie_name:
return jsonify({'message': 'Movie name is required'}), 400 # Return error if no movie name provided
try:
# Find index of the movie in the dataset
index = movies[movies['title'] == movie_name].index[0]
# Get similarity scores for the given movie and sort them in descending order
distances = sorted(list(enumerate(similarity[index])), reverse=True, key=lambda x: x[1])
recommend_movies = [] # List to store recommended movie titles
recommend_posters = [] # List to store corresponding movie poster URLs
recommend_ratings = [] # List to store corresponding movie ratings
# Fetch details for the top 6 recommended movies (excluding the input movie)
for i in distances[1:7]:
movie_id = movies.iloc[i[0]].id # Get movie ID
movie_details = fetch_movie_details(movie_id) # Fetch poster and rating
recommend_movies.append(movies.iloc[i[0]].title) # Append movie title
recommend_posters.append(movie_details['poster']) # Append poster URL
recommend_ratings.append(movie_details['rating']) # Append rating
return jsonify({
'movies': recommend_movies,
'posters': recommend_posters,
'ratings': recommend_ratings
})
except IndexError:
return jsonify({'message': 'Movie not found'}), 404 # Return error if movie is not found in dataset
if __name__ == '__main__':
print(app.url_map) # Print all registered routes for debugging purposes
app.run(debug=True) # Run the Flask app with debugging enabled