s2049 commited on
Commit
afb6dea
·
verified ·
1 Parent(s): b90f766

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +159 -113
app.py CHANGED
@@ -4,36 +4,34 @@ from bs4 import BeautifulSoup
4
  import os
5
  import re
6
  import random
7
- from dotenv import load_dotenv
8
  from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
9
  import torch
10
  import gradio as gr
11
  import time
12
 
13
- # Opt-in to future pandas behavior to potentially silence the downcasting warning
14
- # pd.set_option('future.no_silent_downcasting', True) # You can uncomment this if you wish
15
-
16
  # --- Configuration ---
17
- load_dotenv()
18
- TMDB_API_KEY = os.environ.get("TMDB_API_KEY", "442a13f1865d8936f95aa20737e6f6f5")
19
- HF_TOKEN = os.environ.get("HF_TOKEN") # CRUCIAL for gated models
 
 
20
 
21
- # CORRECTED MODEL NAME
22
- MODEL_NAME = "ALLaM-AI/ALLaM-7B-Instruct-preview"
23
 
24
  BASE_TMDB_URL = "https://api.themoviedb.org/3"
25
  POSTER_BASE_URL = "https://image.tmdb.org/t/p/w500"
26
  NUM_RECOMMENDATIONS_TO_DISPLAY = 5
27
  MIN_RATING_FOR_SEED = 3.5
28
- MIN_VOTE_COUNT_TMDB = 100
29
 
30
- # --- Global Variables ---
31
  df_profile_global = None
32
  df_watchlist_global = None
33
  df_reviews_global = None
34
  df_diary_global = None
35
  df_ratings_global = None
36
- df_watched_global = None
37
 
38
  uri_to_movie_map_global = {}
39
  all_watched_titles_global = set()
@@ -48,7 +46,7 @@ llm_tokenizer = None
48
  def clean_html(raw_html):
49
  if pd.isna(raw_html) or raw_html is None: return ""
50
  text = str(raw_html)
51
- text = re.sub(r'<br\s*/?>', '\n', text)
52
  soup = BeautifulSoup(text, "html.parser")
53
  return soup.get_text(separator=" ", strip=True)
54
 
@@ -67,7 +65,9 @@ def get_movie_uri_map(dfs_dict):
67
  year = int(row['Year'])
68
  uri_map[uri] = (str(row['Name']), year)
69
  processed_uris.add(uri)
70
- except ValueError: pass
 
 
71
  return uri_map
72
 
73
  def load_all_data():
@@ -76,15 +76,17 @@ def load_all_data():
76
  global watchlist_titles_global, favorite_film_details_global, seed_movies_global
77
 
78
  try:
 
79
  df_profile_global = pd.read_csv("profile.csv")
 
80
  df_watchlist_global = pd.read_csv("watchlist.csv")
81
  df_reviews_global = pd.read_csv("reviews.csv")
82
  df_diary_global = pd.read_csv("diary.csv")
83
  df_ratings_global = pd.read_csv("ratings.csv")
84
- _df_watched_log = pd.read_csv("watched.csv")
85
  except FileNotFoundError as e:
86
- print(f"ERROR: CSV file not found: {e}.")
87
- return False
88
 
89
  dfs_for_uri_map = {
90
  "reviews.csv": df_reviews_global, "diary.csv": df_diary_global,
@@ -114,17 +116,14 @@ def load_all_data():
114
  consolidated.drop(columns=['Rating_simple'], inplace=True)
115
 
116
  watched_log_subset = _df_watched_log[['Letterboxd URI', 'Name', 'Year']].copy()
117
- watched_log_subset['from_watched_log'] = True # This column is an object/boolean dtype
118
  consolidated = pd.merge(consolidated, watched_log_subset, on=['Letterboxd URI', 'Name', 'Year'], how='outer')
119
-
120
- # Address the FutureWarning directly or use pd.set_option
121
- # This ensures 'from_watched_log' becomes boolean after fillna
122
  consolidated['from_watched_log'] = consolidated['from_watched_log'].fillna(False).astype(bool)
123
 
124
 
125
  consolidated['Review Text'] = consolidated['Review Text'].fillna('').apply(clean_html)
126
  consolidated['Year'] = pd.to_numeric(consolidated['Year'], errors='coerce').astype('Int64')
127
- consolidated.dropna(subset=['Name', 'Year'], inplace=True)
128
  consolidated.drop_duplicates(subset=['Name', 'Year'], keep='first', inplace=True)
129
  df_watched_global = consolidated
130
 
@@ -142,7 +141,7 @@ def load_all_data():
142
  except ValueError: pass
143
 
144
  favorite_film_details_global = []
145
- if df_profile_global is not None and 'Favorite Films' in df_profile_global.columns:
146
  fav_uris_str = df_profile_global.iloc[0]['Favorite Films']
147
  if pd.notna(fav_uris_str):
148
  fav_uris = [uri.strip() for uri in fav_uris_str.split(',')]
@@ -155,61 +154,76 @@ def load_all_data():
155
  favorite_film_details_global.append({'name': name, 'year': year, 'rating': rating, 'review_text': review, 'uri': uri})
156
 
157
  seed_movies_global.extend(favorite_film_details_global)
158
- highly_rated_df = df_watched_global[df_watched_global['Rating'] >= MIN_RATING_FOR_SEED]
159
- favorite_uris = {fav['uri'] for fav in favorite_film_details_global if 'uri' in fav}
160
- for _, row in highly_rated_df.iterrows():
161
- if row['Letterboxd URI'] not in favorite_uris:
162
- seed_movies_global.append({
163
- 'name': row['Name'], 'year': row['Year'], 'rating': row['Rating'],
164
- 'review_text': row['Review Text'], 'uri': row['Letterboxd URI']
165
- })
166
- temp_df = pd.DataFrame(seed_movies_global)
167
- if not temp_df.empty: # Check if DataFrame is not empty before dropping duplicates
168
- temp_df.drop_duplicates(subset=['name', 'year'], keep='first', inplace=True)
169
- seed_movies_global = temp_df.to_dict('records')
 
 
170
  else:
171
- seed_movies_global = [] # Ensure it's an empty list if temp_df was empty
172
 
173
  random.shuffle(seed_movies_global)
174
  return True
175
 
176
  def initialize_llm():
177
  global llm_pipeline, llm_tokenizer
178
- if llm_pipeline is None:
179
- print(f"Initializing LLM: {MODEL_NAME}")
180
  if not HF_TOKEN:
181
- print("WARNING: HF_TOKEN not found. Access to gated models like ALLaM will fail.")
182
- # Optionally, you could prevent the attempt to load if no token,
183
- # or let it try and fail, as it currently does.
184
- # return # uncomment to stop here if no token
185
 
186
  try:
187
- llm_tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True, token=HF_TOKEN)
 
 
 
 
 
 
 
