Sahithi27 commited on
Commit
fec65ac
·
verified ·
1 Parent(s): d67f394

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -50
app.py CHANGED
@@ -3,31 +3,27 @@ import joblib
3
  import pandas as pd
4
  import numpy as np
5
  import requests
6
- import time
7
 
8
- # ================================
9
- # WEATHER CONFIG
10
- # ================================
 
 
 
 
 
 
11
  API_KEY = "YOUR_API_KEY"
12
  CITY = "Visakhapatnam,IN"
13
 
14
- _last_weather = None
15
- _last_time = 0
16
-
17
  def get_weather_features():
18
- global _last_weather, _last_time
19
-
20
- # Cache for 5 minutes
21
- if _last_weather and (time.time() - _last_time < 300):
22
- return _last_weather
23
-
24
  try:
25
  url = "https://api.openweathermap.org/data/2.5/weather"
26
  params = {"q": CITY, "appid": API_KEY, "units": "metric"}
27
  data = requests.get(url, params=params, timeout=5).json()
28
 
29
- condition = data["weather"][0]["main"]
30
- temp = data["main"]["temp"]
31
 
32
  mapping = {
33
  "Clear": 1.0,
@@ -36,30 +32,13 @@ def get_weather_features():
36
  "Thunderstorm": 1.30
37
  }
38
 
39
- weather_factor = mapping.get(condition, 1.0)
40
-
41
- _last_weather = (weather_factor, temp)
42
- _last_time = time.time()
43
- return _last_weather
44
 
45
  except:
46
- return (1.0, 30)
47
 
48
 
