Sahithi27 commited on
Commit
d1930da
·
verified ·
1 Parent(s): a88a052

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -66
app.py CHANGED
@@ -1,95 +1,101 @@
1
- # app.py — Hugging Face / Gradio app for Dynamic Pricing (holiday+festival aware)
2
  import gradio as gr
3
  import joblib
4
  import pandas as pd
5
  import numpy as np
6
- import os
7
- import math
8
 
9
- # ---------- Load artifact (model + features) ----------
 
 
10
  ARTIFACT_PATH = "dynamic_pricing_artifact.joblib"
11
 
12
- if not os.path.exists(ARTIFACT_PATH):
13
- raise FileNotFoundError(f"Artifact not found: {ARTIFACT_PATH}. Upload dynamic_pricing_artifact.joblib to the repo root.")
14
-
15
  artifact = joblib.load(ARTIFACT_PATH)
16
  model = artifact["model"]
17
  FEATURES = artifact["features"]
18
 
19
- # ---------- Helper: build row and predict ----------
20
- def predict_from_inputs_dict(input_dict, artifact):
21
- """
22
- Build DataFrame row matching artifact['features'] order and predict surge.
23
- input_dict must contain numeric values for keys used below.
24
- """
25
- model = artifact["model"]
26
- FEATURES = artifact["features"]
 
 
 
27
 
28
- # initialize a row dict with zeros
29
  row = {f: 0.0 for f in FEATURES}
30
 
31
- # copy available numeric inputs into row (safely)
32
- for k, v in input_dict.items():
33
- if k in row:
34
- try:
35
- row[k] = float(v)
36
- except Exception:
37
- row[k] = 0.0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- # ensure demand_supply_ratio computed consistently
40
- demand_val = float(input_dict.get("demand", row.get("demand", 1.0)))
41
- supply_val = float(input_dict.get("supply", row.get("supply", 1.0)))
42
- row["demand_supply_ratio"] = float(np.clip(demand_val / (supply_val + 1.0), 0.0, 10.0))
43
 
44
- # create DataFrame in exact order
45
  df_row = pd.DataFrame([[row[f] for f in FEATURES]], columns=FEATURES)
46
 
47
- # predict surge
48
  surge = float(model.predict(df_row)[0])
49
 
50
- # base_price = EXACT user-entered base_fare (do not recalc)
51
- base_price = float(input_dict.get("base_fare", row.get("base_fare", 30.0)))
52
  final_price = base_price * surge
53
 
54
- return base_price, surge, final_price
55
 
56
- # ---------- Gradio prediction wrapper ----------
57
- def gh_predict(
58
- zone_id, demand, supply, driver_availability, weather_factor, event_factor,
59
- temperature, traffic_index, distance_km, duration_min, base_fare,
60
- hour, day_of_week, is_weekend, month, is_holiday, is_festival,
61
- season_autumn, season_monsoon, season_summer, season_winter
62
- ):
63
- inp = {
64
- "zone_id": zone_id, "demand": demand, "supply": supply, "driver_availability": driver_availability,
65
- "weather_factor": weather_factor, "event_factor": event_factor, "temperature": temperature, "traffic_index": traffic_index,
66
- "distance_km": distance_km, "duration_min": duration_min, "base_fare": base_fare,
67
- "hour": hour, "day_of_week": day_of_week, "is_weekend": is_weekend,
68
- "month": month, "is_holiday": is_holiday, "is_festival": is_festival,
69
- "season_autumn": season_autumn, "season_monsoon": season_monsoon, "season_summer": season_summer, "season_winter": season_winter
70
- }
71
- base_price, surge, final_price = predict_from_inputs_dict(inp, artifact)
72
- return round(base_price, 2), round(surge, 4), round(final_price, 2)
73
 
