Agrannya commited on
Commit
024be50
Β·
verified Β·
1 Parent(s): 0b3fd85

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1004 -28
app.py CHANGED
@@ -10,24 +10,36 @@ from sklearn.metrics.pairwise import cosine_similarity
10
  from flask import Flask, request, jsonify
11
  from flask_cors import CORS
12
  import gradio as gr
13
- from typing import List, Dict, Any
14
  import html
15
  import re
 
 
16
 
17
- # --- MovieRecommendationSystem Class ---
 
 
 
 
 
 
 
 
 
18
  class MovieRecommendationSystem:
19
  def __init__(self):
20
  self.movies_df = None
21
  self.similarity_matrix = None
22
  self.vectorizer = CountVectorizer(stop_words='english')
23
- # Use Hugging Face secret for OMDb API key
24
- self.API_KEY = os.getenv("OpenIMBD")
25
  if not self.API_KEY:
26
- print("🚨 WARNING: OpenIMBD secret not found in environment variables.")
27
  self.BASE_URL = "http://www.omdbapi.com/"
28
  self.HEADERS = {}
29
 
30
  def fetch_movie_by_title(self, title):
 
31
  if not self.API_KEY:
32
  print("OMDb API key is not set. Cannot fetch movie.")
33
  return None
@@ -37,7 +49,7 @@ class MovieRecommendationSystem:
37
  "plot": "full"
38
  }
39
  try:
40
- response = requests.get(self.BASE_URL, headers=self.HEADERS, params=params, timeout=10)
41
  if response.status_code == 200:
42
  data = response.json()
43
  if data.get("Response") == "True":
@@ -51,7 +63,8 @@ class MovieRecommendationSystem:
51
  print(f"Error fetching movie '{title}': {e}")
52
  return None
53
 
54
- def fetch_movies(self, titles=None, limit=30): # Limit for demo speed
 
55
  if titles is None:
56
  titles = [
57
  "Inception", "The Dark Knight", "Interstellar", "The Matrix", "Fight Club",
@@ -59,16 +72,83 @@ class MovieRecommendationSystem:
59
  "Avatar", "The Avengers", "Jurassic Park", "Star Wars", "The Lord of the Rings",
60
  "Harry Potter", "Pirates of the Caribbean", "The Godfather", "Back to the Future",
61
  "Indiana Jones", "The Lion King", "Toy Story", "Finding Nemo", "Up", "WALL-E",
62
- "The Incredibles", "Coco", "Spider-Man", "Iron Man", "Captain America"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  ][:limit]
 
 
64
  movies = []
65
- for title in titles:
 
 
66
  movie_data = self.fetch_movie_by_title(title)
67
  if movie_data:
68
  movies.append(movie_data)
 
69
  return movies
70
 
71
  def prepare_movie_data(self):
 
72
  movies = self.fetch_movies()
73
  if not movies:
74
  print("🚨 API returned no movies. Loading fallback dataset.")
@@ -101,6 +181,7 @@ class MovieRecommendationSystem:
101
  return self.movies_df
102
 
103
  def build_similarity_matrix(self):
 
104
  if self.movies_df is not None and not self.movies_df.empty:
105
  max_features = 5000
106
  self.vectorizer = CountVectorizer(stop_words='english', max_features=max_features)
@@ -109,36 +190,46 @@ class MovieRecommendationSystem:
109
  self.similarity_matrix = cosine_similarity(vectorized_features)
110
  print(f"βœ… Similarity matrix built with shape: {self.similarity_matrix.shape}")
111
  else:
112
- print("🚨 Cannot build similarity matrix: movies_df is empty.")
 
113
 
114
  def get_recommendations(self, selected_movie_ids, num_recommendations=5):
 
115
  if self.similarity_matrix is None or self.movies_df.empty:
116
  print("Debug: Similarity matrix or movies_df is empty.")
117
  return []
 
118
  selected_indices = self.movies_df[self.movies_df['id'].isin(selected_movie_ids)].index.tolist()
 
119
  if not selected_indices:
120
  print("Debug: No selected movies found in DataFrame for recommendations.")
121
  return []
 
122
  avg_similarity_scores = np.mean(self.similarity_matrix[selected_indices], axis=0)
 
123
  movie_indices = np.argsort(avg_similarity_scores)[::-1]
 
124
  recommendations = []
125
  for idx in movie_indices:
126
  movie = self.movies_df.iloc[idx]
 
127
  if movie['id'] not in selected_movie_ids:
128
  recommendations.append(movie.to_dict())
129
  if len(recommendations) >= num_recommendations:
130
  break
 
131
  return recommendations
132
 
133
  # Initialize the recommender globally
134
  recommender = MovieRecommendationSystem()
135
 
136
- # --- Flask Application ---
137
  app = Flask(__name__)
138
- CORS(app)
139
 
140
  @app.route('/')
141
  def index():
 
