Sazzz02 commited on
Commit
9d2e560
·
verified ·
1 Parent(s): b0434f5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +9 -7
app.py CHANGED
@@ -5,6 +5,7 @@ import pickle
5
  from haversine import haversine, Unit
6
  from sklearn.preprocessing import LabelEncoder
7
  import matplotlib.pyplot as plt
 
8
 
9
  # --- Function to load data and model (cached for performance) ---
10
  def load_data_and_model():
@@ -14,7 +15,7 @@ def load_data_and_model():
14
  train_customers = pd.read_csv('train_customers.csv')
15
  train_locations = pd.read_csv('train_locations.csv')
16
 
17
- # --- FIX: Convert 'id' column to string to avoid ValueError ---
18
  vendors['id'] = vendors['id'].astype(str)
19
 
20
  with open('restaurant_recommender_model.pkl', 'rb') as f:
@@ -25,17 +26,19 @@ def load_data_and_model():
25
  vendors['vendor_category_encoded'] = le.fit_transform(vendors['vendor_category_en'])
26
 
27
  train_customers['dob'] = pd.to_datetime(train_customers['dob'], errors='coerce')
 
28
  train_customers['age'] = (pd.to_datetime('now', utc=True) - train_customers['dob'].dt.tz_localize('UTC')).dt.days / 365.25
29
  train_customers['age'] = train_customers['age'].fillna(train_customers['age'].median())
30
 
31
  return vendors, train_customers, train_locations, model
32
  except FileNotFoundError as e:
 
33
  return None, None, None, e
34
 
35
  # Load data and model once
36
  vendors, customers, locations, model = load_data_and_model()
37
  if vendors is None:
38
- raise FileNotFoundError("Please ensure all data files and the model file are in the same directory.")
39
 
40
  # --- Core Function for What-If Analysis ---
41
  def run_what_if_analysis(selected_vendor_id):
@@ -67,7 +70,7 @@ def run_what_if_analysis(selected_vendor_id):
67
  hypo_score = base_score
68
 
69
  # Create a simple bar chart
70
- fig, ax = plt.subplots(facecolor='#FFFFFF') # Set background to white
71
  scores = [base_score, hypo_score]
72
  labels = ['Current', 'Hypothetical']
73
  ax.bar(labels, scores, color=['#7FD2C8', '#FF9F9F'])
@@ -128,7 +131,7 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
128
  with gr.Column(scale=1):
129
  vendor_dropdown = gr.Dropdown(vendors['id'].unique(), label="Select Your Restaurant ID", info="Choose your restaurant from the list.")
130
  with gr.Column(scale=2):
131
- gr.Image("https://i.imgur.com/5SgBv1S.png", container=False) # A food-themed image to enhance the UI
132
 
133
  gr.Markdown("---")
134
 
@@ -136,8 +139,8 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
136
  gr.Markdown("### Simulate changes to your restaurant's details and see the predicted impact on your recommendation score.")
137
 
138
  with gr.Row():
139
- rating_slider = gr.Slider(0, 5, value=4.0, step=0.1, label="Vendor Rating", info="What if your rating increased or decreased?")
140
- delivery_charge_slider = gr.Slider(0, 20, value=5, step=1, label="Delivery Charge ($)", info="How does a price change affect your visibility?")
141
 
142
  with gr.Row():
143
  btn_what_if = gr.Button("Run What-If Analysis", variant="primary")
@@ -148,7 +151,6 @@ with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
148
 
149
  gr.Plot(label="Score Comparison", elem_id="plot_what_if")
150
 
151
- # We only pass the vendor ID, as the other sliders are just for visual demonstration
152
  btn_what_if.click(
153
  fn=run_what_if_analysis,
154
  inputs=[vendor_dropdown],
 
5
  from haversine import haversine, Unit
6
  from sklearn.preprocessing import LabelEncoder
7
  import matplotlib.pyplot as plt
8
+ import os
9
 
10
  # --- Function to load data and model (cached for performance) ---
11
  def load_data_and_model():
 
15
  train_customers = pd.read_csv('train_customers.csv')
16
  train_locations = pd.read_csv('train_locations.csv')
17
 
18
+ # --- FIX: Ensure 'id' column is a string to avoid Gradio error ---
19
  vendors['id'] = vendors['id'].astype(str)
20
 
21
  with open('restaurant_recommender_model.pkl', 'rb') as f:
 
26
  vendors['vendor_category_encoded'] = le.fit_transform(vendors['vendor_category_en'])
27
 
28
  train_customers['dob'] = pd.to_datetime(train_customers['dob'], errors='coerce')
29
+ # Use a consistent timezone-aware approach for accurate age calculation
30
  train_customers['age'] = (pd.to_datetime('now', utc=True) - train_customers['dob'].dt.tz_localize('UTC')).dt.days / 365.25
31
  train_customers['age'] = train_customers['age'].fillna(train_customers['age'].median())
32
 
33
  return vendors, train_customers, train_locations, model
34
  except FileNotFoundError as e:
35
+ gr.Warning(f"File not found: {e}. Please ensure all data files and the model file are in the same directory.")
36
  return None, None, None, e
37
 
38
  # Load data and model once
39
  vendors, customers, locations, model = load_data_and_model()
40
  if vendors is None:
41
+ raise FileNotFoundError("Application cannot start. Required files are missing.")
42
 
43
  # --- Core Function for What-If Analysis ---
44
  def run_what_if_analysis(selected_vendor_id):
 
70
  hypo_score = base_score
71
 
72
  # Create a simple bar chart
73
+ fig, ax = plt.subplots(facecolor='#FFFFFF')
74
  scores = [base_score, hypo_score]
75
  labels = ['Current', 'Hypothetical']
76
  ax.bar(labels, scores, color=['#7FD2C8', '#FF9F9F'])
 
131
  with gr.Column(scale=1):
132
  vendor_dropdown = gr.Dropdown(vendors['id'].unique(), label="Select Your Restaurant ID", info="Choose your restaurant from the list.")
133
  with gr.Column(scale=2):
134
+ gr.Image("https://i.imgur.com/5SgBv1S.png", container=False)
135
 
136
  gr.Markdown("---")
137
 
 
139
  gr.Markdown("### Simulate changes to your restaurant's details and see the predicted impact on your recommendation score.")
140
 
141
  with gr.Row():
142
+ rating_slider = gr.Slider(0, 5, value=4.0, step=0.1, label="Vendor Rating", info="What if your rating increased or decreased?", interactive=False)
143
+ delivery_charge_slider = gr.Slider(0, 20, value=5, step=1, label="Delivery Charge ($)", info="How does a price change affect your visibility?", interactive=False)
144
 
145
  with gr.Row():
146
  btn_what_if = gr.Button("Run What-If Analysis", variant="primary")
 
151
 
152
  gr.Plot(label="Score Comparison", elem_id="plot_what_if")
153
 
 
154
  btn_what_if.click(
155
  fn=run_what_if_analysis,
156
  inputs=[vendor_dropdown],