74
- # ---------- Gradio UI elements ----------
 
 
75
  inputs = [
76
  gr.Number(label="Zone ID", value=1),
77
  gr.Number(label="Demand", value=150),
78
  gr.Number(label="Supply", value=80),
79
  gr.Number(label="Driver Availability", value=60),
80
- gr.Number(label="Weather Factor (1.0–1.35)", value=1.0),
81
- gr.Number(label="Event Factor (1.0–1.5)", value=1.0),
82
- gr.Number(label="Temperature °C", value=30),
83
  gr.Number(label="Traffic Index (0–1)", value=0.5),
84
  gr.Number(label="Distance (km)", value=10),
85
  gr.Number(label="Duration (min)", value=20),
86
- gr.Number(label="Base Fare (exact input used)", value=120),
87
  gr.Number(label="Hour (0–23)", value=18),
88
  gr.Number(label="Day of Week (0=Mon)", value=4),
89
  gr.Number(label="Is Weekend? (0/1)", value=0),
90
  gr.Number(label="Month (1–12)", value=11),
91
- gr.Number(label="Is Holiday (0/1)", value=0),
92
- gr.Number(label="Is Festival (0/1)", value=0),
93
  gr.Number(label="Season Autumn (0/1)", value=0),
94
  gr.Number(label="Season Monsoon (0/1)", value=0),
95
  gr.Number(label="Season Summer (0/1)", value=1),
@@ -98,20 +104,16 @@ inputs = [
98
 
99
  outputs = [
100
  gr.Number(label="Base Price"),
101
- gr.Number(label="Predicted Surge Factor"),
102
  gr.Number(label="Final Dynamic Price")
103
  ]
104
 
105
- demo = gr.Interface(
106
- fn=gh_predict,
107
  inputs=inputs,
108
  outputs=outputs,
109
- title="Dynamic Pricing Model (Holiday & Festival Aware)",
110
- description="Base price is used exactly as entered. Final = base_price * predicted_surge. Make sure 'dynamic_pricing_artifact.joblib' is uploaded."
111
  )
112
 
113
- # ---------- Launch app ----------
114
- if __name__ == "__main__":
115
- # in HF Spaces set debug=False (default). In local use demo.launch(share=True) if needed.
116
- demo.launch()
117
-
 
 
1
  import gradio as gr
2
  import joblib
3
  import pandas as pd
4
  import numpy as np
 
 
5
 
6
+ # ==========================
7
+ # Load Artifact
8
+ # ==========================
9
  ARTIFACT_PATH = "dynamic_pricing_artifact.joblib"
10
 
 
 
 
11
  artifact = joblib.load(ARTIFACT_PATH)
12
  model = artifact["model"]
13
  FEATURES = artifact["features"]
14
 
15
+ # ==========================
16
+ # Prediction Logic
17
+ # ==========================
18
+ def predict_price(
19
+ zone_id, demand, supply, driver_availability,
20
+ weather_factor, event_factor, temperature, traffic_index,
21
+ distance_km, duration_min, base_fare,
22
+ hour, day_of_week, is_weekend,
23
+ month, is_holiday, is_festival,
24
+ season_autumn, season_monsoon, season_summer, season_winter
25
+ ):
26
 
27
+ # Build input row
28
  row = {f: 0.0 for f in FEATURES}
29
 
30
+ # Fill user values
31
+ input_dict = {
32
+ "zone_id": zone_id,
33
+ "demand": demand,
34
+ "supply": supply,
35
+ "driver_availability": driver_availability,
36
+ "weather_factor": weather_factor,
37
+ "event_factor": event_factor,
38
+ "temperature": temperature,
39
+ "traffic_index": traffic_index,
40
+ "distance_km": distance_km,
41
+ "duration_min": duration_min,
42
+ "base_fare": base_fare,
43
+ "hour": hour,
44
+ "day_of_week": day_of_week,
45
+ "is_weekend": is_weekend,
46
+ "month": month,
47
+ "is_holiday": is_holiday,
48
+ "is_festival": is_festival,
49
+ "season_autumn": season_autumn,
50
+ "season_monsoon": season_monsoon,
51
+ "season_summer": season_summer,
52
+ "season_winter": season_winter
53
+ }
54
+
55
+ # Fill row with user inputs
56
+ for key, val in input_dict.items():
57
+ if key in row:
58
+ row[key] = float(val)
59
 
60
+ # Auto compute demand_supply_ratio
61
+ row["demand_supply_ratio"] = float(
62
+ np.clip(row["demand"] / (row["supply"] + 1), 0, 10)
63
+ )
64
 
65
+ # Convert to dataframe
66
  df_row = pd.DataFrame([[row[f] for f in FEATURES]], columns=FEATURES)
67
 
68
+ # Model prediction
69
  surge = float(model.predict(df_row)[0])
70
 
71
+ # Final price
72
+ base_price = base_fare
73
  final_price = base_price * surge
74
 
75
+ return round(base_price, 2), round(surge, 3), round(final_price, 2)
76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
+ # ==========================
79
+ # Build UI
80
+ # ==========================
81
  inputs = [
82
  gr.Number(label="Zone ID", value=1),
83
  gr.Number(label="Demand", value=150),
84
  gr.Number(label="Supply", value=80),
85
  gr.Number(label="Driver Availability", value=60),
86
+ gr.Number(label="Weather Factor (1–1.35)", value=1.0),
87
+ gr.Number(label="Event Factor (1–1.5)", value=1.0),
88
+ gr.Number(label="Temperature (°C)", value=30),
89
  gr.Number(label="Traffic Index (0–1)", value=0.5),
90
  gr.Number(label="Distance (km)", value=10),
91
  gr.Number(label="Duration (min)", value=20),
92
+ gr.Number(label="Base Fare", value=120),
93
  gr.Number(label="Hour (0–23)", value=18),
94
  gr.Number(label="Day of Week (0=Mon)", value=4),
95
  gr.Number(label="Is Weekend? (0/1)", value=0),
96
  gr.Number(label="Month (1–12)", value=11),
97
+ gr.Number(label="Is Holiday? (0/1)", value=0),
98
+ gr.Number(label="Is Festival? (0/1)", value=0),
99
  gr.Number(label="Season Autumn (0/1)", value=0),
100
  gr.Number(label="Season Monsoon (0/1)", value=0),
101
  gr.Number(label="Season Summer (0/1)", value=1),
 
104
 
105
  outputs = [
106
  gr.Number(label="Base Price"),
107
+ gr.Number(label="Predicted Surge"),
108
  gr.Number(label="Final Dynamic Price")
109
  ]
110
 
111
+ app = gr.Interface(
112
+ fn=predict_price,
113
  inputs=inputs,
114
  outputs=outputs,
115
+ title="Dynamic Pricing Prediction (Holiday + Festival Aware)",
116
+ description="Predicts fare surge based on demand, supply, weather, events, festivals, holidays, and season."
117
  )
118
 
119
+ app.launch()