142
  return jsonify({
143
  "message": "Netflix Clone API is running!",
144
  "status": "success",
@@ -147,76 +238,961 @@ def index():
147
 
148
  @app.route('/api/movies')
149
  def get_movies():
 
150
  try:
151
  if recommender.movies_df is None or recommender.movies_df.empty:
152
  print("Preparing movie data...")
153
  recommender.prepare_movie_data()
154
  print(f"Loaded {len(recommender.movies_df)} movies")
 
155
  movies = recommender.movies_df.to_dict('records')
156
  return jsonify(movies)
 
157
  except Exception as e:
158
  print(f"Error in get_movies: {e}")
159
  return jsonify({'error': 'Failed to fetch movies'}), 500
160
 
161
  @app.route('/api/recommend', methods=['POST'])
162
  def recommend_movies():
 
163
  try:
164
  data = request.json
165
  selected_movie_ids = data.get('selected_movies', [])
 
166
  if len(selected_movie_ids) < 5:
167
  return jsonify({'error': 'Please select at least 5 movies'}), 400
 
168
  print(f"Getting recommendations for movies: {selected_movie_ids}")
169
  recommendations = recommender.get_recommendations(selected_movie_ids)
 
170
  return jsonify(recommendations)
 
171
  except Exception as e:
172
  print(f"Error in recommend_movies: {e}")
173
  return jsonify({'error': 'Failed to get recommendations'}), 500
174
 
175
  @app.route('/api/health')
176
  def health_check():
 
177
  return jsonify({
178
  "status": "healthy",
179
  "movies_loaded": len(recommender.movies_df) if recommender.movies_df is not None else 0,
180
  "similarity_matrix_built": recommender.similarity_matrix is not None
181
  })
182
 
 
183
  def start_flask_server():
 
184
  try:
185
  print("πŸš€ Starting Flask backend server...")
 
186
  app.run(host='127.0.0.1', port=5000, debug=False)
187
  except Exception as e:
188
  print(f"❌ Error starting Flask server: {e}")
189
 
190
- # --- Gradio Application ---
 
 
191
  API_BASE_URL = "http://127.0.0.1:5000"
 
192
  MAX_SELECTIONS = 10
193
  MIN_RECOMMENDATIONS = 5
194
 
195
  class CinemaCloneApp:
196
- # ... (keep your CinemaCloneApp class as in your original code) ...
197
- # No changes needed for secrets here
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198
 
199
  # Initialize the app instance globally
200
  gradio_app_instance = CinemaCloneApp()
201
 
202
- # ... (keep your Gradio UI and event handlers as in your original code) ...
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  if __name__ == "__main__":
205
- # For Hugging Face Spaces, do NOT use load_dotenv()
 
206
  # Start Flask server in a separate thread
207
  flask_thread = threading.Thread(target=start_flask_server)
208
  flask_thread.daemon = True
209
  flask_thread.start()
210
- time.sleep(10)
211
- demo.launch(server_name="0.0.0.0")
212
 
213
- # --- Ngrok usage example (if needed) ---
214
- NGROK_AUTH_TOKEN = os.getenv("Ngrok")
215
- if NGROK_AUTH_TOKEN:
216
- try:
217
- from pyngrok import ngrok
218
- ngrok.set_auth_token(NGROK_AUTH_TOKEN)
219
- # Example: ngrok.connect(7860)
220
- except ImportError:
221
- print("pyngrok not installed; skipping ngrok setup.")
222
 
 
10
  from flask import Flask, request, jsonify
11
  from flask_cors import CORS
12
  import gradio as gr
13
+ from typing import List, Dict, Any, Optional
14
  import html
15
  import re
16
+ from dotenv import load_dotenv # Import load_dotenv
17
+ from pyngrok import ngrok
18
 
19
+ # --- Ngrok usage example (if needed) ---
20
+ NGROK_AUTH_TOKEN = os.getenv("Ngrok")
21
+ if NGROK_AUTH_TOKEN:
22
+ try:
23
+ ngrok.set_auth_token(NGROK_AUTH_TOKEN)
24
+ # Example: ngrok.connect(7860)
25
+ except ImportError:
26
+ print("pyngrok not installed; skipping ngrok setup.")
27
+
28
+ # --- MovieRecommendationSystem Class (from Cell C) ---
29
  class MovieRecommendationSystem:
30
  def __init__(self):
31
  self.movies_df = None
32
  self.similarity_matrix = None
33
  self.vectorizer = CountVectorizer(stop_words='english')
34
+ # Load API key from environment variable
35
+ self.API_KEY = os.getenv("OPENImbd")
36
  if not self.API_KEY:
37
+ print("🚨 WARNING: OMDB_API_KEY not found in environment variables.")
38
  self.BASE_URL = "http://www.omdbapi.com/"
39
  self.HEADERS = {}
40
 
41
  def fetch_movie_by_title(self, title):
42
+ """Fetch a single movie by title from OMDb API."""
43
  if not self.API_KEY:
44
  print("OMDb API key is not set. Cannot fetch movie.")
45
  return None
 
49
  "plot": "full"
50
  }
51
  try:
52
+ response = requests.get(self.BASE_URL, headers=self.HEADERS, params=params, timeout=10) # Added timeout
53
  if response.status_code == 200:
54
  data = response.json()
55
  if data.get("Response") == "True":
 
63
  print(f"Error fetching movie '{title}': {e}")
64
  return None
65
 
66
+ def fetch_movies(self, titles=None, limit=400):
67
+ """Fetch a list of movies, either from provided titles or a default list."""
68
  if titles is None:
69
  titles = [
70
  "Inception", "The Dark Knight", "Interstellar", "The Matrix", "Fight Club",
 
72
  "Avatar", "The Avengers", "Jurassic Park", "Star Wars", "The Lord of the Rings",
73
  "Harry Potter", "Pirates of the Caribbean", "The Godfather", "Back to the Future",
74
  "Indiana Jones", "The Lion King", "Toy Story", "Finding Nemo", "Up", "WALL-E",
75
+ "The Incredibles", "Coco", "Spider-Man", "Iron Man", "Captain America",
76
+ "Thor", "Black Panther", "Deadpool", "Logan", "X-Men", "Batman Begins",
77
+ "The Dark Knight Rises", "Man of Steel", "Wonder Woman", "Aquaman", "Parasite",
78
+ "Joker", "Once Upon a Time in Hollywood", "Avengers: Endgame", "Toy Story 4",
79
+ "Spider-Man: Into the Spider-Verse", "Green Book", "Bohemian Rhapsody",
80
+ "A Star Is Born", "The Irishman", "1917", "Ford v Ferrari", "Little Women",
81
+ "Marriage Story", "Knives Out", "Us", "Midsommar", "Parasite", "Joker",
82
+ "Once Upon a Time in Hollywood", "Avengers: Endgame", "Toy Story 4",
83
+ "Spider-Man: Into the Spider-Verse", "Green Book", "Bohemian Rhapsody",
84
+ "A Star Is Born", "The Irishman", "1917", "Ford v Ferrari", "Little Women",
85
+ "Marriage Story", "Knives Out", "Us", "Midsommar", "Get Out", "Dunkirk",
86
+ "La La Land", "Moonlight", "Arrival", "Hacksaw Ridge", "Hell or High Water",
87
+ "Manchester by the Sea", "Hidden Figures", "Lion", "Fences", "Deadpool",
88
+ "Logan", "Arrival", "Hell or High Water", "Manchester by the Sea", "Hidden Figures",
89
+ "Lion", "Fences", "Zootopia", "Moana", "Sing Street", "The Nice Guys",
90
+ "Captain America: Civil War", "Doctor Strange", "Fantastic Beasts and Where to Find Them",
91
+ "Rogue One: A Star Wars Story", "Arrival", "Hacksaw Ridge", "Hell or High Water",
92
+ "Manchester by the Sea", "Hidden Figures", "Lion", "Fences", "Zootopia",
93
+ "Moana", "Sing Street", "The Nice Guys", "Captain America: Civil War", "Doctor Strange",
94
+ "Fantastic Beasts and Where to Find Them", "Rogue One: A Star Wars Story", "Deadpool",
95
+ "Logan", "Arrival", "Hell or High Water", "Manchester by the Sea", "Hidden Figures",
96
+ "Lion", "Fences", "Zootopia", "Moana", "Sing Street", "The Nice Guys",
97
+ "Captain America: Civil War", "Doctor Strange", "Fantastic Beasts and Where to Find Them",
98
+ "Rogue One: A Star Wars Story", "The Martian", "Mad Max: Fury Road", "Inside Out",
99
+ "Spotlight", "The Revenant", "Room", "Brooklyn", "Carol", "Sicario",
100
+ "Straight Outta Compton", "The Big Short", "Bridge of Spies", "Ex Machina",
101
+ "The Hateful Eight", "Anomalisa", "Son of Saul", "The Lobster", "Amy",
102
+ "Cartel Land", "Winter on Fire: Ukraine's Fight for Freedom", "What Happened, Miss Simone?",
103
+ "Listen to Me Marlon", "The Look of Silence", "Shaun the Sheep Movie", "When Marnie Was There",
104
+ "Boy and the World", "Mustang", "Embrace of the Serpent", "Theeb", "A War",
105
+ "A Bigger Splash", "Florence Foster Jenkins", "Hail, Caesar!", "Julieta",
106
+ "Love & Friendship", "Maggie's Plan", "Miles Ahead", "Our Little Sister",
107
+ "The Lobster", "Amy", "Cartel Land", "Winter on Fire: Ukraine's Fight for Freedom",
108
+ "What Happened, Miss Simone?", "Listen to Me Marlon", "The Look of Silence",
109
+ "Shaun the Sheep Movie", "When Marnie Was There", "Boy and the World",
110
+ "Mustang", "Embrace of the Serpent", "Theeb", "A War", "A Bigger Splash",
111
+ "Florence Foster Jenkins", "Hail, Caesar!", "Julieta", "Love & Friendship",
112
+ "Maggie's Plan", "Miles Ahead", "Our Little Sister", "Paterson", "Sing Street",
113
+ "The Nice Guys", "Captain America: Civil War", "Doctor Strange",
114
+ "Fantastic Beasts and Where to Find Them", "Rogue One: A Star Wars Story",
115
+ "The Martian", "Mad Max: Fury Road", "Inside Out", "Spotlight", "The Revenant",
116
+ "Room", "Brooklyn", "Carol", "Sicario", "Straight Outta Compton",
117
+ "The Big Short", "Bridge of Spies", "Ex Machina", "The Hateful Eight",
118
+ "Anomalisa", "Son of Saul", "The Lobster", "Amy", "Cartel Land",
119
+ "Winter on Fire: Ukraine's Fight for Freedom", "What Happened, Miss Simone?",
120
+ "Listen to Me Marlon", "The Look of Silence", "Shaun the Sheep Movie",
121
+ "When Marnie Was There", "Boy and the World", "Mustang", "Embrace of the Serpent",
122
+ "Theeb", "A War", "A Bigger Splash", "Florence Foster Jenkins",
123
+ "Hail, Caesar!", "Julieta", "Love & Friendship", "Maggie's Plan",
124
+ "Miles Ahead", "Our Little Sister", "Paterson", "Sing Street", "The Nice Guys",
125
+ "Captain America: Civil War", "Doctor Strange",
126
+ "Fantastic Beasts and Where to Find Them", "Rogue One: A Star Wars Story",
127
+ "The Martian", "Mad Max: Fury Road", "Inside Out", "Spotlight", "The Revenant",
128
+ "Room", "Brooklyn", "Carol", "Sicario", "Straight Outta Compton",
129
+ "The Big Short", "Bridge of Spies", "Ex Machina", "The Hateful Eight",
130
+ "Anomalisa", "Son of Saul", "The Lobster", "Amy", "Cartel Land",
131
+ "Winter on Fire: Ukraine's Fight for Freedom", "What Happened, Miss Simone?",
132
+ "Listen to Me Marlon", "The Look of Silence", "Shaun the Sheep Movie",
133
+ "When Marnie Was There", "Boy and the World", "Mustang", "Embrace of the Serpent",
134
+ "Theeb", "A War", "A Bigger Splash", "Florence Foster Jenkins",
135
+ "Hail, Caesar!", "Julieta", "Love & Friendship", "Maggie's Plan",
136
+ "Miles Ahead", "Our Little Sister", "Paterson"
137
  ][:limit]
138
+
139
+
140
  movies = []
141
+ titles_to_fetch = titles[:limit] if limit is not None else titles
142
+
143
+ for title in titles_to_fetch:
144
  movie_data = self.fetch_movie_by_title(title)
145
  if movie_data:
146
  movies.append(movie_data)
147
+
148
  return movies
149
 
150
  def prepare_movie_data(self):
151
+ """Prepare movie data from OMDb API or fallback if API fetch fails."""
152
  movies = self.fetch_movies()
153
  if not movies:
154
  print("🚨 API returned no movies. Loading fallback dataset.")
 
181
  return self.movies_df
182
 
183
  def build_similarity_matrix(self):
184
+ """Build similarity matrix for recommendations based on combined features."""
185
  if self.movies_df is not None and not self.movies_df.empty:
186
  max_features = 5000
187
  self.vectorizer = CountVectorizer(stop_words='english', max_features=max_features)
 
190
  self.similarity_matrix = cosine_similarity(vectorized_features)
191
  print(f"βœ… Similarity matrix built with shape: {self.similarity_matrix.shape}")
192
  else:
193
+ print("🚨 Cannot build similarity matrix: movies_df is empty.")
194
+
195
 
196
  def get_recommendations(self, selected_movie_ids, num_recommendations=5):
197
+ """Get movie recommendations based on selected movie IDs."""
198
  if self.similarity_matrix is None or self.movies_df.empty:
199
  print("Debug: Similarity matrix or movies_df is empty.")
200
  return []
201
+
202
  selected_indices = self.movies_df[self.movies_df['id'].isin(selected_movie_ids)].index.tolist()
203
+
204
  if not selected_indices:
205
  print("Debug: No selected movies found in DataFrame for recommendations.")
206
  return []
207
+
208
  avg_similarity_scores = np.mean(self.similarity_matrix[selected_indices], axis=0)
209
+
210
  movie_indices = np.argsort(avg_similarity_scores)[::-1]
211
+
212
  recommendations = []
213
  for idx in movie_indices:
214
  movie = self.movies_df.iloc[idx]
215
+ # Ensure the recommended movie is not one of the selected movies
216
  if movie['id'] not in selected_movie_ids:
217
  recommendations.append(movie.to_dict())
218
  if len(recommendations) >= num_recommendations:
219
  break
220
+
221
  return recommendations
222
 
223
  # Initialize the recommender globally
224
  recommender = MovieRecommendationSystem()
225
 
226
+ # --- Flask Application (from Cell D, modified) ---
227
  app = Flask(__name__)
228
+ CORS(app) # Enable CORS
229
 
230
  @app.route('/')
231
  def index():
232
+ """Health check endpoint"""
233
  return jsonify({
234
  "message": "Netflix Clone API is running!",
235
  "status": "success",
 
238
 
239
  @app.route('/api/movies')
240
  def get_movies():
241
+ """Get all movies for display"""
242
  try:
243
  if recommender.movies_df is None or recommender.movies_df.empty:
244
  print("Preparing movie data...")
245
  recommender.prepare_movie_data()
246
  print(f"Loaded {len(recommender.movies_df)} movies")
247
+
248
  movies = recommender.movies_df.to_dict('records')
249
  return jsonify(movies)
250
+
251
  except Exception as e:
252
  print(f"Error in get_movies: {e}")
253
  return jsonify({'error': 'Failed to fetch movies'}), 500
254
 
255
  @app.route('/api/recommend', methods=['POST'])
256
  def recommend_movies():
257
+ """Get recommendations based on selected movies"""
258
  try:
259
  data = request.json
260
  selected_movie_ids = data.get('selected_movies', [])
261
+
262
  if len(selected_movie_ids) < 5:
263
  return jsonify({'error': 'Please select at least 5 movies'}), 400
264
+
265
  print(f"Getting recommendations for movies: {selected_movie_ids}")
266
  recommendations = recommender.get_recommendations(selected_movie_ids)
267
+
268
  return jsonify(recommendations)
269
+
270
  except Exception as e:
271
  print(f"Error in recommend_movies: {e}")
272
  return jsonify({'error': 'Failed to get recommendations'}), 500
273
 
274
  @app.route('/api/health')
275
  def health_check():
276
+ """Health check endpoint"""
277
  return jsonify({
278
  "status": "healthy",
279
  "movies_loaded": len(recommender.movies_df) if recommender.movies_df is not None else 0,
280
  "similarity_matrix_built": recommender.similarity_matrix is not None
281
  })
282
 
283
+ # Function to start Flask server (from Cell E, modified)
284
  def start_flask_server():
285
+ """Start Flask server in background"""
286
  try:
287
  print("πŸš€ Starting Flask backend server...")
288
+ # Run Flask app on port 5000, accessible locally within the Space
289
  app.run(host='127.0.0.1', port=5000, debug=False)
290
  except Exception as e:
291
  print(f"❌ Error starting Flask server: {e}")
292
 
293
+
294
+ # --- Gradio Application (from Cell 7P4A_qIhjvbT, modified) ---
295
+ # API_BASE_URL now points to the Flask app running locally within the Space
296
  API_BASE_URL = "http://127.0.0.1:5000"
297
+
298
  MAX_SELECTIONS = 10
299
  MIN_RECOMMENDATIONS = 5
300
 
301
  class CinemaCloneApp:
302
+ def __init__(self):
303
+ self.selected_movies = []
304
+ self.all_movies = []
305
+ self.recommendations = []
306
+
307
+ def sanitize_input(self, text: str) -> str:
308
+ """Sanitize user input to prevent XSS attacks"""
309
+ if not isinstance(text, str):
310
+ return ""
311
+ text = re.sub(r'<[^>]*>', '', text)
312
+ text = html.escape(text)
313
+ return text.strip()
314
+
315
+ def validate_movie_data(self, movie: Dict[str, Any]) -> bool:
316
+ """Validate movie data structure"""
317
+ required_fields = ['id', 'title']
318
+ return all(field in movie and movie[field] for field in required_fields)
319
+
320
+ def fetch_movies_from_backend(self) -> List[Dict[str, Any]]:
321
+ """Fetch movies from the Flask backend with comprehensive error handling"""
322
+ try:
323
+ response = requests.get(
324
+ f"{API_BASE_URL}/api/movies",
325
+ timeout=60, # Increased timeout
326
+ headers={'Accept': 'application/json'}
327
+ )
328
+
329
+ if response.status_code == 200:
330
+ content_type = response.headers.get('content-type', '')
331
+ if 'application/json' not in content_type:
332
+ # Attempt to read text response for debugging non-JSON errors
333
+ print(f"Warning: Received non-JSON response (status {response.status_code}). Content: {response.text[:500]}...") # Print first 500 chars
334
+ raise ValueError(f"Backend returned non-JSON response (Status: {response.status_code})")
335
+
336
+ movies = response.json()
337
+ if isinstance(movies, list) and len(movies) > 0:
338
+ validated_movies = []
339
+ for movie in movies:
340
+ if self.validate_movie_data(movie):
341
+ movie['title'] = self.sanitize_input(movie.get('title', ''))
342
+ movie['overview'] = self.sanitize_input(movie.get('overview', ''))
343
+ movie['genres'] = self.sanitize_input(movie.get('genres', ''))
344
+ movie['cast'] = self.sanitize_input(movie.get('cast', '')) # Sanitize cast as well
345
+ validated_movies.append(movie)
346
+
347
+ self.all_movies = validated_movies
348
+ print(f"Successfully fetched and validated {len(validated_movies)} movies from backend.")
349
+ return validated_movies
350
+ elif isinstance(movies, list) and len(movies) == 0:
351
+ print("Backend returned an empty movie list.")
352
+ return self.get_fallback_movies()
353
+ else:
354
+ print(f"Backend returned unexpected data format: {movies}")
355
+ raise ValueError("Invalid movie data structure from backend")
356
+ else:
357
+ try:
358
+ error_response = response.json()
359
+ print(f"Backend error response (Status {response.status_code}): {error_response}")
360
+ except json.JSONDecodeError:
361
+ print(f"Backend non-JSON error response (Status {response.status_code}) from recommendations endpoint: {response.text[:500]}...")
362
+ raise requests.RequestException(f"Backend request failed with status: {response.status_code}")
363
+
364
+ except requests.exceptions.Timeout:
365
+ print(f"Timeout fetching movies from backend at {API_BASE_URL}/api/movies")
366
+ return self.get_fallback_movies()
367
+ except requests.exceptions.ConnectionError as ce:
368
+ print(f"Connection error fetching movies from backend at {API_BASE_URL}/api/movies: {ce}")
369
+ print("Ensure the Flask backend is running and accessible at http://127.0.0.1:5000.")
370
+ return self.get_fallback_movies()
371
+ except Exception as e:
372
+ print(f"An unexpected error occurred fetching movies from backend: {e}")
373
+ return self.get_fallback_movies()
374
+
375
+ def get_recommendations_from_backend(self, selected_ids: List[str]) -> List[Dict[str, Any]]:
376
+ """Get recommendations from Flask backend with security validation"""
377
+ try:
378
+ if not selected_ids or not isinstance(selected_ids, list):
379
+ raise ValueError("Invalid selected movie IDs")
380
+
381
+ sanitized_ids = [self.sanitize_input(str(id_)) for id_ in selected_ids if id_]
382
+
383
+ response = requests.post(
384
+ f"{API_BASE_URL}/api/recommend",
385
+ json={"selected_movies": sanitized_ids},
386
+ headers={'Content-Type': 'application/json', 'Accept': 'application/json'},
387
+ timeout=30
388
+ )
389
+
390
+ if response.status_code == 200:
391
+ content_type = response.headers.get('content-type', '')
392
+ if 'application/json' not in content_type:
393
+ print(f"Warning: Received non-JSON response (status {response.status_code}) from recommendations endpoint. Content: {response.text[:500]}...")
394
+ raise ValueError(f"Backend returned non-JSON response (Status: {response.status_code}) from recommendations endpoint")
395
+
396
+ recommendations = response.json()
397
+ if isinstance(recommendations, list):
398
+ validated_recs = []
399
+ for rec in recommendations:
400
+ if self.validate_movie_data(rec):
401
+ rec['title'] = self.sanitize_input(rec.get('title', ''))
402
+ rec['overview'] = self.sanitize_input(rec.get('overview', ''))
403
+ rec['genres'] = self.sanitize_input(rec.get('genres', ''))
404
+ rec['cast'] = self.sanitize_input(rec.get('cast', '')) # Sanitize cast as well
405
+ validated_recs.append(rec)
406
+ print(f"Successfully received and validated {len(validated_recs)} recommendations.")
407
+ return validated_recs
408
+ else:
409
+ print(f"Backend returned unexpected data format for recommendations: {recommendations}")
410
+ raise ValueError("Invalid recommendations data structure from backend")
411
+ else:
412
+ try:
413
+ error_response = response.json()
414
+ print(f"Backend error response (Status {response.status_code}) from recommendations endpoint: {error_response}")
415
+ except json.JSONDecodeError:
416
+ print(f"Backend non-JSON error response (Status {response.status_code}) from recommendations endpoint: {response.text[:500]}...")
417
+ raise requests.RequestException(f"Backend recommendation request failed with status: {response.status_code}")
418
+
419
+ except requests.exceptions.Timeout:
420
+ print(f"Timeout getting recommendations from backend at {API_BASE_URL}/api/recommend")
421
+ return []
422
+ except requests.exceptions.ConnectionError as ce:
423
+ print(f"Connection error getting recommendations from backend at {API_BASE_URL}/api/recommend: {ce}")
424
+ print("Ensure the Flask backend is running and accessible at http://127.0.0.1:5000.")
425
+ return []
426
+ except Exception as e:
427
+ print(f"An unexpected error occurred getting recommendations: {e}")
428
+ return []
429
+
430
+ def create_movie_card_html(self, movie: Dict[str, Any], is_selected: bool = False, is_recommendation: bool = False) -> str:
431
+ """Create HTML for a movie card with React-inspired styling and animations"""
432
+ # Ensure all fields are present with default empty strings to avoid KeyError
433
+ title = html.escape(movie.get('title', 'Unknown'))
434
+ overview = html.escape(movie.get('overview', '')[:200] + "..." if len(movie.get('overview', '')) > 200 else movie.get('overview', ''))
435
+ genres = html.escape(movie.get('genres', ''))
436
+ cast = html.escape(movie.get('cast', '')[:150] + "..." if len(movie.get('cast', '')) > 150 else movie.get('cast', ''))
437
+ rating = float(movie.get('vote_average', 0))
438
+ year = html.escape(str(movie.get('release_date', '')))
439
+ movie_id = html.escape(str(movie.get('id', ''))) # Ensure ID is also sanitized and present
440
+
441
+ poster_url = movie.get('poster_path', '')
442
+ if not poster_url or not poster_url.startswith(('http://', 'https://')):
443
+ poster_url = 'https://via.placeholder.com/300x450/1a1a1a/fff?text=No+Image'
444
+
445
+ selected_class = "selected" if is_selected else ""
446
+ rec_class = "recommendation" if is_recommendation else ""
447
+ selection_indicator = "βœ“" if is_selected else "+"
448
+
449
+ genre_list = genres.split(', ') if genres else []
450
+ genre_tags_html = ""
451
+ for genre in genre_list[:3]:
452
+ genre_tags_html += f'<span class="genre-tag">{html.escape(genre.strip())}</span>' # Sanitize genre tags
453
+
454
+ # Use data-movie-id for JavaScript interaction
455
+ return f"""
456
+ <div class="movie-card {selected_class} {rec_class}" data-movie-id="{movie_id}" onclick="selectMovieByTitle('{title}')">
457
+ <div class="movie-poster-container">
458
+ <img src="{html.escape(poster_url)}"
459
+ alt="{title}"
460
+ class="movie-poster"
461
+ onerror="this.src='https://via.placeholder.com/300x450/1a1a1a/fff?text=No+Image'">
462
+ <div class="movie-overlay">
463
+ <div class="action-buttons">
464
+ <!-- Add your action buttons here if needed -->
465
+ </div>
466
+ </div>
467
+ <div class="selection-indicator">{selection_indicator}</div>
468
+ </div>
469
+ <div class="movie-info">
470
+ <h3 class="movie-title">{title}</h3>
471
+ <div class="movie-meta">
472
+ <div class="movie-rating">
473
+ <span class="star">⭐</span>
474
+ <span class="rating-value">{rating:.1f}</span>
475
+ </div>
476
+ <div class="movie-year">{year}</div>
477
+ </div>
478
+ <div class="genre-tags">
479
+ {genre_tags_html}
480
+ </div>
481
+ <div class="movie-cast">
482
+ <strong>Cast:</strong> {cast}
483
+ </div>
484
+ <div class="movie-overview">{overview}</div>
485
+ </div>
486
+ </div>
487
+ """
488
+
489
+ def create_movies_grid_html(self, movies: List[Dict[str, Any]], is_recommendation: bool = False) -> str:
490
+ """Create HTML grid of movie cards with React-inspired layout"""
491
+ if not movies:
492
+ return f"""
493
+ <div class="no-movies">
494
+ <div class="no-movies-icon">🎬</div>
495
+ <h3>No {'recommendations' if is_recommendation else 'movies'} available</h3>
496
+ <p>{'Select more movies to get better recommendations' if is_recommendation else 'Click Load Movies to start exploring'}</p>
497
+ </div>
498
+ """
499
+
500
+ cards_html = ""
501
+ for movie in movies[:500]: # Limit for performance, can be adjusted
502
+ # Find the full movie object from self.all_movies to check selection status
503
+ full_movie_data = next((item for item in self.all_movies if item.get('id') == movie.get('id')), None)
504
+ is_selected = full_movie_data and full_movie_data.get('id') in self.selected_movies
505
+ cards_html += self.create_movie_card_html(movie, is_selected, is_recommendation)
506
+
507
+
508
+ grid_class = "recommendations-grid" if is_recommendation else "movies-grid"
509
+
510
+ return f"""
511
+ <div class="{grid_class}">
512
+ {cards_html}
513
+ </div>
514
+ """
515
 
516
  # Initialize the app instance globally
517
  gradio_app_instance = CinemaCloneApp()
518
 
519
+ # Enhanced CSS with React-inspired styling and animations
520
+ cinema_css = """
521
+ <style>
522
+ @import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap');
523
+
524
+ * {
525
+ box-sizing: border-box;
526
+ }
527
+
528
+ .gradio-container {
529
+ background: linear-gradient(135deg, #0a0a0a 0%, #1a1a1a 50%, #0f0f0f 100%);
530
+ color: white;
531
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
532
+ min-height: 100vh;
533
+ }
534
+
535
+ .cinema-header {
536
+ text-align: center;
537
+ padding: 40px 20px;
538
+ background: linear-gradient(135deg, #e50914 0%, #ff6b6b 50%, #8b5cf6 100%);
539
+ -webkit-background-clip: text;
540
+ -webkit-text-fill-color: transparent;
541
+ background-clip: text;
542
+ font-size: clamp(2.5rem, 5vw, 4rem);
543
+ font-weight: 900;
544
+ letter-spacing: -3px;
545
+ margin-bottom: 20px;
546
+ text-shadow: 0 0 30px rgba(229, 9, 20, 0.3);
547
+ }
548
+
549
+ .subtitle {
550
+ font-size: 1.2rem;
551
+ opacity: 0.8;
552
+ margin-bottom: 40px;
553
+ font-weight: 400;
554
+ }
555
+
556
+ .selection-counter {
557
+ background: linear-gradient(135deg, #e50914 0%, #ff6b6b 100%);
558
+ padding: 20px 30px;
559
+ border-radius: 50px;
560
+ text-align: center;
561
+ font-weight: 700;
562
+ margin: 30px auto;
563
+ max-width: 400px;
564
+ box-shadow: 0 15px 35px rgba(229, 9, 20, 0.4);
565
+ backdrop-filter: blur(20px);
566
+ border: 1px solid rgba(255, 255, 255, 0.1);
567
+ font-size: 1.1rem;
568
+ }
569
+
570
+ .movies-grid, .recommendations-grid {
571
+ display: grid;
572
+ grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
573
+ gap: 30px;
574
+ padding: 30px;
575
+ max-height: 800px;
576
+ overflow-y: auto;
577
+ scrollbar-width: thin;
578
+ scrollbar-color: #e50914 #1a1a1a;
579
+ }
580
+
581
+ .movies-grid::-webkit-scrollbar, .recommendations-grid::-webkit-scrollbar {
582
+ width: 8px;
583
+ }
584
+
585
+ .movies-grid::-webkit-scrollbar-track, .recommendations-grid::-webkit-scrollbar-track {
586
+ background: #1a1a1a;
587
+ border-radius: 4px;
588
+ }
589
+
590
+ .movies-grid::-webkit-scrollbar-thumb, .recommendations-grid::-webkit-scrollbar-thumb {
591
+ background: linear-gradient(135deg, #e50914, #ff6b6b);
592
+ border-radius: 4px;
593
+ }
594
+
595
+ .movie-card {
596
+ position: relative;
597
+ border-radius: 20px;
598
+ overflow: hidden;
599
+ background: linear-gradient(145deg, #1e1e1e, #2a2a2a);
600
+ box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
601
+ transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
602
+ cursor: pointer;
603
+ border: 2px solid transparent;
604
+ backdrop-filter: blur(10px);
605
+ }
606
+
607
+ .movie-card:hover {
608
+ transform: scale(1.05) translateY(-15px);
609
+ box-shadow: 0 25px 50px rgba(229, 9, 20, 0.4);
610
+ border-color: rgba(229, 9, 20, 0.5);
611
+ }
612
+
613
+ .movie-card.selected {
614
+ border-color: #e50914;
615
+ box-shadow: 0 0 30px rgba(229, 9, 20, 0.6);
616
+ transform: scale(1.02);
617
+ }
618
+
619
+ .movie-card.recommendation {
620
+ background: linear-gradient(145deg, #2a1a2a, #3a2a3a);
621
+ border-color: rgba(139, 92, 246, 0.5);
622
+ }
623
+
624
+ .movie-card.recommendation:hover {
625
+ box-shadow: 0 25px 50px rgba(139, 92, 246, 0.4);
626
+ border-color: #8b5cf6;
627
+ }
628
+
629
+ .movie-poster-container {
630
+ position: relative;
631
+ width: 100%;
632
+ height: 400px;
633
+ overflow: hidden;
634
+ }
635
+
636
+ .movie-poster {
637
+ width: 100%;
638
+ height: 100%;
639
+ object-fit: cover;
640
+ transition: transform 0.4s ease;
641
+ }
642
+
643
+ .movie-card:hover .movie-poster {
644
+ transform: scale(1.1);
645
+ }
646
+
647
+ .movie-overlay {
648
+ position: absolute;
649
+ top: 0;
650
+ left: 0;
651
+ right: 0;
652
+ bottom: 0;
653
+ background: linear-gradient(
654
+ to bottom,
655
+ transparent 0%,
656
+ transparent 40%,
657
+ rgba(0, 0, 0, 0.7) 70%,
658
+ rgba(0, 0, 0, 0.9) 100%
659
+ );
660
+ display: flex;
661
+ align-items: flex-end;
662
+ justify-content: center;
663
+ padding: 20px;
664
+ opacity: 0;
665
+ transition: opacity 0.3s ease;
666
+ }
667
+
668
+ .movie-card:hover .movie-overlay {
669
+ opacity: 1;
670
+ }
671
+
672
+ .action-buttons {
673
+ display: flex;
674
+ gap: 12px;
675
+ transform: translateY(20px);
676
+ transition: transform 0.3s ease;
677
+ }
678
+
679
+ .movie-card:hover .action-buttons {
680
+ transform: translateY(0);
681
+ }
682
+
683
+ .action-btn {
684
+ width: 45px;
685
+ height: 45px;
686
+ border-radius: 50%;
687
+ border: 2px solid rgba(255, 255, 255, 0.3);
688
+ background: rgba(255, 255, 255, 0.1);
689
+ color: white;
690
+ display: flex;
691
+ align-items: center;
692
+ justify-content: center;
693
+ cursor: pointer;
694
+ transition: all 0.3s ease;
695
+ backdrop-filter: blur(10px);
696
+ }
697
+
698
+ .action-btn.primary {
699
+ background: linear-gradient(135deg, #e50914, #ff6b6b);
700
+ border-color: #e50914;
701
+ }
702
+
703
+ .action-btn:hover {
704
+ transform: scale(1.1);
705
+ background: rgba(255, 255, 255, 0.2);
706
+ }
707
+
708
+ .action-btn.primary:hover {
709
+ background: linear-gradient(135deg, #ff1a25, #ff7b7b);
710
+ }
711
+
712
+ .selection-indicator {
713
+ position: absolute;
714
+ top: 15px;
715
+ right: 15px;
716
+ width: 35px;
717
+ height: 35px;
718
+ border-radius: 50%;
719
+ background: rgba(229, 9, 20, 0.9);
720
+ display: flex;
721
+ align-items: center;
722
+ justify-content: center;
723
+ color: white;
724
+ font-weight: bold;
725
+ font-size: 18px;
726
+ backdrop-filter: blur(10px);
727
+ border: 2px solid rgba(255, 255, 255, 0.2);
728
+ transition: all 0.3s ease;
729
+ }
730
+
731
+ .movie-card.selected .selection-indicator {
732
+ background: linear-gradient(135deg, #e50914, #ff6b6b);
733
+ transform: scale(1.1);
734
+ }
735
+
736
+ .movie-info {
737
+ padding: 25px;
738
+ background: linear-gradient(135deg, #1a1a1a, #2a2a2a);
739
+ }
740
+
741
+ .movie-title {
742
+ font-size: 1.3rem;
743
+ font-weight: 700;
744
+ margin-bottom: 12px;
745
+ color: white;
746
+ line-height: 1.3;
747
+ display: -webkit-box;
748
+ -webkit-line-clamp: 2;
749
+ -webkit-box-orient: vertical;
750
+ overflow: hidden;
751
+ }
752
+
753
+ .movie-meta {
754
+ display: flex;
755
+ justify-content: space-between;
756
+ align-items: center;
757
+ margin-bottom: 15px;
758
+ }
759
+
760
+ .movie-rating {
761
+ display: flex;
762
+ align-items: center;
763
+ gap: 8px;
764
+ font-weight: 600;
765
+ }
766
+
767
+ .star {
768
+ font-size: 1.2rem;
769
+ }
770
 
771
+ .rating-value {
772
+ color: #ffd700;
773
+ font-size: 1rem;
774
+ }
775
+
776
+ .movie-year {
777
+ color: #999;
778
+ font-size: 0.9rem;
779
+ font-weight: 500;
780
+ background: rgba(255, 255, 255, 0.1);
781
+ padding: 4px 12px;
782
+ border-radius: 20px;
783
+ }
784
+
785
+ .genre-tags {
786
+ display: flex;
787
+ gap: 8px;
788
+ flex-wrap: wrap;
789
+ margin-bottom: 15px;
790
+ }
791
+
792
+ .genre-tag {
793
+ background: linear-gradient(135deg, #e50914, #ff6b6b);
794
+ padding: 4px 12px;
795
+ border-radius: 20px;
796
+ font-size: 0.75rem;
797
+ font-weight: 600;
798
+ color: white;
799
+ border: 1px solid rgba(255, 255, 255, 0.1);
800
+ }
801
+
802
+ .movie-card.recommendation .genre-tag {
803
+ background: linear-gradient(135deg, #8b5cf6, #a78bfa);
804
+ }
805
+
806
+ .movie-cast {
807
+ color: #ccc;
808
+ font-size: 0.85rem;
809
+ margin-bottom: 12px;
810
+ line-height: 1.4;
811
+ }
812
+
813
+ .movie-cast strong {
814
+ color: #e50914;
815
+ font-weight: 600;
816
+ }
817
+
818
+ .movie-overview {
819
+ color: #ddd;
820
+ font-size: 0.8rem;
821
+ line-height: 1.5;
822
+ display: -webkit-box;
823
+ -webkit-line-clamp: 4;
824
+ -webkit-box-orient: vertical;
825
+ overflow: hidden;
826
+ }
827
+
828
+ .no-movies {
829
+ text-align: center;
830
+ color: #ccc;
831
+ padding: 80px 40px;
832
+ background: rgba(255, 255, 255, 0.02);
833
+ border-radius: 20px;
834
+ margin: 40px;
835
+ border: 2px dashed rgba(255, 255, 255, 0.1);
836
+ }
837
+
838
+ .no-movies-icon {
839
+ font-size: 4rem;
840
+ margin-bottom: 20px;
841
+ opacity: 0.5;
842
+ }
843
+
844
+ .no-movies h3 {
845
+ font-size: 1.5rem;
846
+ margin-bottom: 10px;
847
+ color: white;
848
+ }
849
+
850
+ .no-movies p {
851
+ font-size: 1rem;
852
+ opacity: 0.7;
853
+ }
854
+
855
+ .recommendations-section {
856
+ margin-top: 60px;
857
+ padding: 40px;
858
+ background: linear-gradient(135deg, rgba(139, 92, 246, 0.1), rgba(229, 9, 20, 0.1));
859
+ border-radius: 30px;
860
+ border: 1px solid rgba(139, 92, 246, 0.2);
861
+ backdrop-filter: blur(20px);
862
+ }
863
+
864
+ .section-title {
865
+ font-size: 2.5rem;
866
+ font-weight: 800;
867
+ margin-bottom: 30px;
868
+ background: linear-gradient(135deg, #8b5cf6, #e50914);
869
+ -webkit-background-clip: text;
870
+ -webkit-text-fill-color: transparent;
871
+ background-clip: text;
872
+ text-align: center;
873
+ }
874
+
875
+ .error-message {
876
+ background: linear-gradient(135deg, rgba(229, 9, 20, 0.2), rgba(255, 107, 107, 0.1));
877
+ color: #ff6b6b;
878
+ padding: 20px;
879
+ border-radius: 15px;
880
+ text-align: center;
881
+ margin: 20px 0;
882
+ border: 1px solid rgba(229, 9, 20, 0.3);
883
+ backdrop-filter: blur(10px);
884
+ }
885
+
886
+ .success-message {
887
+ background: linear-gradient(135deg, rgba(76, 175, 80, 0.2), rgba(139, 195, 74, 0.1));
888
+ color: #4caf50;
889
+ padding: 20px;
890
+ border-radius: 15px;
891
+ text-align: center;
892
+ margin: 20px 0;
893
+ border: 1px solid rgba(76, 175, 80, 0.3);
894
+ backdrop-filter: blur(10px);
895
+ }
896
+
897
+ /* Button Styling */
898
+ .gr-button {
899
+ background: linear-gradient(135deg, #e50914, #ff6b6b) !important;
900
+ border: none !important;
901
+ color: white !important;
902
+ font-weight: 700 !important;
903
+ border-radius: 25px !important;
904
+ padding: 15px 30px !important;
905
+ transition: all 0.3s ease !important;
906
+ box-shadow: 0 10px 25px rgba(229, 9, 20, 0.3) !important;
907
+ }
908
+
909
+ .gr-button:hover {
910
+ transform: translateY(-3px) !important;
911
+ box-shadow: 0 15px 35px rgba(229, 9, 20, 0.5) !important;
912
+ background: linear-gradient(135deg, #ff1a25, #ff7b7b) !important;
913
+ }
914
+
915
+ .gr-dropdown {
916
+ background: rgba(255, 255, 255, 0.1) !important;
917
+ border: 1px solid rgba(229, 9, 20, 0.3) !important;
918
+ color: white !important;
919
+ border-radius: 15px !important;
920
+ backdrop-filter: blur(10px) !important;
921
+ }
922
+
923
+ /* Responsive Design */
924
+ @media (max-width: 768px) {
925
+ .movies-grid, .recommendations-grid {
926
+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
927
+ gap: 20px;
928
+ padding: 20px;
929
+ }
930
+
931
+ .cinema-header {
932
+ font-size: 2.5rem;
933
+ padding: 30px 15px;
934
+ }
935
+
936
+ .movie-card {
937
+ border-radius: 15px;
938
+ }
939
+
940
+ .movie-poster-container {
941
+ height: 350px;
942
+ }
943
+ }
944
+
945
+ /* Animation Keyframes */
946
+ @keyframes fadeInUp {
947
+ from {
948
+ opacity: 0;
949
+ transform: translateY(30px);
950
+ }
951
+ to {
952
+ opacity: 1;
953
+ transform: translateY(0);
954
+ }
955
+ }
956
+
957
+ .movie-card {
958
+ animation: fadeInUp 0.6s ease-out;
959
+ }
960
+
961
+ .movie-card:nth-child(even) {
962
+ animation-delay: 0.1s;
963
+ }
964
+
965
+ .movie-card:nth-child(3n) {
966
+ animation-delay: 0.2s;
967
+ }
968
+ </style>
969
+
970
+ <script>
971
+ // This script is needed for the Gradio component to interact with the HTML cards
972
+ // It triggers the Gradio 'select_btn' click event with the movie title
973
+ function selectMovieByTitle(title) {
974
+ // Find the Gradio Dropdown element by its label or other identifier
975
+ // This might need adjustment based on Gradio's internal structure
976
+ const dropdown = document.querySelector('.gr-dropdown label').parentElement.querySelector('select');
977
+ if (dropdown) {
978
+ // Set the value of the dropdown to the clicked movie title
979
+ dropdown.value = title;
980
+
981
+ // Find the 'Add/Remove Selection' button
982
+ const selectButton = document.querySelector('button.gr-button').nextElementSibling; // Assuming it's the button after Load
983
+
984
+ // Find the select button more reliably
985
+ const buttons = document.querySelectorAll('button.gr-button');
986
+ let selectButtonElement = null;
987
+ for (const btn of buttons) {
988
+ if (btn.textContent.includes('Add/Remove Selection')) { // Match button text
989
+ selectButtonElement = btn;
990
+ break;
991
+ }
992
+ }
993
+
994
+ if (selectButtonElement) {
995
+ // Trigger a click event on the select button
996
+ selectButtonElement.click();
997
+ console.log('Triggered select button for:', title);
998
+ } else {
999
+ console.error("Could not find the 'Add/Remove Selection' button.");
1000
+ }
1001
+ } else {
1002
+ console.error("Could not find the movie dropdown element.");
1003
+ }
1004
+ }
1005
+ </script>
1006
+ """
1007
+
1008
+ def load_movies():
1009
+ """Load movies from backend with enhanced UI feedback"""
1010
+ try:
1011
+ movies = gradio_app_instance.fetch_movies_from_backend()
1012
+ movies_html = gradio_app_instance.create_movies_grid_html(movies, is_recommendation=False)
1013
+ status = f"<div class='success-message'>✨ Successfully loaded {len(movies)} amazing movies!</div>"
1014
+
1015
+ movie_choices = ["🎬 Select a movie"] + [movie['title'] for movie in movies if movie.get('title')]
1016
+ # Clear selected movies on load
1017
+ gradio_app_instance.selected_movies = []
1018
+ selection_counter_html = f"<div class='selection-counter'>Selected: {len(gradio_app_instance.selected_movies)}/{MAX_SELECTIONS}</div>"
1019
+
1020
+
1021
+ return movies_html, status_display, gr.update(visible=False), gr.update(choices=movie_choices, value="🎬 Select a movie"), "", selection_counter_html
1022
+
1023
+ except Exception as e:
1024
+ error_msg = f"<div class='error-message'>❌ Oops! Failed to load movies: {str(e)}</div>"
1025
+ return "<div class='error-message'>Failed to load movies. Please try again.</div>", error_msg, gr.update(visible=False), gr.update(choices=["🎬 Select a movie"], value="🎬 Select a movie"), "", "<div class='selection-counter'>Selected: 0/10</div>"
1026
+
1027
+
1028
+ def toggle_movie_selection(movie_title: str):
1029
+ """Toggle movie selection with enhanced feedback"""
1030
+ movie_title = gradio_app_instance.sanitize_input(movie_title)
1031
+
1032
+ if not movie_title or movie_title == "🎬 Select a movie":
1033
+ return gr.update(), "<div class='error-message'>Please select a movie first! 🎬</div>", gr.update(visible=False), f"<div class='selection-counter'>Selected: {len(gradio_app_instance.selected_movies)}/{MAX_SELECTIONS}</div>"
1034
+
1035
+ selected_movie = None
1036
+ for movie in gradio_app_instance.all_movies:
1037
+ if movie.get('title') == movie_title:
1038
+ selected_movie = movie
1039
+ break
1040
+
1041
+ if not selected_movie:
1042
+ return gr.update(), "<div class='error-message'>❌ Movie not found in our collection</div>", gr.update(visible=False), f"<div class='selection-counter'>Selected: {len(gradio_app_instance.selected_movies)}/{MAX_SELECTIONS}</div>"
1043
+
1044
+ movie_id = selected_movie['id']
1045
+
1046
+ if movie_id in gradio_app_instance.selected_movies:
1047
+ gradio_app_instance.selected_movies.remove(movie_id)
1048
+ action = "removed from"
1049
+ emoji = "βž–"
1050
+ else:
1051
+ if len(gradio_app_instance.selected_movies) >= MAX_SELECTIONS:
1052
+ return gr.update(), f"<div class='error-message'>🚫 Maximum {MAX_SELECTIONS} movies can be selected</div>", gr.update(visible=False), f"<div class='selection-counter'>Selected: {len(gradio_app_instance.selected_movies)}/{MAX_SELECTIONS}</div>"
1053
+ gradio_app_instance.selected_movies.append(movie_id)
1054
+ action = "added to"
1055
+ emoji = "βž•"
1056
+
1057
+ # Re-render the movies grid to update selection indicators
1058
+ movies_html = gradio_app_instance.create_movies_grid_html(gradio_app_instance.all_movies, is_recommendation=False)
1059
+
1060
+ status = f"<div class='success-message'>{emoji} '{movie_title}' {action} your collection</div>"
1061
+ selection_counter_html = f"<div class='selection-counter'>Selected: {len(gradio_app_instance.selected_movies)}/{MAX_SELECTIONS}</div>"
1062
+ show_rec_btn = len(gradio_app_instance.selected_movies) >= MIN_RECOMMENDATIONS
1063
+
1064
+ return movies_html, status_display, gr.update(visible=show_rec_btn), selection_counter_html
1065
+
1066
+
1067
+ def get_recommendations():
1068
+ """Get movie recommendations with beautiful presentation"""
1069
+ if len(gradio_app_instance.selected_movies) < MIN_RECOMMENDATIONS:
1070
+ return gr.update(), f"<div class='error-message'>🎯 Please select at least {MIN_RECOMMENDATIONS} movies to get personalized recommendations</div>", gr.update(visible=False)
1071
+
1072
+ try:
1073
+ recommendations = gradio_app_instance.get_recommendations_from_backend(gradio_app_instance.selected_movies)
1074
+
1075
+ if not recommendations:
1076
+ return gr.update(), "<div class='error-message'>πŸ€” No recommendations found. Try selecting different movies!</div>", gr.update(visible=False)
1077
+
1078
+ rec_html = f"""
1079
+ <div class="recommendations-section">
1080
+ <div class="section-title">🎯 Curated Just For You</div>
1081
+ {gradio_app_instance.create_movies_grid_html(recommendations, is_recommendation=True)}
1082
+ </div>
1083
+ """
1084
+
1085
+ status = f"<div class='success-message'>🌟 Found {len(recommendations)} perfect recommendations based on your {len(gradio_app_instance.selected_movies)} selections!</div>"
1086
+
1087
+ return rec_html, status_display, gr.update(visible=True)
1088
+
1089
+ except Exception as e:
1090
+ error_msg = f"<div class='error-message'>❌ Error getting recommendations: {str(e)}</div>"
1091
+ return gr.update(), error_msg, gr.update(visible=False)
1092
+
1093
+ def clear_selections():
1094
+ """Clear all selections with confirmation"""
1095
+ gradio_app_instance.selected_movies.clear()
1096
+ # Re-render the movies grid to clear selection indicators
1097
+ movies_html = gradio_app_instance.create_movies_grid_html(gradio_app_instance.all_movies, is_recommendation=False)
1098
+ selection_counter_html = f"<div class='selection-counter'>Selected: {len(gradio_app_instance.selected_movies)}/{MAX_SELECTIONS}</div>"
1099
+
1100
+ return movies_html, "<div class='success-message'>πŸ”„ All selections cleared! Start fresh with new choices</div>", gr.update(visible=False), gr.update(visible=False), gr.update(value="🎬 Select a movie"), "", selection_counter_html
1101
+
1102
+ def search_movies(query: str):
1103
+ """Search movies by title and update the grid"""
1104
+ query = gradio_app_instance.sanitize_input(query).lower()
1105
+ if not query:
1106
+ # If search query is empty, display all movies
1107
+ return gradio_app_instance.create_movies_grid_html(gradio_app_instance.all_movies, is_recommendation=False)
1108
+ else:
1109
+ # Filter movies based on the query
1110
+ filtered_movies = [
1111
+ movie for movie in gradio_app_instance.all_movies
1112
+ if query in movie.get('title', '').lower()
1113
+ ]
1114
+ return gradio_app_instance.create_movies_grid_html(filtered_movies, is_recommendation=False)
1115
+
1116
+
1117
+ # Create the stunning Gradio interface
1118
+ with gr.Blocks(css=cinema_css, title="CinemaAI - Movie Recommendations", theme=gr.themes.Default()) as demo:
1119
+ gr.HTML("""
1120
+ <div class="cinema-header">
1121
+ 🎬 CINEMA AI
1122
+ </div>
1123
+ <div style="text-align: center; margin-bottom: 40px;">
1124
+ <h2 class="subtitle">Discover Your Next Cinematic Adventure</h2>
1125
+ <p style="opacity: 0.7; font-size: 1.1rem;">Select your favorite movies and let our AI curate personalized recommendations just for you</p>
1126
+ </div>
1127
+ """)
1128
+
1129
+ with gr.Row():
1130
+ with gr.Column(scale=3):
1131
+ load_btn = gr.Button("🎬 Load Movie Collection", variant="primary", size="lg")
1132
+ with gr.Column(scale=2):
1133
+ clear_btn = gr.Button("πŸ”„ Clear All Selections", variant="secondary")
1134
+
1135
+ selection_counter_display = gr.HTML("<div class='selection-counter'>Selected: 0/10</div>")
1136
+ status_display = gr.HTML("<div class='selection-counter'>🎭 Click 'Load Movie Collection' to begin your journey</div>")
1137
+
1138
+
1139
+ with gr.Row():
1140
+ movie_dropdown = gr.Dropdown(
1141
+ choices=["🎬 Select a movie"],
1142
+ label="🎯 Choose Your Favorite Movie",
1143
+ value="🎬 Select a movie",
1144
+ interactive=True
1145
+ )
1146
+ select_btn = gr.Button("✨ Add/Remove Selection", variant="secondary")
1147
+
1148
+ search_bar = gr.Textbox(label="πŸ” Search for a movie by title", placeholder="e.g., Inception", interactive=True)
1149
+
1150
+
1151
+ movies_display = gr.HTML("<div class='no-movies'><div class='no-movies-icon'>🎬</div><h3>Your Movie Collection Awaits</h3><p>Load movies to start exploring amazing cinema</p></div>")
1152
+
1153
+ rec_btn = gr.Button("🎯 Get My Personal Recommendations", variant="primary", size="lg", visible=False)
1154
+ recommendations_display = gr.HTML("", visible=False)
1155
+
1156
+ # Event handlers
1157
+ load_btn.click(
1158
+ fn=load_movies,
1159
+ outputs=[movies_display, status_display, recommendations_display, movie_dropdown, search_bar, selection_counter_display]
1160
+ )
1161
+
1162
+ select_btn.click(
1163
+ fn=toggle_movie_selection,
1164
+ inputs=[movie_dropdown],
1165
+ outputs=[movies_display, status_display, rec_btn, selection_counter_display]
1166
+ )
1167
+
1168
+ rec_btn.click(
1169
+ fn=get_recommendations,
1170
+ outputs=[recommendations_display, status_display, recommendations_display]
1171
+ )
1172
+
1173
+ clear_btn.click(
1174
+ fn=clear_selections,
1175
+ outputs=[movies_display, status_display, rec_btn, recommendations_display, movie_dropdown, search_bar, selection_counter_display]
1176
+ )
1177
+
1178
+ search_bar.change(
1179
+ fn=search_movies,
1180
+ inputs=[search_bar],
1181
+ outputs=[movies_display]
1182
+ )
1183
+
1184
+ # --- Main execution block ---
1185
  if __name__ == "__main__":
1186
+ load_dotenv() # Load environment variables from .env file
1187
+
1188
  # Start Flask server in a separate thread
1189
  flask_thread = threading.Thread(target=start_flask_server)
1190
  flask_thread.daemon = True
1191
  flask_thread.start()
 
 
1192
 
1193
+ # Give Flask a moment to start
1194
+ time.sleep(5) # Increased sleep time
1195
+
1196
+ # Launch Gradio interface
1197
+ demo.launch()
 
 
 
 
1198