188
  model = AutoModelForCausalLM.from_pretrained(
189
  MODEL_NAME,
190
  torch_dtype=torch.float16,
191
- device_map="auto",
192
- load_in_8bit=True,
193
  trust_remote_code=True,
194
  token=HF_TOKEN
195
  )
 
 
196
  if llm_tokenizer.pad_token is None:
 
197
  llm_tokenizer.pad_token = llm_tokenizer.eos_token
198
- model.config.pad_token_id = model.config.eos_token_id
 
 
199
 
200
  llm_pipeline = pipeline(
201
- "text-generation", model=model, tokenizer=llm_tokenizer
 
 
202
  )
203
- print(f"LLM ({MODEL_NAME}) Initialized Successfully.")
204
  except Exception as e:
205
- print(f"Error initializing LLM ({MODEL_NAME}): {e}")
 
206
  llm_pipeline = None
207
-
208
 
209
  # --- TMDB API Functions ---
210
  def search_tmdb_movie_details(title, year):
211
- if not TMDB_API_KEY or TMDB_API_KEY == "YOUR_TMDB_API_KEY_FALLBACK":
212
- print("TMDB API Key not properly configured.")
213
  return None
214
  try:
215
  search_url = f"{BASE_TMDB_URL}/search/movie"
@@ -232,14 +246,14 @@ def search_tmdb_movie_details(title, year):
232
  'vote_average': movie.get('vote_average'), 'vote_count': movie.get('vote_count'),
233
  'popularity': movie.get('popularity')
234
  }
235
- time.sleep(0.25)
236
- except requests.RequestException as e: print(f"Error searching TMDB for {title} ({year}): {e}")
237
- except Exception as ex: print(f"Unexpected error in search_tmdb_movie_details for {title} ({year}): {ex}")
238
  return None
239
 
240
  def get_tmdb_recommendations(movie_id, page=1):
241
- if not TMDB_API_KEY or TMDB_API_KEY == "YOUR_TMDB_API_KEY_FALLBACK":
242
- print("TMDB API Key not properly configured.")
243
  return []
244
  recommendations = []
245
  try:
@@ -258,21 +272,23 @@ def get_tmdb_recommendations(movie_id, page=1):
258
  'vote_average': movie.get('vote_average'), 'vote_count': movie.get('vote_count'),
259
  'popularity': movie.get('popularity')
260
  })
261
- time.sleep(0.25)
262
- except requests.RequestException as e: print(f"Error getting TMDB recommendations for movie ID {movie_id}: {e}")
263
- except Exception as ex: print(f"Unexpected error in get_tmdb_recommendations for movie ID {movie_id}: {ex}")
264
  return recommendations
265
 
266
  # --- LLM Explanation ---
267
  def generate_saudi_explanation(recommended_movie_title, seed_movie_title, seed_movie_context=""):
268
  global llm_pipeline, llm_tokenizer
269
  if llm_pipeline is None or llm_tokenizer is None:
270
- return "للأسف، نموذج الذكاء الاصطناعي مو جاهز الحين. حاول مرة ثانية بعد شوي."
 
271
 
272
  max_context_len = 150
273
  seed_movie_context_short = (seed_movie_context[:max_context_len] + "...") if len(seed_movie_context) > max_context_len else seed_movie_context
274
 
275
- # Check ALLaM model card for specific prompt format. Using [INST] as it's common for Instruct models.
 
