Michtiii commited on
Commit
54ba5c0
Β·
verified Β·
1 Parent(s): 64b51e9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -40
app.py CHANGED
@@ -1,7 +1,6 @@
1
  # ==============================
2
  # πŸš– Uber Driver Recommendation System
3
- # Single File - Hugging Face Ready
4
- # ==============================
5
 
6
  import numpy as np
7
  import pandas as pd
@@ -14,14 +13,13 @@ from sklearn.ensemble import RandomForestRegressor
14
  # ------------------------------
15
  def generate_data(n=1000):
16
  np.random.seed(42)
17
- data = pd.DataFrame({
18
  "pickup_distance": np.random.uniform(0.5, 10, n),
19
  "trip_distance": np.random.uniform(1, 20, n),
20
  "fare": np.random.uniform(50, 500, n),
21
  "surge": np.random.choice([1, 1.5, 2], n),
22
  "rating": np.random.uniform(3, 5, n)
23
  })
24
- return data
25
 
26
  # ------------------------------
27
  # 2. Feature Engineering
@@ -29,11 +27,13 @@ def generate_data(n=1000):
29
  def feature_engineering(df):
30
  df = df.copy()
31
  df["earning_per_km"] = df["fare"] / (df["trip_distance"] + 1)
32
- df["efficiency"] = (df["fare"] * df["surge"]) / (df["pickup_distance"] + df["trip_distance"])
 
 
33
  return df
34
 
35
  # ------------------------------
36
- # 3. Model Training
37
  # ------------------------------
38
  def train_model():
39
  data = generate_data()
@@ -44,79 +44,84 @@ def train_model():
44
  X = data.drop("reward", axis=1)
45
  y = data["reward"]
46
 
47
- X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
48
 
49
- model = RandomForestRegressor(n_estimators=50)
50
  model.fit(X_train, y_train)
51
 
52
- return model
53
 
54
- model = train_model()
55
 
56
  # ------------------------------
57
- # 4. Ride Generator (Dynamic UI)
58
  # ------------------------------
59
- def generate_rides(base_pickup, base_trip, base_fare, base_surge):
60
  rides = []
61
  for _ in range(5):
62
  rides.append({
63
- "pickup_distance": base_pickup + np.random.uniform(-1, 1),
64
- "trip_distance": base_trip + np.random.uniform(-2, 2),
65
- "fare": base_fare + np.random.uniform(-50, 50),
66
- "surge": max(1, base_surge + np.random.choice([0, 0.5]))
 
67
  })
68
  return pd.DataFrame(rides)
69
 
70
  # ------------------------------
71
- # 5. Explainability Logic
72
  # ------------------------------
73
  def explain(row):
74
  reasons = []
 
75
  if row["fare"] > 300:
76
- reasons.append("High Fare πŸ’°")
77
  if row["pickup_distance"] < 3:
78
- reasons.append("Close Pickup πŸ“")
79
  if row["surge"] > 1:
80
- reasons.append("Surge Pricing ⚑")
81
  if row["trip_distance"] > 10:
82
- reasons.append("Long Trip πŸš—")
83
 
84
  return ", ".join(reasons) if reasons else "Balanced Ride"
85
 
86
  # ------------------------------
87
- # 6. Recommendation Engine
88
  # ------------------------------
89
  def recommend(pickup, trip, fare, surge):
90
  rides = generate_rides(pickup, trip, fare, surge)
91
  rides = feature_engineering(rides)
92
 
 
 
 
93
  scores = model.predict(rides)
94
  rides["score"] = scores
95
 
96
  rides = rides.sort_values(by="score", ascending=False).head(3)
97
 
98
- # Build dashboard output
99
  output = ""
100
- for i, row in rides.iterrows():
101
- explanation = explain(row)
102
- output += f"""
103
- πŸš– Ride Option
104
- Score: {round(row['score'],2)}
105
- Fare: β‚Ή{round(row['fare'],2)}
106
- Pickup Distance: {round(row['pickup_distance'],2)} km
107
- Trip Distance: {round(row['trip_distance'],2)} km
108
- Surge: {row['surge']}
109
- Why: {explanation}
110
- -------------------------
111
- """
112
  return output
113
 
114
  # ------------------------------
115
- # 7. Gradio UI
116
  # ------------------------------
117
  with gr.Blocks() as demo:
118
  gr.Markdown("## πŸš– Uber Driver Recommendation System")
119
- gr.Markdown("Get best rides based on smart AI scoring")
120
 
121
  with gr.Row():
122
  pickup = gr.Slider(0.5, 10, value=2, label="Pickup Distance (km)")
@@ -128,12 +133,19 @@ with gr.Blocks() as demo:
128
 
129
  btn = gr.Button("Get Recommendation")
130
 
131
- output = gr.Textbox(label="Top Ride Recommendations")
 
 
 
132
 
133
- btn.click(recommend, inputs=[pickup, trip, fare, surge], outputs=output)
 
 
 
 
134
 
135
  # ------------------------------
136
- # 8. Launch App
137
  # ------------------------------
138
  if __name__ == "__main__":
139
  demo.launch()
 
1
  # ==============================