49
- # ================================
50
- # LOAD MODEL
51
- # ================================
52
- artifact = joblib.load("dynamic_pricing_artifact_v1.joblib")
53
-
54
- model = artifact["model"]
55
- FEATURES = artifact["features"]
56
- FIXED_FARE = artifact["fixed_fare"]
57
- RATE_PER_KM = artifact["rate_per_km"]
58
-
59
-
60
- # ================================
61
- # PREDICTION FUNCTION
62
- # ================================
63
  def predict_dynamic_price(
64
  zone_id, demand, supply, driver_availability,
65
  event_factor, traffic_index,
@@ -68,15 +47,14 @@ def predict_dynamic_price(
68
  is_holiday, is_festival
69
  ):
70
 
71
- # -------- WEATHER --------
72
  weather_factor, temperature = get_weather_features()
73
 
74
- # -------- BASE FARE --------
75
  base_price = FIXED_FARE + (distance_km * RATE_PER_KM)
76
 
77
- # -------- BUILD FEATURE VECTOR --------
78
  row = {f: 0.0 for f in FEATURES}
79
 
 
80
  inputs = {
81
  "zone_id": zone_id,
82
  "hour": hour,
@@ -93,27 +71,54 @@ def predict_dynamic_price(
93
  "traffic_index": traffic_index,
94
  "distance_km": distance_km,
95
  "duration_min": duration_min,
96
- "base_fare": base_price
 
97
  }
98
 
99
  for k, v in inputs.items():
100
  if k in row:
101
  row[k] = float(v)
102
 
103
- # -------- CRITICAL: DEMAND/SUPPLY RATIO --------
104
- row["demand_supply_ratio"] = np.clip((demand + 1) / (supply + 1), 0, 50)
105
-
106
  df_row = pd.DataFrame([[row[f] for f in FEATURES]], columns=FEATURES)
107
 
108
- # -------- DEBUG (Remove later) --------
109
- print("Demand:", demand, "Supply:", supply, "Drivers:", driver_availability)
110
- print("Ratio:", row["demand_supply_ratio"])
111
-
112
- # -------- MODEL PREDICTION --------
113
  surge = float(model.predict(df_row)[0])
114
- print("Raw Surge:", surge)
115
-
116
- # Avoid constant clipping hiding variation
117
  surge = np.clip(surge, 1.0, 3.5)
118
 
119
  final_price = base_price * surge
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  import pandas as pd
4
  import numpy as np
5
  import requests
 
6
 
7
+ # ===================== LOAD MODEL =====================
8
+ artifact = joblib.load("dynamic_pricing_artifact_v1.joblib")
9
+
10
+ model = artifact["model"]
11
+ FEATURES = artifact["features"]
12
+ FIXED_FARE = artifact["fixed_fare"]
13
+ RATE_PER_KM = artifact["rate_per_km"]
14
+
15
+ # ===================== WEATHER (SAFE) =====================
16
  API_KEY = "YOUR_API_KEY"
17
  CITY = "Visakhapatnam,IN"
18
 
 
 
 
19
  def get_weather_features():
 
 
 
 
 
 
20
  try:
21
  url = "https://api.openweathermap.org/data/2.5/weather"
22
  params = {"q": CITY, "appid": API_KEY, "units": "metric"}
23
  data = requests.get(url, params=params, timeout=5).json()
24
 
25
+ condition = data.get("weather", [{}])[0].get("main", "Clear")
26
+ temp = data.get("main", {}).get("temp", 30)
27
 
28
  mapping = {
29
  "Clear": 1.0,
 
32
  "Thunderstorm": 1.30
33
  }
34
 
35
+ return mapping.get(condition, 1.0), temp
 
 
 
 
36
 
37
  except:
38
+ return 1.0, 30
39
 
40
 
41
+ # ===================== PREDICTION =====================
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  def predict_dynamic_price(
43
  zone_id, demand, supply, driver_availability,
44
  event_factor, traffic_index,
 
47
  is_holiday, is_festival
48
  ):
49
 
 
50
  weather_factor, temperature = get_weather_features()
51
 
 
52
  base_price = FIXED_FARE + (distance_km * RATE_PER_KM)
53
 
54
+ # Initialize all features = 0
55
  row = {f: 0.0 for f in FEATURES}
56
 
57
+ # Fill known inputs
58
  inputs = {
59
  "zone_id": zone_id,
60
  "hour": hour,
 
71
  "traffic_index": traffic_index,
72
  "distance_km": distance_km,
73
  "duration_min": duration_min,
74
+ "base_fare": base_price,
75
+ "demand_supply_ratio": (demand + 1) / (supply + 1)
76
  }
77
 
78
  for k, v in inputs.items():
79
  if k in row:
80
  row[k] = float(v)
81
 
82
+ # Create dataframe with EXACT feature order
 
 
83
  df_row = pd.DataFrame([[row[f] for f in FEATURES]], columns=FEATURES)
84
 
85
+ # Predict
 
 
 
 
86
  surge = float(model.predict(df_row)[0])
 
 
 
87
  surge = np.clip(surge, 1.0, 3.5)
88
 
89
  final_price = base_price * surge
90
+
91
+ return round(base_price, 2), round(surge, 3), round(final_price, 2)
92
+
93
+
94
+ # ===================== UI =====================
95
+ inputs = [
96
+ gr.Number(label="Zone ID", value=1),
97
+ gr.Number(label="Demand", value=150),
98
+ gr.Number(label="Supply", value=80),
99
+ gr.Number(label="Driver Availability", value=60),
100
+ gr.Number(label="Event Factor", value=1.0),
101
+ gr.Number(label="Traffic Index", value=0.5),
102
+ gr.Number(label="Distance (km)", value=10),
103
+ gr.Number(label="Duration (min)", value=20),
104
+ gr.Number(label="Hour", value=18),
105
+ gr.Number(label="Day of Week", value=4),
106
+ gr.Number(label="Is Weekend", value=0),
107
+ gr.Number(label="Is Holiday", value=0),
108
+ gr.Number(label="Is Festival", value=0),
109
+ ]
110
+
111
+ outputs = [
112
+ gr.Number(label="Base Price"),
113
+ gr.Number(label="Surge Factor"),
114
+ gr.Number(label="Final Dynamic Price"),
115
+ ]
116
+
117
+ demo = gr.Interface(
118
+ fn=predict_dynamic_price,
119
+ inputs=inputs,
120
+ outputs=outputs,
121
+ title="Dynamic Pricing (Stable Version)"
122
+ )
123
+
124
+ demo.launch()