276
  prompt_template = f"""<s>[INST] أنت ناقد أفلام سعودي خبير ودمك خفيف جداً. مهمتك هي كتابة توصية لفيلم جديد بناءً على فيلم سابق أعجب المستخدم.
277
  المستخدم أعجب بالفيلم هذا: "{seed_movie_title}".
278
  وكان تعليقه أو سبب إعجابه (إذا متوفر): "{seed_movie_context_short}"
@@ -293,7 +309,7 @@ def generate_saudi_explanation(recommended_movie_title, seed_movie_title, seed_m
293
  prompt_template, do_sample=True, top_k=20, top_p=0.9, num_return_sequences=1,
294
  eos_token_id=llm_tokenizer.eos_token_id,
295
  pad_token_id=llm_tokenizer.pad_token_id if llm_tokenizer.pad_token_id is not None else llm_tokenizer.eos_token_id,
296
- max_new_tokens=150
297
  )
298
  explanation = sequences[0]['generated_text'].split("[/INST]")[-1].strip()
299
  explanation = explanation.replace("<s>", "").replace("</s>", "").strip()
@@ -301,50 +317,61 @@ def generate_saudi_explanation(recommended_movie_title, seed_movie_title, seed_m
301
  explanation = re.sub(r"كنموذج لغوي.*?\s*,?\s*", "", explanation, flags=re.IGNORECASE)
302
 
303
  if not explanation or explanation.lower().startswith("أنت ناقد أفلام") or len(explanation) < 20 :
 
304
  return f"شكلك بتنبسط ع��ى فيلم '{recommended_movie_title}' لأنه يشبه جو فيلم '{seed_movie_title}' اللي حبيته! عطيه تجربة."
305
  return explanation
306
  except Exception as e:
307
- print(f"Error during LLM generation with {MODEL_NAME}: {e}")
308
  return f"يا كابتن، شكلك بتحب '{recommended_movie_title}'، خاصة إنك استمتعت بـ'{seed_movie_title}'. جربه وعطنا رأيك!"
309
 
310
  # --- Recommendation Logic ---
311
- def get_recommendations(progress=gr.Progress()):
312
- if not TMDB_API_KEY or (TMDB_API_KEY == "442a13f1865d8936f95aa20737e6f6f5" and not os.environ.get("TMDB_API_KEY")):
313
- print("Warning: Using fallback TMDB API Key.")
314
  if not TMDB_API_KEY:
315
- return "<p style='color:red; text-align:right;'>خطأ: مفتاح TMDB API مو موجود.</p>"
316
- if not all([df_profile_global is not None, df_watched_global is not None, seed_movies_global]):
317
- return "<p style='color:red; text-align:right;'>خطأ: فشل في تحميل بيانات المستخدم.</p>"
318
 
319
- # Ensure LLM is initialized before trying to use it
320
- if llm_pipeline is None:
321
- initialize_llm() # Attempt to initialize if not already done
322
- if llm_pipeline is None: # Check again if initialization failed
323
- return "<p style='color:red; text-align:right;'>خطأ: فشل في تهيئة نموذج الذكاء الاصطناعي. تأكد من وجود HF_TOKEN وأن لديك صلاحية الوصول للنموذج.</p>"
 
 
324
 
325
  progress(0.1, desc="نجمع أفلامك المفضلة...")
326
  potential_recs = {}
327
- seeds_to_process = seed_movies_global[:25]
 
328
 
329
  for i, seed_movie in enumerate(seeds_to_process):
330
- progress(0.1 + (i / len(seeds_to_process)) * 0.4, desc=f"نبحث عن توصيات بناءً على: {seed_movie['name']}")
331
- seed_tmdb_details = search_tmdb_movie_details(seed_movie['name'], seed_movie['year'])
332
  if seed_tmdb_details and seed_tmdb_details.get('id'):
333
  tmdb_recs = get_tmdb_recommendations(seed_tmdb_details['id'])
334
  for rec in tmdb_recs:
335
  try:
336
- rec_tuple = (str(rec['title']), int(rec['year']))
 
 
 
 
337
  if rec.get('id') and rec_tuple not in all_watched_titles_global and rec_tuple not in watchlist_titles_global:
338
- if rec['id'] not in potential_recs:
339
  potential_recs[rec['id']] = {
340
- 'movie_info': rec, 'seed_movie_title': seed_movie['name'],
 
341
  'seed_movie_context': seed_movie.get('review_text', '') or seed_movie.get('comment_text', '')
342
  }
343
- except (ValueError, TypeError): continue # Catch TypeError if year is None
 
 
344
  if not potential_recs:
345
- return "<p style='text-align:right;'>ما لقينا توصيات جديدة لك حالياً. 😉</p>"
346
 
 
347
  sorted_recs_list = sorted(potential_recs.values(), key=lambda x: x['movie_info'].get('popularity', 0), reverse=True)
 
348
  final_recommendations_data = []
349
  displayed_ids = set()
350
  for rec_data in sorted_recs_list:
@@ -352,74 +379,93 @@ def get_recommendations(progress=gr.Progress()):
352
  if rec_data['movie_info']['id'] not in displayed_ids:
353
  final_recommendations_data.append(rec_data)
354
  displayed_ids.add(rec_data['movie_info']['id'])
 
355
  if not final_recommendations_data:
356
- return "<p style='text-align:right;'>ما لقينا توصيات جديدة لك حالياً بعد الفلترة. 😉</p>"
357
 
358
- output_html = "<div>"
359
  progress(0.6, desc="نجهز لك الشرح باللغة العامية...")
 
360
  for i, rec_data in enumerate(final_recommendations_data):
361
  progress(0.6 + (i / len(final_recommendations_data)) * 0.4, desc=f"نكتب شرح لفيلم: {rec_data['movie_info']['title']}")
362
  explanation = generate_saudi_explanation(
363
  rec_data['movie_info']['title'], rec_data['seed_movie_title'], rec_data['seed_movie_context']
364
  )
365
  poster_url = rec_data['movie_info']['poster_path']
366
- if not poster_url or "placeholder.com" in poster_url:
367
- poster_url = f"https://via.placeholder.com/300x450.png?text={rec_data['movie_info']['title'].replace(' ', '+')}"
 
 
368
  output_html += f"""