2
  # πŸš– Uber Driver Recommendation System
3
+ # # ==============================
 
4
 
5
  import numpy as np
6
  import pandas as pd
 
13
  # ------------------------------
14
  def generate_data(n=1000):
15
  np.random.seed(42)
16
+ return pd.DataFrame({
17
  "pickup_distance": np.random.uniform(0.5, 10, n),
18
  "trip_distance": np.random.uniform(1, 20, n),
19
  "fare": np.random.uniform(50, 500, n),
20
  "surge": np.random.choice([1, 1.5, 2], n),
21
  "rating": np.random.uniform(3, 5, n)
22
  })
 
23
 
24
  # ------------------------------
25
  # 2. Feature Engineering
 
27
  def feature_engineering(df):
28
  df = df.copy()
29
  df["earning_per_km"] = df["fare"] / (df["trip_distance"] + 1)
30
+ df["efficiency"] = (df["fare"] * df["surge"]) / (
31
+ df["pickup_distance"] + df["trip_distance"]
32
+ )
33
  return df
34
 
35
  # ------------------------------
36
+ # 3. Train Model
37
  # ------------------------------
38
  def train_model():
39
  data = generate_data()
 
44
  X = data.drop("reward", axis=1)
45
  y = data["reward"]
46
 
47
+ X_train, _, y_train, _ = train_test_split(X, y, test_size=0.2, random_state=42)
48
 
49
+ model = RandomForestRegressor(n_estimators=50, random_state=42)
50
  model.fit(X_train, y_train)
51
 
52
+ return model, X.columns.tolist()
53
 
54
+ model, feature_columns = train_model()
55
 
56
  # ------------------------------
57
+ # 4. Generate Ride Options (FIXED)
58
  # ------------------------------
59
+ def generate_rides(pickup, trip, fare, surge):
60
  rides = []
61
  for _ in range(5):
62
  rides.append({
63
+ "pickup_distance": max(0.5, pickup + np.random.uniform(-1, 1)),
64
+ "trip_distance": max(1, trip + np.random.uniform(-2, 2)),
65
+ "fare": max(50, fare + np.random.uniform(-50, 50)),
66
+ "surge": min(2, max(1, surge + np.random.choice([0, 0.5]))),
67
+ "rating": np.random.uniform(3, 5) # βœ… FIX
68
  })
69
  return pd.DataFrame(rides)
70
 
71
  # ------------------------------
72
+ # 5. Explanation Logic
73
  # ------------------------------
74
  def explain(row):
75
  reasons = []
76
+
77
  if row["fare"] > 300:
78
+ reasons.append("High Fare")
79
  if row["pickup_distance"] < 3:
80
+ reasons.append("Close Pickup")
81
  if row["surge"] > 1:
82
+ reasons.append("Surge Benefit")
83
  if row["trip_distance"] > 10:
84
+ reasons.append("Long Trip")
85
 
86
  return ", ".join(reasons) if reasons else "Balanced Ride"
87
 
88
  # ------------------------------
89
+ # 6. Recommendation Engine (FIXED)
90
  # ------------------------------
91
  def recommend(pickup, trip, fare, surge):
92
  rides = generate_rides(pickup, trip, fare, surge)
93
  rides = feature_engineering(rides)
94
 
95
+ # βœ… Ensure feature consistency
96
+ rides = rides[feature_columns]
97
+
98
  scores = model.predict(rides)
99
  rides["score"] = scores
100
 
101
  rides = rides.sort_values(by="score", ascending=False).head(3)
102
 
103
+ # βœ… Clean UI Output
104
  output = ""
105
+ for idx, row in rides.iterrows():
106
+ output += (
107
+ f"πŸš– Ride Option\n"
108
+ f"Score: {round(row['score'], 2)}\n"
109
+ f"Fare: β‚Ή{round(row['fare'], 2)}\n"
110
+ f"Pickup: {round(row['pickup_distance'], 2)} km\n"
111
+ f"Trip: {round(row['trip_distance'], 2)} km\n"
112
+ f"Surge: {row['surge']}\n"
113
+ f"Why: {explain(row)}\n"
114
+ f"-----------------------------\n"
115
+ )
116
+
117
  return output
118
 
119
  # ------------------------------
120
+ # 7. Gradio UI (STABLE)
121
  # ------------------------------
122
  with gr.Blocks() as demo:
123
  gr.Markdown("## πŸš– Uber Driver Recommendation System")
124
+ gr.Markdown("AI-based smart ride selection")
125
 
126
  with gr.Row():
127
  pickup = gr.Slider(0.5, 10, value=2, label="Pickup Distance (km)")
 
133
 
134
  btn = gr.Button("Get Recommendation")
135
 
136
+ output = gr.Textbox(
137
+ label="Top Ride Recommendations",
138
+ lines=15
139
+ )
140
 
141
+ btn.click(
142
+ fn=recommend,
143
+ inputs=[pickup, trip, fare, surge],
144
+ outputs=output
145
+ )
146
 
147
  # ------------------------------
148
+ # 8. Launch
149
  # ------------------------------
150
  if __name__ == "__main__":
151
  demo.launch()