s2049 commited on
Commit
dd21ebf
·
verified ·
1 Parent(s): 6ff23a7

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +510 -0
app.py ADDED
@@ -0,0 +1,510 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import requests
3
+ from bs4 import BeautifulSoup
4
+ import os
5
+ import re
6
+ import random
7
+ import io # No longer needed for CSV data, but keep for other potential uses
8
+ from dotenv import load_dotenv
9
+ from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
10
+ import torch
11
+ import gradio as gr
12
+ from sklearn.feature_extraction.text import TfidfVectorizer
13
+ from sklearn.metrics.pairwise import cosine_similarity
14
+ import time # For adding slight delays if TMDB API rate limits are hit
15
+
16
+ # --- Configuration ---
17
+ load_dotenv() # Load environment variables from .env file for local testing
18
+ TMDB_API_KEY = os.environ.get("TMDB_API_KEY")
19
+ HF_TOKEN = os.environ.get("HF_TOKEN")
20
+
21
+ MODEL_NAME = "mistralai/Mistral-7B-Instruct-v0.1"
22
+
23
+ BASE_TMDB_URL = "https://api.themoviedb.org/3"
24
+ POSTER_BASE_URL = "https://image.tmdb.org/t/p/w500"
25
+ NUM_RECOMMENDATIONS_TO_GENERATE = 20 # Generate more initially
26
+ NUM_RECOMMENDATIONS_TO_DISPLAY = 5 # Display top 5
27
+ MIN_RATING_FOR_SEED = 3.5
28
+ MIN_VOTE_COUNT_TMDB = 100 # Min votes on TMDB for a movie to be considered
29
+
30
+ # --- Global Variables for Data (Load once) ---
31
+ df_profile_global = None
32
+ df_comments_global = None
33
+ df_watchlist_global = None
34
+ df_reviews_global = None
35
+ df_diary_global = None
36
+ df_ratings_global = None
37
+ df_watched_global = None # This will be a consolidated df
38
+
39
+ uri_to_movie_map_global = {}
40
+ all_watched_titles_global = set()
41
+ watchlist_titles_global = set()
42
+ favorite_film_details_global = []
43
+ seed_movies_global = []
44
+
45
+ # LLM Pipeline (Load once)
46
+ llm_pipeline = None
47
+ llm_tokenizer = None
48
+
49
+ # --- Helper Functions ---
50
+ def clean_html(raw_html):
51
+ if pd.isna(raw_html) or raw_html is None:
52
+ return ""
53
+ # Add space before tags to handle cases like </b>text
54
+ text = str(raw_html)
55
+ text = re.sub(r'<br\s*/?>', '\n', text) # Convert <br> to newlines
56
+ soup = BeautifulSoup(text, "html.parser")
57
+ return soup.get_text(separator=" ", strip=True)
58
+
59
+ def get_movie_uri_map(dfs_dict):
60
+ """Creates a map from Letterboxd URI to (Name, Year)."""
61
+ uri_map = {}
62
+ # Order of preference for names/years if URIs are duplicated across files
63
+ # (though Name/Year should ideally be consistent for the same URI)
64
+ df_priority = ['reviews.csv', 'diary.csv', 'ratings.csv', 'watched.csv', 'watchlist.csv']
65
+
66
+ processed_uris = set()
67
+
68
+ for df_name in df_priority:
69
+ df = dfs_dict.get(df_name)
70
+ if df is not None and 'Letterboxd URI' in df.columns and 'Name' in df.columns and 'Year' in df.columns:
71
+ for _, row in df.iterrows():
72
+ uri = row['Letterboxd URI']
73
+ if pd.notna(uri) and uri not in processed_uris:
74
+ if pd.notna(row['Name']) and pd.notna(row['Year']):
75
+ try:
76
+ year = int(row['Year']) # Ensure year is int
77
+ uri_map[uri] = (str(row['Name']), year)
78
+ processed_uris.add(uri)
79
+ except ValueError:
80
+ # print(f"Warning: Could not parse year for {row['Name']} in {df_name}. Skipping URI map entry.")
81
+ pass # Or handle as an error/log
82
+ return uri_map
83
+
84
+ def load_all_data():
85
+ global df_profile_global, df_comments_global, df_watchlist_global, df_reviews_global
86
+ global df_diary_global, df_ratings_global, df_watched_global, uri_to_movie_map_global
87
+ global all_watched_titles_global, watchlist_titles_global, favorite_film_details_global, seed_movies_global
88
+
89
+ # --- Load DataFrames from CSV files ---
90
+ # IMPORTANT: Ensure these CSV files are uploaded to your Hugging Face Space root.
91
+ try:
92
+ df_profile_global = pd.read_csv("profile.csv")
93
+ df_comments_global = pd.read_csv("comments.csv")
94
+ df_watchlist_global = pd.read_csv("watchlist.csv")
95
+ df_reviews_global = pd.read_csv("reviews.csv")
96
+ df_diary_global = pd.read_csv("diary.csv")
97
+ df_ratings_global = pd.read_csv("ratings.csv")
98
+ # The 'watched.csv' you provided seems to be a log similar to diary, but without ratings.
99
+ # We'll primarily use diary, reviews, and ratings for watched history with ratings.
100
+ _df_watched_log = pd.read_csv("watched.csv") # Raw watched log
101
+ except FileNotFoundError as e:
102
+ print(f"ERROR: CSV file not found: {e}. Please ensure all CSV files are uploaded to the HF Space.")
103
+ return False # Indicate failure
104
+
105
+ dfs_for_uri_map = {
106
+ "reviews.csv": df_reviews_global,
107
+ "diary.csv": df_diary_global,
108
+ "ratings.csv": df_ratings_global,
109
+ "watched.csv": _df_watched_log, # from watched.csv
110
+ "watchlist.csv": df_watchlist_global
111
+ }
112
+ uri_to_movie_map_global = get_movie_uri_map(dfs_for_uri_map)
113
+
114
+ # --- Consolidate Watched History ---
115
+ # Combine diary, reviews, and ratings to get a comprehensive view of watched movies and their ratings/reviews
116
+ # Standardize column names for easier merging
117
+ df_diary_global.rename(columns={'Rating': 'Diary Rating'}, inplace=True)
118
+ df_reviews_global.rename(columns={'Rating': 'Review Rating', 'Review': 'Review Text'}, inplace=True)
119
+ df_ratings_global.rename(columns={'Rating': 'Simple Rating'}, inplace=True)
120
+
121
+ # Merge based on Letterboxd URI, Name, and Year (if URI is missing, try Name/Year)
122
+ # Start with reviews as it's richest
123
+ consolidated = df_reviews_global[['Letterboxd URI', 'Name', 'Year', 'Review Rating', 'Review Text', 'Watched Date']].copy()
124
+ consolidated.rename(columns={'Review Rating': 'Rating'}, inplace=True)
125
+
126
+ # Merge diary
127
+ diary_subset = df_diary_global[['Letterboxd URI', 'Name', 'Year', 'Diary Rating', 'Watched Date']].copy()
128
+ diary_subset.rename(columns={'Diary Rating': 'Rating_diary', 'Watched Date': 'Watched Date_diary'}, inplace=True)
129
+ consolidated = pd.merge(consolidated, diary_subset, on=['Letterboxd URI', 'Name', 'Year'], how='outer', suffixes=('', '_diary'))
130
+ consolidated['Rating'] = consolidated['Rating'].fillna(consolidated['Rating_diary'])
131
+ consolidated['Watched Date'] = consolidated['Watched Date'].fillna(consolidated['Watched Date_diary'])
132
+ consolidated.drop(columns=['Rating_diary', 'Watched Date_diary'], inplace=True)
133
+
134
+
135
+ # Merge simple ratings
136
+ ratings_subset = df_ratings_global[['Letterboxd URI', 'Name', 'Year', 'Simple Rating']].copy()
137
+ ratings_subset.rename(columns={'Simple Rating': 'Rating_simple'}, inplace=True)
138
+ consolidated = pd.merge(consolidated, ratings_subset, on=['Letterboxd URI', 'Name', 'Year'], how='outer', suffixes=('', '_simple'))
139
+ consolidated['Rating'] = consolidated['Rating'].fillna(consolidated['Rating_simple'])
140
+ consolidated.drop(columns=['Rating_simple'], inplace=True)
141
+
142
+ # Add movies from the raw watched.csv if they aren't already there (they won't have ratings from this source)
143
+ watched_log_subset = _df_watched_log[['Letterboxd URI', 'Name', 'Year']].copy()
144
+ # Add a 'Watched' column to mark these, and merge, filling NaNs appropriately
145
+ watched_log_subset['from_watched_log'] = True
146
+ consolidated = pd.merge(consolidated, watched_log_subset, on=['Letterboxd URI', 'Name', 'Year'], how='outer')
147
+ consolidated['from_watched_log'] = consolidated['from_watched_log'].fillna(False)
148
+
149
+
150
+ # Clean up and fill NAs
151
+ consolidated['Review Text'] = consolidated['Review Text'].fillna('').apply(clean_html)
152
+ consolidated['Year'] = pd.to_numeric(consolidated['Year'], errors='coerce').astype('Int64') # Handle potential non-numeric years
153
+ consolidated.dropna(subset=['Name', 'Year'], inplace=True) # Movies must have a name and year
154
+ consolidated.drop_duplicates(subset=['Name', 'Year'], keep='first', inplace=True)
155
+
156
+ df_watched_global = consolidated
157
+
158
+ # Populate all_watched_titles_global (Name, Year) tuples
159
+ all_watched_titles_global = set(zip(df_watched_global['Name'].astype(str), df_watched_global['Year'].astype(int)))
160
+ # Add from raw watched log as well
161
+ for _, row in _df_watched_log.iterrows():
162
+ if pd.notna(row['Name']) and pd.notna(row['Year']):
163
+ try:
164
+ all_watched_titles_global.add((str(row['Name']), int(row['Year'])))
165
+ except ValueError:
166
+ pass
167
+
168
+
169
+ # --- Process Watchlist ---
170
+ if df_watchlist_global is not None:
171
+ watchlist_titles_global = set()
172
+ for _, row in df_watchlist_global.iterrows():
173
+ if pd.notna(row['Name']) and pd.notna(row['Year']):
174
+ try:
175
+ watchlist_titles_global.add((str(row['Name']), int(row['Year'])))
176
+ except ValueError:
177
+ pass
178
+
179
+
180
+ # --- Process Favorite Films ---
181
+ favorite_film_details_global = []
182
+ if df_profile_global is not None and 'Favorite Films' in df_profile_global.columns:
183
+ fav_uris_str = df_profile_global.iloc[0]['Favorite Films']
184
+ if pd.notna(fav_uris_str):
185
+ fav_uris = [uri.strip() for uri in fav_uris_str.split(',')]
186
+ for uri in fav_uris:
187
+ if uri in uri_to_movie_map_global:
188
+ name, year = uri_to_movie_map_global[uri]
189
+ # Try to find rating and review from consolidated watched data
190
+ match = df_watched_global[(df_watched_global['Name'] == name) & (df_watched_global['Year'] == year)]
191
+ rating = match['Rating'].iloc[0] if not match.empty and pd.notna(match['Rating'].iloc[0]) else None
192
+ review = match['Review Text'].iloc[0] if not match.empty and match['Review Text'].iloc[0] else ""
193
+ favorite_film_details_global.append({'name': name, 'year': year, 'rating': rating, 'review_text': review, 'uri': uri})
194
+
195
+ # --- Identify Seed Movies ---
196
+ # Start with favorites
197
+ seed_movies_global.extend(favorite_film_details_global)
198
+
199
+ # Add other highly-rated movies (non-favorites)
200
+ highly_rated_df = df_watched_global[df_watched_global['Rating'] >= MIN_RATING_FOR_SEED]
201
+
202
+ favorite_uris = {fav['uri'] for fav in favorite_film_details_global if 'uri' in fav}
203
+
204
+ for _, row in highly_rated_df.iterrows():
205
+ if row['Letterboxd URI'] not in favorite_uris: # Avoid duplicates if already in favorites
206
+ seed_movies_global.append({
207
+ 'name': row['Name'],
208
+ 'year': row['Year'],
209
+ 'rating': row['Rating'],
210
+ 'review_text': row['Review Text'],
211
+ 'uri': row['Letterboxd URI']
212
+ })
213
+ # Remove duplicates based on name and year, preferring entries with more info (e.g., from favorites)
214
+ temp_df = pd.DataFrame(seed_movies_global)
215
+ temp_df.drop_duplicates(subset=['name', 'year'], keep='first', inplace=True)
216
+ seed_movies_global = temp_df.to_dict('records')
217
+
218
+ random.shuffle(seed_movies_global) # Shuffle to get variety if we pick a subset
219
+
220
+ return True # Indicate success
221
+
222
+ def initialize_llm():
223
+ global llm_pipeline, llm_tokenizer
224
+ if llm_pipeline is None:
225
+ print(f"Initializing LLM: {MODEL_NAME}")
226
+ try:
227
+ llm_tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
228
+ # For CPU, bfloat16 might not be supported, try float32 or default
229
+ # Adding device_map="auto" and load_in_8bit=True for potentially better memory management on CPU
230
+ # For Spaces CPU, bitsandbytes might not be ideal. Try without quantization first if issues arise.
231
+ # Remove load_in_8bit if it causes issues on standard CPU Space.
232
+ model = AutoModelForCausalLM.from_pretrained(
233
+ MODEL_NAME,
234
+ torch_dtype=torch.float16, # Use float16 for faster inference and less memory
235
+ device_map="auto", # Automatically maps to available device (CPU or GPU if available)
236
+ # load_in_8bit=True, # Quantization - might need bitsandbytes
237
+ trust_remote_code=True,
238
+ token=HF_TOKEN if HF_TOKEN else None
239
+ )
240
+ llm_pipeline = pipeline(
241
+ "text-generation",
242
+ model=model,
243
+ tokenizer=llm_tokenizer,
244
+ torch_dtype=torch.float16,
245
+ device_map="auto"
246
+ )
247
+ print("LLM Initialized Successfully.")
248
+ except Exception as e:
249
+ print(f"Error initializing LLM: {e}")
250
+ llm_pipeline = None # Ensure it's None if initialization fails
251
+
252
+ # --- TMDB API Functions ---
253
+ def search_tmdb_movie_details(title, year):
254
+ if not TMDB_API_KEY:
255
+ print("TMDB API Key not configured.")
256
+ return None
257
+ try:
258
+ search_url = f"{BASE_TMDB_URL}/search/movie"
259
+ params = {'api_key': TMDB_API_KEY, 'query': title, 'year': year, 'language': 'en-US'}
260
+ response = requests.get(search_url, params=params)
261
+ response.raise_for_status()
262
+ results = response.json().get('results', [])
263
+ if results:
264
+ movie = results[0]
265
+ # Fetch genres using the /movie/{movie_id} endpoint to get full genre names
266
+ movie_details_url = f"{BASE_TMDB_URL}/movie/{movie['id']}"
267
+ details_params = {'api_key': TMDB_API_KEY, 'language': 'en-US'}
268
+ details_response = requests.get(movie_details_url, params=details_params)
269
+ details_response.raise_for_status()
270
+ movie_full_details = details_response.json()
271
+
272
+ return {
273
+ 'id': movie.get('id'),
274
+ 'title': movie.get('title'),
275
+ 'year': str(movie.get('release_date', ''))[:4],
276
+ 'overview': movie.get('overview'),
277
+ 'poster_path': POSTER_BASE_URL + movie.get('poster_path') if movie.get('poster_path') else "https://via.placeholder.com/500x750.png?text=No+Poster",
278
+ 'genres': [genre['name'] for genre in movie_full_details.get('genres', [])],
279
+ 'vote_average': movie.get('vote_average'),
280
+ 'vote_count': movie.get('vote_count'),
281
+ 'popularity': movie.get('popularity')
282
+ }
283
+ time.sleep(0.2) # Small delay to respect API rate limits
284
+ except requests.RequestException as e:
285
+ print(f"Error searching TMDB for {title} ({year}): {e}")
286
+ except Exception as ex:
287
+ print(f"Unexpected error in search_tmdb_movie_details for {title} ({year}): {ex}")
288
+ return None
289
+
290
+ def get_tmdb_recommendations(movie_id, page=1):
291
+ if not TMDB_API_KEY:
292
+ print("TMDB API Key not configured.")
293
+ return []
294
+ recommendations = []
295
+ try:
296
+ rec_url = f"{BASE_TMDB_URL}/movie/{movie_id}/recommendations"
297
+ params = {'api_key': TMDB_API_KEY, 'page': page, 'language': 'en-US'}
298
+ response = requests.get(rec_url, params=params)
299
+ response.raise_for_status()
300
+ results = response.json().get('results', [])
301
+
302
+ for movie in results:
303
+ if movie.get('vote_count', 0) >= MIN_VOTE_COUNT_TMDB:
304
+ recommendations.append({
305
+ 'id': movie.get('id'),
306
+ 'title': movie.get('title'),
307
+ 'year': str(movie.get('release_date', ''))[:4] if movie.get('release_date') else "N/A",
308
+ 'overview': movie.get('overview'),
309
+ 'poster_path': POSTER_BASE_URL + movie.get('poster_path') if movie.get('poster_path') else "https://via.placeholder.com/500x750.png?text=No+Poster",
310
+ 'vote_average': movie.get('vote_average'),
311
+ 'vote_count': movie.get('vote_count'),
312
+ 'popularity': movie.get('popularity')
313
+ })
314
+ time.sleep(0.2) # Small delay
315
+ except requests.RequestException as e:
316
+ print(f"Error getting TMDB recommendations for movie ID {movie_id}: {e}")
317
+ except Exception as ex:
318
+ print(f"Unexpected error in get_tmdb_recommendations for movie ID {movie_id}: {ex}")
319
+ return recommendations
320
+
321
+ # --- LLM Explanation Generation ---
322
+ def generate_saudi_explanation(recommended_movie_title, seed_movie_title, seed_movie_context=""):
323
+ global llm_pipeline, llm_tokenizer
324
+ if llm_pipeline is None or llm_tokenizer is None:
325
+ return "للأسف، نموذج الذكاء الاصطناعي مو جاهز الحين. حاول مرة ثانية بعد شوي."
326
+
327
+ # Truncate long context to avoid overly long prompts
328
+ max_context_len = 200
329
+ if len(seed_movie_context) > max_context_len:
330
+ seed_movie_context_short = seed_movie_context[:max_context_len] + "..."
331
+ else:
332
+ seed_movie_context_short = seed_movie_context
333
+
334
+ prompt_template = f"""<s>[INST] أنت ناقد أفلام سعودي خبير ودمك خفيف. المستخدم أعجب بالفيلم "{seed_movie_title}".
335
+ سبب إعجابه بالفيلم الأول (إذا متوفر): "{seed_movie_context_short}"
336
+ بناءً على ذلك، نُرشح له فيلم "{recommended_movie_title}".
337
+ اكتب جملة أو جملتين باللهجة السعودية العامية، تشرح ليش ممكن يعجبه الفيلم الجديد "{recommended_movie_title}"، مع ربطها بالفيلم اللي عجبه "{seed_movie_title}". خلي كلامك وناسة ويشد الواحد وما يكون طويل. لا تذكر أبداً أنك نموذج لغوي أو ذكاء اصطناعي.
338
+
339
+ مثال للأسلوب المطلوب (لو الفيلم اللي عجبه "Mad Max: Fury Road" والفيلم المرشح "Dune"):
340
+ "يا طويل العمر، شفت كيف 'Mad Max: Fury Road' عجّبك بجوّه الصحراوي والأكشن اللي ما يوقّف؟ أجل اسمع، 'Dune' بيوديك لصحراء ثانية بس أعظم وأفخم، وقصة تحبس الأنفاس! شد حيلك وشوفه."
341
+
342
+ الآن، الفيلم الذي أعجب المستخدم هو: "{seed_movie_title}"
343
+ سبب إعجابه بالفيلم الأول (إذا متوفر): "{seed_movie_context_short}"
344
+ الفيلم المرشح: "{recommended_movie_title}"
345
+ اشرح باللهجة السعودية: [/INST]"""
346
+
347
+ try:
348
+ sequences = llm_pipeline(
349
+ prompt_template,
350
+ do_sample=True,
351
+ top_k=10,
352
+ num_return_sequences=1,
353
+ eos_token_id=llm_tokenizer.eos_token_id,
354
+ max_new_tokens=100 # Limit output length
355
+ )
356
+ explanation = sequences[0]['generated_text'].split("[/INST]")[-1].strip()
357
+ # Further clean up if the model repeats parts of the prompt or adds unwanted prefixes
358
+ explanation = re.sub(r"^اشرح باللهجة السعودية:\s*", "", explanation, flags=re.IGNORECASE)
359
+ explanation = explanation.replace("<s>", "").replace("</s>", "").strip()
360
+ if not explanation or explanation.lower().startswith("أنت ناقد أفلام"): # Fallback if generation is poor
361
+ return f"شكلك بتنبسط على فيلم '{recommended_movie_title}' لأنه يشبه جو فيلم '{seed_movie_title}' اللي حبيته! عطيه تجربة."
362
+ return explanation
363
+ except Exception as e:
364
+ print(f"Error during LLM generation: {e}")
365
+ return f"يا كابتن، شكلك بتحب '{recommended_movie_title}'، خاصة إنك استمتعت بـ'{seed_movie_title}'. جربه وعطنا رأيك!"
366
+
367
+ # --- Recommendation Logic ---
368
+ def get_recommendations_for_salman(progress=gr.Progress()):
369
+ if not TMDB_API_KEY:
370
+ return "<p style='color:red; text-align:right;'>خطأ: مفتاح TMDB API مو موجود. الرجاء إضافته كـ Secret في Hugging Face Space.</p>"
371
+
372
+ if not all([df_profile_global is not None, df_watched_global is not None, seed_movies_global]):
373
+ return "<p style='color:red; text-align:right;'>خطأ: فشل في تحميل بياناتك. تأكد من رفع ملفات CSV بشكل صحيح.</p>"
374
+
375
+ if llm_pipeline is None:
376
+ initialize_llm() # Attempt to initialize if not already
377
+ if llm_pipeline is None:
378
+ return "<p style='color:red; text-align:right;'>خطأ: فشل في تهيئة نموذج الذكاء الاصطناعي. حاول تحديث الصفحة.</p>"
379
+
380
+
381
+ progress(0.1, desc="جمعنا أفلامك المفضلة واللي قيمتها عالي...")
382
+
383
+ potential_recs = {} # Store as {tmdb_id: {'movie_info': ..., 'seed_movie': ..., 'seed_context': ...}}
384
+
385
+ # Limit the number of seed movies to process to avoid excessive API calls / long processing
386
+ seeds_to_process = seed_movies_global[:30] if len(seed_movies_global) > 30 else seed_movies_global
387
+
388
+ for i, seed_movie in enumerate(seeds_to_process):
389
+ progress(0.1 + (i / len(seeds_to_process)) * 0.4, desc=f"نبحث عن توصيات بناءً على: {seed_movie['name']}")
390
+
391
+ seed_tmdb_details = search_tmdb_movie_details(seed_movie['name'], seed_movie['year'])
392
+ if seed_tmdb_details and seed_tmdb_details.get('id'):
393
+ tmdb_recs = get_tmdb_recommendations(seed_tmdb_details['id'])
394
+ for rec in tmdb_recs:
395
+ rec_tuple = (str(rec['title']), int(rec['year'])) # (Name, Year)
396
+ # Ensure rec_tuple elements are of correct type before comparison
397
+ if rec.get('id') and rec_tuple not in all_watched_titles_global and rec_tuple not in watchlist_titles_global:
398
+ if rec['id'] not in potential_recs: # Add if new, prioritizing first seed
399
+ potential_recs[rec['id']] = {
400
+ 'movie_info': rec,
401
+ 'seed_movie_title': seed_movie['name'],
402
+ 'seed_movie_context': seed_movie.get('review_text', '') or seed_movie.get('comment_text', '')
403
+ }
404
+ # Simple content-based similarity as a fallback or supplement (Optional, can be complex)
405
+ # For now, primarily TMDB-based
406
+
407
+ if not potential_recs:
408
+ return "<p style='text-align:right;'>ما لقينا توصيات جديدة لك حالياً. يمكن شفت كل شيء رهيب! 😉</p>"
409
+
410
+ # Sort recommendations (e.g., by popularity or a mix, or just randomize for now)
411
+ # Let's sort by TMDB popularity for now to get some generally well-regarded films
412
+ sorted_recs_list = sorted(potential_recs.values(), key=lambda x: x['movie_info'].get('popularity', 0), reverse=True)
413
+
414
+ final_recommendations_data = []
415
+
416
+ # Take top N distinct recommendations
417
+ displayed_ids = set()
418
+ for rec_data in sorted_recs_list:
419
+ if len(final_recommendations_data) >= NUM_RECOMMENDATIONS_TO_DISPLAY:
420
+ break
421
+ if rec_data['movie_info']['id'] not in displayed_ids:
422
+ final_recommendations_data.append(rec_data)
423
+ displayed_ids.add(rec_data['movie_info']['id'])
424
+
425
+ if not final_recommendations_data:
426
+ return "<p style='text-align:right;'>ما لقينا توصيات جديدة لك حالياً بعد الفلترة. يمكن شفت كل شيء رهيب! 😉</p>"
427
+
428
+ output_html = "<div>" # Main container
429
+ progress(0.6, desc="نجهز لك الشرح باللغة العامية...")
430
+
431
+ for i, rec_data in enumerate(final_recommendations_data):
432
+ progress(0.6 + (i / len(final_recommendations_data)) * 0.4, desc=f"نكتب شرح لفيلم: {rec_data['movie_info']['title']}")
433
+
434
+ explanation = generate_saudi_explanation(
435
+ rec_data['movie_info']['title'],
436
+ rec_data['seed_movie_title'],
437
+ rec_data['seed_movie_context']
438
+ )
439
+
440
+ poster_url = rec_data['movie_info']['poster_path']
441
+ if not poster_url or "placeholder.com" in poster_url: # Use a default if no poster
442
+ poster_url = f"https://via.placeholder.com/300x450.png?text={rec_data['movie_info']['title'].replace(' ', '+')}"
443
+
444
+ output_html += f"""
445
+ <div style="display: flex; flex-direction: row-reverse; align-items: flex-start; margin-bottom: 25px; border-bottom: 1px solid #ddd; padding-bottom:15px; background-color: #f9f9f9; border-radius: 8px; padding: 15px;">
446
+ <img src="{poster_url}" alt="{rec_data['movie_info']['title']}" style="width: 150px; max-width:30%; height: auto; margin-left: 20px; border-radius: 5px; box-shadow: 2px 2px 5px rgba(0,0,0,0.1);">
447
+ <div style="text-align: right; direction: rtl; flex-grow: 1;">
448
+ <h3 style="margin-top:0; color: #c70039;">{rec_data['movie_info']['title']} ({rec_data['movie_info']['year']})</h3>
449
+ <p style="font-size: 1.1em; color: #333; line-height: 1.6;">{explanation}</p>
450
+ <p style="font-size: 0.9em; color: #777; margin-top: 10px;"><em>يا وحش، رشحنا لك هذا الفيلم لأنك حبيت: <strong style="color:#555;">{rec_data['seed_movie_title']}</strong></em></p>
451
+ </div>
452
+ </div>
453
+ """
454
+ output_html += "</div>"
455
+ return gr.HTML(output_html)
456
+
457
+ # --- Gradio Interface ---
458
+ css = """
459
+ body { font-family: 'Tajawal', sans-serif; }
460
+ .gradio-container { font-family: 'Tajawal', sans-serif !important; direction: rtl; }
461
+ footer { display: none !important; }
462
+ .gr-button { background-color: #c70039 !important; color: white !important; font-size: 1.2em !important; padding: 10px 20px !important; border-radius: 8px !important; }
463
+ .gr-button:hover { background-color: #a3002f !important; }
464
+ .gr-input { text-align: right !important; }
465
+ .gr-output { text-align: right !important; }
466
+ h1, h3 { color: #900c3f !important; }
467
+ """
468
+
469
+ # Load data once when the script starts
470
+ data_loaded_successfully = load_all_data()
471
+ if data_loaded_successfully:
472
+ print("All user data loaded and preprocessed successfully.")
473
+ # Initialize LLM after data loading to ensure it happens on app startup if data is present
474
+ initialize_llm()
475
+ else:
476
+ print("Failed to load user data. The app might not function correctly.")
477
+
478
+
479
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="red", secondary_hue="pink"), css=css) as iface:
480
+ gr.Markdown(
481
+ """
482
+ <div style="text-align: center;">
483
+ <h1 style="color: #c70039; font-size: 2.5em;">🎬 رفيقك السينمائي 🍿</h1>
484
+ <p style="font-size: 1.2em; color: #555;">يا هلا بك يا سلمان! اضغط الزر تحت وخلنا نعطيك توصيات أفلام على كيف كيفك، مع شرح بالعامية ليش ممكن تدخل مزاجك.</p>
485
+ </div>
486
+ """
487
+ )
488
+
489
+ recommend_button = gr.Button("يا سلمان، عطني توصيات أفلام!")
490
+
491
+ with gr.Column():
492
+ output_recommendations = gr.HTML(label="توصياتك النارية 🔥")
493
+
494
+ recommend_button.click(
495
+ fn=get_recommendations_for_salman,
496
+ inputs=[],
497
+ outputs=[output_recommendations]
498
+ )
499
+
500
+ gr.Markdown(
501
+ """
502
+ <div style="text-align: center; margin-top: 30px; font-size: 0.9em; color: #777;">
503
+ <p>تم تطوير هذا النظام بواسطة الذكاء الاصطناعي مع لمسة شخصية من بياناتك في ليتربوكسد.</p>
504
+ <p>استمتع بالمشاهدة! 🎥</p>
505
+ </div>
506
+ """
507
+ )
508
+
509
+ if __name__ == "__main__":
510
+ iface.launch(debug=True) # debug=True for local testing, remove for HF