369
- <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;">
370
  <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);">
371
  <div style="text-align: right; direction: rtl; flex-grow: 1;">
372
  <h3 style="margin-top:0; color: #c70039;">{rec_data['movie_info']['title']} ({rec_data['movie_info']['year']})</h3>
373
  <p style="font-size: 1.1em; color: #333; line-height: 1.6;">{explanation}</p>
374
- <p style="font-size: 0.9em; color: #777; margin-top: 10px;"><em>رشحنا لك هذا الفيلم لأنك حبيت: <strong style="color:#555;">{rec_data['seed_movie_title']}</strong></em></p>
375
  </div>
376
  </div>"""
377
  output_html += "</div>"
378
  return gr.HTML(output_html)
379
 
380
  # --- Gradio Interface ---
381
- css = """
382
  body { font-family: 'Tajawal', sans-serif; }
383
- .gradio-container { font-family: 'Tajawal', sans-serif !important; direction: rtl; }
384
  footer { display: none !important; }
385
- .gr-button { background-color: #c70039 !important; color: white !important; font-size: 1.2em !important; padding: 10px 20px !important; border-radius: 8px !important; }
386
- .gr-button:hover { background-color: #a3002f !important; }
387
- h1, h3 { color: #900c3f !important; }
388
- """ # Removed .gr-input and .gr-output as they aren't used directly for styling here
 
389
 
 
390
  data_loaded_successfully = load_all_data()
391
  if data_loaded_successfully:
392
- print("All user data loaded and preprocessed successfully.")
393
- # LLM will be initialized on first click if not already
 
 
394
  else:
395
- print("Failed to load user data. The app might not function correctly.")
396
 
397
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="red", secondary_hue="pink"), css=css) as iface:
 
 
 
 
398
  gr.Markdown(
399
  """
400
- <div style="text-align: center;">
401
- <h1 style="color: #c70039; font-size: 2.5em;">🎬 رفيقك السينمائي 🍿</h1>
402
  <p style="font-size: 1.2em; color: #555;">يا هلا بك! اضغط الزر تحت وخلنا نعطيك توصيات أفلام على كيف كيفك، مع شرح بالعامية ليش ممكن تدخل مزاجك.</p>
403
  </div>"""
404
  )
405
- recommend_button = gr.Button("عطني توصيات أفلام!")
406
- with gr.Column():
407
- output_recommendations = gr.HTML(label="توصياتك النارية 🔥")
 
408
 
409
- # Call initialize_llm once when the interface is defined if data loaded successfully
410
- # This way, it tries to load the LLM when the app starts, not just on the first click.
411
  if data_loaded_successfully:
412
- initialize_llm() # Moved initialization here
413
 
414
- recommend_button.click(fn=get_recommendations, inputs=[], outputs=[output_recommendations])
 
415
  gr.Markdown(
416
  """
417
- <div style="text-align: center; margin-top: 30px; font-size: 0.9em; color: #777;">
418
- <p>استمتع بالمشاهدة! 🎥</p>
419
  </div>"""
420
  )
421
 
422
  if __name__ == "__main__":
423
- if not TMDB_API_KEY or (TMDB_API_KEY == "442a13f1865d8936f95aa20737e6f6f5" and not os.environ.get("TMDB_API_KEY")):
424
- print("\nWARNING: TMDB_API_KEY is using the hardcoded fallback or is missing.")
425
- iface.launch(debug=True) # Set debug=False for production or normal HF Space operation
 
 
 
 
 
 
 
4
  import os
5
  import re
6
  import random
7
+ from dotenv import load_dotenv # For local testing with a .env file
8
  from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
9
  import torch
10
  import gradio as gr
11
  import time
12
 
 
 
 
13
  # --- Configuration ---
14
+ load_dotenv() # Loads HF_TOKEN and TMDB_API_KEY from .env for local testing
15
+
16
+ # SECRETS - These will be read from Hugging Face Space Secrets when deployed
17
+ TMDB_API_KEY = os.environ.get("TMDB_API_KEY")
18
+ HF_TOKEN = os.environ.get("HF_TOKEN") # Essential for gated models like ALLaM
19
 
20
+ MODEL_NAME = "ALLaM-AI/ALLaM-7B-Instruct-preview" # Target ALLaM model
 
21
 
22
  BASE_TMDB_URL = "https://api.themoviedb.org/3"
23
  POSTER_BASE_URL = "https://image.tmdb.org/t/p/w500"
24
  NUM_RECOMMENDATIONS_TO_DISPLAY = 5
25
  MIN_RATING_FOR_SEED = 3.5
26
+ MIN_VOTE_COUNT_TMDB = 100 # Minimum votes on TMDB for a movie to be considered
27
 
28
+ # --- Global Variables for Data & Model (Load once) ---
29
  df_profile_global = None
30
  df_watchlist_global = None
31
  df_reviews_global = None
32
  df_diary_global = None
33
  df_ratings_global = None
34
+ df_watched_global = None # This will be a consolidated df
35
 
36
  uri_to_movie_map_global = {}
37
  all_watched_titles_global = set()
 
46
  def clean_html(raw_html):
47
  if pd.isna(raw_html) or raw_html is None: return ""
48
  text = str(raw_html)
49
+ text = re.sub(r'<br\s*/?>', '\n', text) # Convert <br> to newlines
50
  soup = BeautifulSoup(text, "html.parser")
51
  return soup.get_text(separator=" ", strip=True)
52
 
 
65
  year = int(row['Year'])
66
  uri_map[uri] = (str(row['Name']), year)
67
  processed_uris.add(uri)
68
+ except ValueError:
69
+ # Silently skip if year is not a valid integer for URI mapping
70
+ pass
71
  return uri_map
72
 
73
  def load_all_data():
 
76
  global watchlist_titles_global, favorite_film_details_global, seed_movies_global
77
 
78
  try:
79
+ # Assumes CSV files are in the root of the Hugging Face Space
80
  df_profile_global = pd.read_csv("profile.csv")
81
+ # df_comments_global = pd.read_csv("comments.csv") # Not directly used in recs logic
82
  df_watchlist_global = pd.read_csv("watchlist.csv")
83
  df_reviews_global = pd.read_csv("reviews.csv")
84
  df_diary_global = pd.read_csv("diary.csv")
85
  df_ratings_global = pd.read_csv("ratings.csv")
86
+ _df_watched_log = pd.read_csv("watched.csv") # Raw log of watched films
87
  except FileNotFoundError as e:
88
+ print(f"CRITICAL ERROR: CSV file not found: {e}. Ensure all CSVs are uploaded to the HF Space root.")
89
+ return False # Indicate failure to load data
90
 
91
  dfs_for_uri_map = {
92
  "reviews.csv": df_reviews_global, "diary.csv": df_diary_global,
 
116
  consolidated.drop(columns=['Rating_simple'], inplace=True)
117
 
118
  watched_log_subset = _df_watched_log[['Letterboxd URI', 'Name', 'Year']].copy()
119
+ watched_log_subset['from_watched_log'] = True
120
  consolidated = pd.merge(consolidated, watched_log_subset, on=['Letterboxd URI', 'Name', 'Year'], how='outer')
 
 
 
121
  consolidated['from_watched_log'] = consolidated['from_watched_log'].fillna(False).astype(bool)
122
 
123
 
124
  consolidated['Review Text'] = consolidated['Review Text'].fillna('').apply(clean_html)
125
  consolidated['Year'] = pd.to_numeric(consolidated['Year'], errors='coerce').astype('Int64')
126
+ consolidated.dropna(subset=['Name', 'Year'], inplace=True) # Ensure essential fields are present
127
  consolidated.drop_duplicates(subset=['Name', 'Year'], keep='first', inplace=True)
128
  df_watched_global = consolidated
129
 
 
141
  except ValueError: pass
142
 
143
  favorite_film_details_global = []
144
+ if df_profile_global is not None and 'Favorite Films' in df_profile_global.columns and not df_profile_global.empty:
145
  fav_uris_str = df_profile_global.iloc[0]['Favorite Films']
146
  if pd.notna(fav_uris_str):
147
  fav_uris = [uri.strip() for uri in fav_uris_str.split(',')]
 
154
  favorite_film_details_global.append({'name': name, 'year': year, 'rating': rating, 'review_text': review, 'uri': uri})
155
 
156
  seed_movies_global.extend(favorite_film_details_global)
157
+ if not df_watched_global.empty: # Ensure df_watched_global is not empty
158
+ highly_rated_df = df_watched_global[df_watched_global['Rating'] >= MIN_RATING_FOR_SEED]
159
+ favorite_uris = {fav['uri'] for fav in favorite_film_details_global if 'uri' in fav}
160
+ for _, row in highly_rated_df.iterrows():
161
+ if row['Letterboxd URI'] not in favorite_uris:
162
+ seed_movies_global.append({
163
+ 'name': row['Name'], 'year': row['Year'], 'rating': row['Rating'],
164
+ 'review_text': row['Review Text'], 'uri': row['Letterboxd URI']
165
+ })
166
+ if seed_movies_global: # Only process if seed_movies_global is not empty
167
+ temp_df = pd.DataFrame(seed_movies_global)
168
+ if not temp_df.empty:
169
+ temp_df.drop_duplicates(subset=['name', 'year'], keep='first', inplace=True)
170
+ seed_movies_global = temp_df.to_dict('records')
171
  else:
172
+ seed_movies_global = []
173
 
174
  random.shuffle(seed_movies_global)
175
  return True
176
 
177
  def initialize_llm():
178
  global llm_pipeline, llm_tokenizer
179
+ if llm_pipeline is None: # Proceed only if pipeline is not already initialized
180
+ print(f"Attempting to initialize LLM: {MODEL_NAME}")
181
  if not HF_TOKEN:
182
+ print("CRITICAL ERROR: HF_TOKEN environment variable not set. Cannot access gated model.")
183
+ return # Stop initialization if token is missing
 
 
184
 
185
  try:
186
+ llm_tokenizer = AutoTokenizer.from_pretrained(
187
+ MODEL_NAME,
188
+ trust_remote_code=True,
189
+ token=HF_TOKEN,
190
+ use_fast=False # Using slow tokenizer as per previous debugging for SentencePiece
191
+ )
192
+ print(f"Tokenizer for {MODEL_NAME} loaded.")
193
+
194
  model = AutoModelForCausalLM.from_pretrained(
195
  MODEL_NAME,
196
  torch_dtype=torch.float16,
197
+ device_map="auto", # Automatically map to available device
198
+ load_in_8bit=True, # Enable 8-bit quantization; requires bitsandbytes
199
  trust_remote_code=True,
200
  token=HF_TOKEN
201
  )
202
+ print(f"Model {MODEL_NAME} loaded.")
203
+
204
  if llm_tokenizer.pad_token is None:
205
+ print("Tokenizer pad_token is None, setting to eos_token.")
206
  llm_tokenizer.pad_token = llm_tokenizer.eos_token
207
+ if model.config.pad_token_id is None: # Also update model config if needed
208
+ model.config.pad_token_id = model.config.eos_token_id
209
+ print(f"Model config pad_token_id set to: {model.config.pad_token_id}")
210
 
211
  llm_pipeline = pipeline(
212
+ "text-generation",
213
+ model=model,
214
+ tokenizer=llm_tokenizer
215
  )
216
+ print(f"LLM pipeline for {MODEL_NAME} initialized successfully.")
217
  except Exception as e:
218
+ print(f"ERROR during LLM initialization ({MODEL_NAME}): {e}")
219
+ # Ensure these are reset if initialization fails partway
220
  llm_pipeline = None
221
+ llm_tokenizer = None
222
 
223
  # --- TMDB API Functions ---
224
  def search_tmdb_movie_details(title, year):
225
+ if not TMDB_API_KEY:
226
+ print("CRITICAL ERROR: TMDB_API_KEY not configured.")
227
  return None
228
  try:
229
  search_url = f"{BASE_TMDB_URL}/search/movie"
 
246
  'vote_average': movie.get('vote_average'), 'vote_count': movie.get('vote_count'),
247
  'popularity': movie.get('popularity')
248
  }
249
+ time.sleep(0.3) # Slightly increased delay for API calls
250
+ except requests.RequestException as e: print(f"TMDB API Error (search) for {title} ({year}): {e}")
251
+ except Exception as ex: print(f"Unexpected error in TMDB search for {title} ({year}): {ex}")
252
  return None
253
 
254
  def get_tmdb_recommendations(movie_id, page=1):
255
+ if not TMDB_API_KEY:
256
+ print("CRITICAL ERROR: TMDB_API_KEY not configured.")
257
  return []
258
  recommendations = []
259
  try:
 
272
  'vote_average': movie.get('vote_average'), 'vote_count': movie.get('vote_count'),
273
  'popularity': movie.get('popularity')
274
  })
275
+ time.sleep(0.3) # Slightly increased delay
276
+ except requests.RequestException as e: print(f"TMDB API Error (recommendations) for movie ID {movie_id}: {e}")
277
+ except Exception as ex: print(f"Unexpected error in TMDB recommendations for movie ID {movie_id}: {ex}")
278
  return recommendations
279
 
280
  # --- LLM Explanation ---
281
  def generate_saudi_explanation(recommended_movie_title, seed_movie_title, seed_movie_context=""):
282
  global llm_pipeline, llm_tokenizer
283
  if llm_pipeline is None or llm_tokenizer is None:
284
+ print("LLM pipeline or tokenizer not available for explanation generation.")
285
+ return "للأسف، نموذج الذكاء الاصطناعي مو جاهز حالياً. حاول مرة ثانية بعد شوي."
286
 
287
  max_context_len = 150
288
  seed_movie_context_short = (seed_movie_context[:max_context_len] + "...") if len(seed_movie_context) > max_context_len else seed_movie_context
289
 
290
+ # Assuming ALLaM-Instruct uses a Llama-like prompt format.
291
+ # ALWAYS verify this on the model card for `ALLaM-AI/ALLaM-7B-Instruct-preview`.
292
  prompt_template = f"""<s>[INST] أنت ناقد أفلام سعودي خبير ودمك خفيف جداً. مهمتك هي كتابة توصية لفيلم جديد بناءً على فيلم سابق أعجب المستخدم.
293
  المستخدم أعجب بالفيلم هذا: "{seed_movie_title}".
294
  وكان تعليقه أو سبب إعجابه (إذا متوفر): "{seed_movie_context_short}"
 
309
  prompt_template, do_sample=True, top_k=20, top_p=0.9, num_return_sequences=1,
310
  eos_token_id=llm_tokenizer.eos_token_id,
311
  pad_token_id=llm_tokenizer.pad_token_id if llm_tokenizer.pad_token_id is not None else llm_tokenizer.eos_token_id,
312
+ max_new_tokens=160 # Increased slightly more
313
  )
314
  explanation = sequences[0]['generated_text'].split("[/INST]")[-1].strip()
315
  explanation = explanation.replace("<s>", "").replace("</s>", "").strip()
 
317
  explanation = re.sub(r"كنموذج لغوي.*?\s*,?\s*", "", explanation, flags=re.IGNORECASE)
318
 
319
  if not explanation or explanation.lower().startswith("أنت ناقد أفلام") or len(explanation) < 20 :
320
+ print(f"LLM explanation for '{recommended_movie_title}' was too short or poor. Falling back.")
321
  return f"شكلك بتنبسط ع��ى فيلم '{recommended_movie_title}' لأنه يشبه جو فيلم '{seed_movie_title}' اللي حبيته! عطيه تجربة."
322
  return explanation
323
  except Exception as e:
324
+ print(f"ERROR during LLM generation with {MODEL_NAME}: {e}")
325
  return f"يا كابتن، شكلك بتحب '{recommended_movie_title}'، خاصة إنك استمتعت بـ'{seed_movie_title}'. جربه وعطنا رأيك!"
326
 
327
  # --- Recommendation Logic ---
328
+ def get_recommendations(progress=gr.Progress(track_tqdm=True)):
 
 
329
  if not TMDB_API_KEY:
330
+ return "<p style='color:red; text-align:right;'>خطأ: مفتاح TMDB API مو موجود أو غير صحيح. الرجاء التأكد من إضافته كـ Secret بشكل صحيح في إعدادات الـ Space.</p>"
331
+ if not all([df_profile_global is not None, df_watched_global is not None, seed_movies_global is not None]): # seed_movies_global can be empty list
332
+ return "<p style='color:red; text-align:right;'>خطأ: فشل في تحميل بيانات المستخدم. تأكد من رفع ملفات CSV بشكل صحيح.</p>"
333
 
334
+ if llm_pipeline is None: # Ensure LLM is ready
335
+ initialize_llm() # Try to initialize if it wasn't at startup
336
+ if llm_pipeline is None:
337
+ return "<p style='color:red; text-align:right;'>خطأ: فشل في تهيئة نموذج الذكاء الاصطناعي. تأكد من وجود HF_TOKEN صحيح وأن لديك صلاحية الوصول للنموذج المحدد.</p>"
338
+
339
+ if not seed_movies_global: # Check if seed_movies list is empty after loading
340
+ return "<p style='text-align:right;'>ما لقينا أفلام مفضلة أو مقيمة تقييم عالي كفاية عشان نبني عليها توصيات. حاول تقيّم بعض الأفلام!</p>"
341
 
342
  progress(0.1, desc="نجمع أفلامك المفضلة...")
343
  potential_recs = {}
344
+ # Limit number of seeds to process to avoid excessive API calls / long processing
345
+ seeds_to_process = seed_movies_global[:20] if len(seed_movies_global) > 20 else seed_movies_global
346
 
347
  for i, seed_movie in enumerate(seeds_to_process):
348
+ progress(0.1 + (i / len(seeds_to_process)) * 0.4, desc=f"نبحث عن توصيات بناءً على: {seed_movie.get('name', 'فيلم غير معروف')}")
349
+ seed_tmdb_details = search_tmdb_movie_details(seed_movie.get('name'), seed_movie.get('year'))
350
  if seed_tmdb_details and seed_tmdb_details.get('id'):
351
  tmdb_recs = get_tmdb_recommendations(seed_tmdb_details['id'])
352
  for rec in tmdb_recs:
353
  try:
354
+ # Ensure year is a valid integer for tuple creation
355
+ year_val = int(rec['year']) if rec.get('year') and str(rec['year']).isdigit() else None
356
+ if year_val is None: continue # Skip if year is invalid
357
+
358
+ rec_tuple = (str(rec['title']), year_val)
359
  if rec.get('id') and rec_tuple not in all_watched_titles_global and rec_tuple not in watchlist_titles_global:
360
+ if rec['id'] not in potential_recs: # Add if new
361
  potential_recs[rec['id']] = {
362
+ 'movie_info': rec,
363
+ 'seed_movie_title': seed_movie.get('name'),
364
  'seed_movie_context': seed_movie.get('review_text', '') or seed_movie.get('comment_text', '')
365
  }
366
+ except (ValueError, TypeError) as e:
367
+ # print(f"Skipping recommendation due to data issue: {rec.get('title')} - {e}")
368
+ continue
369
  if not potential_recs:
370
+ return "<p style='text-align:right;'>ما لقينا توصيات جديدة لك حالياً بناءً على أفلامك المفضلة. يمكن شفت كل شيء رهيب! 😉</p>"
371
 
372
+ # Sort recommendations by TMDB popularity
373
  sorted_recs_list = sorted(potential_recs.values(), key=lambda x: x['movie_info'].get('popularity', 0), reverse=True)
374
+
375
  final_recommendations_data = []
376
  displayed_ids = set()
377
  for rec_data in sorted_recs_list:
 
379
  if rec_data['movie_info']['id'] not in displayed_ids:
380
  final_recommendations_data.append(rec_data)
381
  displayed_ids.add(rec_data['movie_info']['id'])
382
+
383
  if not final_recommendations_data:
384
+ return "<p style='text-align:right;'>ما لقينا توصيات جديدة لك حالياً بعد الفلترة. يمكن شفت كل شيء رهيب! 😉</p>"
385
 
386
+ output_html = "<div style='padding: 10px;'>" # Main container with some padding
387
  progress(0.6, desc="نجهز لك الشرح باللغة العامية...")
388
+
389
  for i, rec_data in enumerate(final_recommendations_data):
390
  progress(0.6 + (i / len(final_recommendations_data)) * 0.4, desc=f"نكتب شرح لفيلم: {rec_data['movie_info']['title']}")
391
  explanation = generate_saudi_explanation(
392
  rec_data['movie_info']['title'], rec_data['seed_movie_title'], rec_data['seed_movie_context']
393
  )
394
  poster_url = rec_data['movie_info']['poster_path']
395
+ # Fallback for missing posters
396
+ if not poster_url or "No+Poster" in poster_url or "placeholder.com" in poster_url :
397
+ poster_url = f"https://via.placeholder.com/300x450.png?text={requests.utils.quote(rec_data['movie_info']['title'])}"
398
+
399
  output_html += f"""
400
+ <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; box-shadow: 0 2px 4px rgba(0,0,0,0.05);">
401
  <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);">
402
  <div style="text-align: right; direction: rtl; flex-grow: 1;">
403
  <h3 style="margin-top:0; color: #c70039;">{rec_data['movie_info']['title']} ({rec_data['movie_info']['year']})</h3>
404
  <p style="font-size: 1.1em; color: #333; line-height: 1.6;">{explanation}</p>
405
+ <p style="font-size: 0.9em; color: #555; margin-top: 10px;"><em><strong style="color:#c70039;">السبب:</strong> حبيّت فيلم <strong style="color:#333;">{rec_data['seed_movie_title']}</strong></em></p>
406
  </div>
407
  </div>"""
408
  output_html += "</div>"
409
  return gr.HTML(output_html)
410
 
411
  # --- Gradio Interface ---
412
+ css_theme = """
413
  body { font-family: 'Tajawal', sans-serif; }
414
+ .gradio-container { font-family: 'Tajawal', sans-serif !important; direction: rtl; max-width: 900px !important; margin: auto !important; }
415
  footer { display: none !important; }
416
+ .gr-button { background-color: #c70039 !important; color: white !important; font-size: 1.2em !important; padding: 12px 24px !important; border-radius: 8px !important; font-weight: bold; }
417
+ .gr-button:hover { background-color: #a3002f !important; box-shadow: 0 2px 5px rgba(0,0,0,0.2); }
418
+ h1 { color: #900c3f !important; }
419
+ .gr-html-output h3 { color: #c70039 !important; } /* Style h3 within the HTML output specifically */
420
+ """
421
 
422
+ # Attempt to load data and LLM at startup
423
  data_loaded_successfully = load_all_data()
424
  if data_loaded_successfully:
425
+ print("User data loaded successfully.")
426
+ # LLM initialization will be attempted when the Gradio app starts,
427
+ # or on the first click if it failed at startup.
428
+ # initialize_llm() # Call it here to attempt loading at startup
429
  else:
430
+ print("CRITICAL: Failed to load user data. App functionality will be limited.")
431
 
432
+ # It's better to initialize LLM once the app blocks are defined,
433
+ # or trigger it on first use if it's very resource-intensive at startup.
434
+ # For Spaces, startup initialization is fine.
435
+
436
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="red", secondary_hue="pink", font=[gr.themes.GoogleFont("Tajawal"), "sans-serif"]), css=css_theme) as iface:
437
  gr.Markdown(
438
  """
439
+ <div style="text-align: center; margin-bottom:20px;">
440
+ <h1 style="color: #c70039; font-size: 2.8em; font-weight: bold; margin-bottom:5px;">🎬 رفيقك السينمائي 🍿</h1>
441
  <p style="font-size: 1.2em; color: #555;">يا هلا بك! اضغط الزر تحت وخلنا نعطيك توصيات أفلام على كيف كيفك، مع شرح بالعامية ليش ممكن تدخل مزاجك.</p>
442
  </div>"""
443
  )
444
+ recommend_button = gr.Button("عطني توصيات أفلام جديدة!")
445
+
446
+ with gr.Column(elem_id="recommendation-output-column"): # Added elem_id for potential specific styling
447
+ output_recommendations = gr.HTML(label="👇 توصياتك النارية وصلت 👇")
448
 
449
+ # Initialize LLM when the Blocks context is active, after data loading attempt
 
450
  if data_loaded_successfully:
451
+ initialize_llm()
452
 
453
+ recommend_button.click(fn=get_recommendations, inputs=None, outputs=[output_recommendations], show_progress="full")
454
+
455
  gr.Markdown(
456
  """
457
+ <div style="text-align: center; margin-top: 40px; padding-top: 20px; border-top: 1px solid #eee; font-size: 0.9em; color: #777;">
458
+ <p>نتمنى لك مشاهدة ممتعة مع رفيقك السينمائي! 🎥✨</p>
459
  </div>"""
460
  )
461
 
462
  if __name__ == "__main__":
463
+ # Print warnings if critical secrets are missing when running locally
464
+ if not TMDB_API_KEY:
465
+ print("\nCRITICAL WARNING: TMDB_API_KEY environment variable is NOT SET.")
466
+ print("TMDB API calls will fail. Please set it in your .env file or system environment.\n")
467
+ if not HF_TOKEN:
468
+ print("\nCRITICAL WARNING: HF_TOKEN environment variable is NOT SET.")
469
+ print(f"LLM initialization for gated models like {MODEL_NAME} will fail. Please set it.\n")
470
+
471
+ iface.launch(debug=True) # debug=True for local testing, set to False for production