Spaces:
Sleeping
Sleeping
File size: 16,526 Bytes
d136a46 92971be d136a46 92971be d136a46 92971be d136a46 92971be d136a46 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 |
# #!/usr/bin/env python
# """
# Gradio App for NYC Taxi Fare Prediction & Road Route Visualization using OSRM
# Requirements:
# pip install torch gradio requests polyline folium pandas numpy
# """
# import torch
# import torch.nn as nn
# import numpy as np
# import pandas as pd
# import requests
# import polyline
# import folium
# import gradio as gr
# # -----------------------------
# # Model Definition (TabularModel)
# # -----------------------------
# class TabularModel(nn.Module):
# def __init__(self, emb_szs, n_cont, out_sz, layers, p=0.5):
# """
# Model for tabular data combining embeddings for categorical variables and
# a feed-forward network for continuous features.
# """
# super().__init__()
# self.embeds = nn.ModuleList([nn.Embedding(ni, nf) for ni, nf in emb_szs])
# self.emb_drop = nn.Dropout(p)
# self.bn_cont = nn.BatchNorm1d(n_cont)
# n_emb = sum([nf for _, nf in emb_szs])
# n_in = n_emb + n_cont
# layerlist = []
# for i in layers:
# layerlist.append(nn.Linear(n_in, i))
# layerlist.append(nn.ReLU(inplace=True))
# layerlist.append(nn.BatchNorm1d(i))
# layerlist.append(nn.Dropout(p))
# n_in = i
# layerlist.append(nn.Linear(layers[-1], out_sz))
# self.layers = nn.Sequential(*layerlist)
# def forward(self, x_cat, x_cont):
# embeddings = []
# for i, e in enumerate(self.embeds):
# embeddings.append(e(x_cat[:, i]))
# x = torch.cat(embeddings, 1)
# x = self.emb_drop(x)
# x_cont = self.bn_cont(x_cont)
# x = torch.cat([x, x_cont], 1)
# x = self.layers(x)
# return x
# # -----------------------------
# # Load the trained model
# # -----------------------------
# # These parameters must match those used during training.
# emb_szs = [(24, 12), (2, 1), (7, 4)]
# n_cont = 6 # [pickup_lat, pickup_long, dropoff_lat, dropoff_long, passenger_count, dist_km]
# out_sz = 1
# layers = [200, 100]
# p = 0.4
# model = TabularModel(emb_szs, n_cont, out_sz, layers, p)
# # Load model state (using weights_only=True to address the warning)
# model.load_state_dict(torch.load("TaxiFareRegrModel.pt", map_location=torch.device("cpu"), weights_only=True))
# model.eval()
# # -----------------------------
# # Helper Function: Haversine
# # -----------------------------
# def haversine_distance_coords(lat1, lon1, lat2, lon2):
# """Compute haversine distance (in km) between two coordinate pairs."""
# r = 6371 # Earth's radius in kilometers
# phi1 = np.radians(lat1)
# phi2 = np.radians(lat2)
# delta_phi = np.radians(lat2 - lat1)
# delta_lambda = np.radians(lon2 - lon1)
# a = np.sin(delta_phi/2)**2 + np.cos(phi1)*np.cos(phi2)*np.sin(delta_lambda/2)**2
# c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a))
# return r * c
# # -----------------------------
# # OSRM Route Retrieval
# # -----------------------------
# def get_osrm_route(lat1, lon1, lat2, lon2):
# """
# Query OSRM for a route between (lat1, lon1) and (lat2, lon2).
# Returns:
# - route_points: list of (lat, lon) tuples for the route polyline
# - distance_m: route distance in meters (from OSRM)
# - duration_s: route duration in seconds (from OSRM)
# """
# # OSRM expects coordinates as "lon,lat;lon,lat"
# coords = f"{lon1},{lat1};{lon2},{lat2}"
# OSRM_URL = f"http://router.project-osrm.org/route/v1/driving/{coords}?overview=full&geometries=polyline"
# response = requests.get(OSRM_URL)
# response.raise_for_status()
# data = response.json()
# if data.get("code") != "Ok":
# raise Exception("Route not found")
# route = data["routes"][0]
# encoded_poly = route["geometry"]
# route_points = polyline.decode(encoded_poly)
# distance_m = route["distance"]
# duration_s = route["duration"]
# return route_points, distance_m, duration_s
# # -----------------------------
# # Main Prediction & Mapping Function
# # -----------------------------
# def predict_fare_and_map(plat, plong, dlat, dlong, psngr, dt):
# """
# 1. Process pickup datetime to extract categorical features.
# 2. Compute haversine distance for the model input.
# 3. Use the PyTorch model to predict the taxi fare.
# 4. Query OSRM for the actual road route geometry & distance.
# 5. Draw a Folium map with the OSRM route (blue line) and markers.
# 6. Return a text string with predicted fare and route distance, plus the map HTML.
# """
# # Process datetime
# try:
# pickup_dt = pd.to_datetime(dt)
# except Exception as e:
# return f"Error parsing date/time: {e}", ""
# hour = pickup_dt.hour
# am_or_pm = 0 if hour < 12 else 1
# weekday_str = pickup_dt.strftime("%a")
# weekday_map = {'Fri': 0, 'Mon': 1, 'Sat': 2, 'Sun': 3, 'Thu': 4, 'Tue': 5, 'Wed': 6}
# weekday = weekday_map.get(weekday_str, 0)
# # Prepare tensors for model input (use haversine distance)
# dist_km = haversine_distance_coords(plat, plong, dlat, dlong)
# cat_array = np.array([[hour, am_or_pm, weekday]])
# cat_tensor = torch.tensor(cat_array, dtype=torch.int64)
# cont_array = np.array([[plat, plong, dlat, dlong, psngr, dist_km]])
# cont_tensor = torch.tensor(cont_array, dtype=torch.float)
# # Predict fare
# with torch.no_grad():
# pred = model(cat_tensor, cont_tensor)
# fare_pred = pred.item()
# # Get route from OSRM
# try:
# route_points, route_distance_m, route_duration_s = get_osrm_route(plat, plong, dlat, dlong)
# except Exception as e:
# return f"Error from OSRM: {e}", ""
# # Create Folium map centered between pickup & dropoff
# mid_lat = (plat + dlat) / 2
# mid_lon = (plong + dlong) / 2
# m = folium.Map(location=[mid_lat, mid_lon], zoom_start=12)
# # Add markers
# folium.Marker([plat, plong], icon=folium.Icon(color="green"), tooltip="Pickup").add_to(m)
# folium.Marker([dlat, dlong], icon=folium.Icon(color="red"), tooltip="Dropoff").add_to(m)
# # Draw the route polyline (blue line) with popup showing OSRM distance
# folium.PolyLine(
# route_points,
# color="blue",
# weight=3,
# opacity=0.7,
# popup=f"OSRM Distance: {route_distance_m/1000:.2f} km"
# ).add_to(m)
# map_html = m._repr_html_()
# route_distance_km = route_distance_m / 1000
# output_text = (f"Predicted Fare: ${fare_pred:.2f}\n"
# f"Route Distance (OSRM): {route_distance_km:.2f} km")
# return output_text, map_html
# # -----------------------------
# # Gradio Interface
# # -----------------------------
# iface = gr.Interface(
# fn=predict_fare_and_map,
# inputs=[
# gr.Number(label="Pickup Latitude", value=40.75),
# gr.Number(label="Pickup Longitude", value=-73.99),
# gr.Number(label="Dropoff Latitude", value=40.73),
# gr.Number(label="Dropoff Longitude", value=-73.98),
# gr.Number(label="Passenger Count", value=1),
# gr.Textbox(label="Pickup Date and Time (YYYY-MM-DD HH:MM:SS)", value="2010-04-19 08:17:56")
# ],
# outputs=[
# gr.Textbox(label="Prediction & Distance"),
# gr.HTML(label="Map")
# ],
# title="NYC Taxi Fare Prediction with OSRM Road Route",
# description=(
# "Enter pickup/dropoff coordinates, passenger count, and pickup datetime to predict the taxi fare. "
# "The app displays the actual road route (blue line) from OSRM on a Folium map."
# )
# )
# if __name__ == "__main__":
# iface.launch()
#!/usr/bin/env python
"""
Gradio App for NYC Taxi Fare Prediction & Road Route Visualization using OSRM
Requirements:
pip install torch gradio requests polyline folium pandas numpy
"""
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
import requests
import polyline
import folium
import gradio as gr
# -----------------------------
# Model Definition (TabularModel)
# -----------------------------
class TabularModel(nn.Module):
def __init__(self, emb_szs, n_cont, out_sz, layers, p=0.5):
"""
Model for tabular data combining embeddings for categorical variables and
a feed-forward network for continuous features.
"""
super().__init__()
self.embeds = nn.ModuleList([nn.Embedding(ni, nf) for ni, nf in emb_szs])
self.emb_drop = nn.Dropout(p)
self.bn_cont = nn.BatchNorm1d(n_cont)
n_emb = sum([nf for _, nf in emb_szs])
n_in = n_emb + n_cont
layerlist = []
for i in layers:
layerlist.append(nn.Linear(n_in, i))
layerlist.append(nn.ReLU(inplace=True))
layerlist.append(nn.BatchNorm1d(i))
layerlist.append(nn.Dropout(p))
n_in = i
layerlist.append(nn.Linear(layers[-1], out_sz))
self.layers = nn.Sequential(*layerlist)
def forward(self, x_cat, x_cont):
embeddings = []
for i, e in enumerate(self.embeds):
embeddings.append(e(x_cat[:, i]))
x = torch.cat(embeddings, 1)
x = self.emb_drop(x)
x_cont = self.bn_cont(x_cont)
x = torch.cat([x, x_cont], 1)
x = self.layers(x)
return x
# -----------------------------
# Load the trained model
# -----------------------------
# These parameters must match those used during training.
emb_szs = [(24, 12), (2, 1), (7, 4)]
n_cont = 6 # [pickup_lat, pickup_long, dropoff_lat, dropoff_long, passenger_count, dist_km]
out_sz = 1
layers = [200, 100]
p = 0.4
model = TabularModel(emb_szs, n_cont, out_sz, layers, p)
# Load model state (using weights_only=True to address the warning)
model.load_state_dict(torch.load("TaxiFareRegrModel.pt", map_location=torch.device("cpu"), weights_only=True))
model.eval()
# -----------------------------
# Helper Function: Haversine
# -----------------------------
def haversine_distance_coords(lat1, lon1, lat2, lon2):
"""Compute haversine distance (in km) between two coordinate pairs."""
r = 6371 # Earth's radius in kilometers
phi1 = np.radians(lat1)
phi2 = np.radians(lat2)
delta_phi = np.radians(lat2 - lat1)
delta_lambda = np.radians(lon2 - lon1)
a = np.sin(delta_phi/2)**2 + np.cos(phi1)*np.cos(phi2)*np.sin(delta_lambda/2)**2
c = 2 * np.arctan2(np.sqrt(a), np.sqrt(1 - a))
return r * c
# -----------------------------
# OSRM Route Retrieval
# -----------------------------
def get_osrm_route(lat1, lon1, lat2, lon2):
"""
Query OSRM for a route between (lat1, lon1) and (lat2, lon2).
Returns:
- route_points: list of (lat, lon) tuples for the route polyline
- distance_m: route distance in meters (from OSRM)
- duration_s: route duration in seconds (from OSRM)
"""
# OSRM expects coordinates as "lon,lat;lon,lat"
coords = f"{lon1},{lat1};{lon2},{lat2}"
OSRM_URL = f"http://router.project-osrm.org/route/v1/driving/{coords}?overview=full&geometries=polyline"
response = requests.get(OSRM_URL)
response.raise_for_status()
data = response.json()
if data.get("code") != "Ok":
raise Exception("Route not found")
route = data["routes"][0]
encoded_poly = route["geometry"]
route_points = polyline.decode(encoded_poly)
distance_m = route["distance"]
duration_s = route["duration"]
return route_points, distance_m, duration_s
# -----------------------------
# Main Prediction & Mapping Function
# -----------------------------
def predict_fare_and_map(plat, plong, dlat, dlong, psngr, dt):
"""
1. Process pickup datetime to extract categorical features.
2. Compute haversine distance for the model input.
3. Use the PyTorch model to predict the taxi fare.
4. Query OSRM for the actual road route geometry & distance.
5. Draw a Folium map with the OSRM route (blue line) and markers.
6. Return a text string with predicted fare and route distance, plus the map HTML.
"""
# Process datetime
try:
pickup_dt = pd.to_datetime(dt)
except Exception as e:
return f"Error parsing date/time: {e}", ""
hour = pickup_dt.hour
am_or_pm = 0 if hour < 12 else 1
weekday_str = pickup_dt.strftime("%a")
weekday_map = {'Fri': 0, 'Mon': 1, 'Sat': 2, 'Sun': 3, 'Thu': 4, 'Tue': 5, 'Wed': 6}
weekday = weekday_map.get(weekday_str, 0)
# Prepare tensors for model input (use haversine distance)
dist_km = haversine_distance_coords(plat, plong, dlat, dlong)
cat_array = np.array([[hour, am_or_pm, weekday]])
cat_tensor = torch.tensor(cat_array, dtype=torch.int64)
cont_array = np.array([[plat, plong, dlat, dlong, psngr, dist_km]])
cont_tensor = torch.tensor(cont_array, dtype=torch.float)
# Predict fare
with torch.no_grad():
pred = model(cat_tensor, cont_tensor)
fare_pred = pred.item()
# Get route from OSRM
try:
route_points, route_distance_m, route_duration_s = get_osrm_route(plat, plong, dlat, dlong)
except Exception as e:
return f"Error from OSRM: {e}", ""
# Create Folium map centered between pickup & dropoff
mid_lat = (plat + dlat) / 2
mid_lon = (plong + dlong) / 2
m = folium.Map(location=[mid_lat, mid_lon], zoom_start=12)
# Add markers
folium.Marker([plat, plong], icon=folium.Icon(color="green"), tooltip="Pickup").add_to(m)
folium.Marker([dlat, dlong], icon=folium.Icon(color="red"), tooltip="Dropoff").add_to(m)
# Draw the route polyline (blue line) with popup showing OSRM distance
folium.PolyLine(
route_points,
color="blue",
weight=3,
opacity=0.7,
popup=f"OSRM Distance: {route_distance_m/1000:.2f} km"
).add_to(m)
map_html = m._repr_html_()
route_distance_km = route_distance_m / 1000
output_text = (f"Predicted Fare: ${fare_pred:.2f}\n"
f"Route Distance (OSRM): {route_distance_km:.2f} km")
return output_text, map_html
# -----------------------------
# Example Locations (Popular NYC Spots)
# Each example is a list of 6 inputs:
# [pickup_lat, pickup_lon, dropoff_lat, dropoff_lon, passenger_count, pickup_datetime]
# -----------------------------
examples = [
# 1. Times Square to Central Park (short ride)
[40.7580, -73.9855, 40.7690, -73.9819, 1, "2010-04-19 08:17:56"],
# 2. Times Square to JFK Airport (long ride)
[40.7580, -73.9855, 40.6413, -73.7781, 1, "2010-04-19 08:17:56"],
# 3. Grand Central Terminal to Empire State Building (very short ride)
[40.7527, -73.9772, 40.7484, -73.9857, 1, "2010-04-19 08:17:56"],
# 4. Brooklyn Bridge to Wall Street (short urban ride)
[40.7061, -73.9969, 40.7069, -74.0113, 1, "2010-04-19 08:17:56"],
# 5. Yankee Stadium to Central Park (moderate ride)
[40.8296, -73.9262, 40.7829, -73.9654, 1, "2010-04-19 08:17:56"],
# 6. Columbia University area to Rockefeller Center (cross-city ride)
[40.8075, -73.9626, 40.7587, -73.9787, 1, "2010-04-19 08:17:56"],
# 7. Battery Park to Central Park (longer ride across Manhattan)
[40.7033, -74.0170, 40.7829, -73.9654, 1, "2010-04-19 08:17:56"]
]
# -----------------------------
# Gradio Interface
# -----------------------------
iface = gr.Interface(
fn=predict_fare_and_map,
inputs=[
gr.Number(label="Pickup Latitude", value=40.75),
gr.Number(label="Pickup Longitude", value=-73.99),
gr.Number(label="Dropoff Latitude", value=40.73),
gr.Number(label="Dropoff Longitude", value=-73.98),
gr.Number(label="Passenger Count", value=1),
gr.Textbox(label="Pickup Date and Time (YYYY-MM-DD HH:MM:SS)", value="2010-04-19 08:17:56")
],
outputs=[
gr.Textbox(label="Prediction & Distance"),
gr.HTML(label="Map")
],
examples=examples,
title="NYC Taxi Fare Prediction with OSRM Road Route",
description=(
"Enter pickup/dropoff coordinates, passenger count, and pickup datetime to predict the taxi fare. "
"The app displays the actual road route (blue line) from OSRM on a Folium map. "
"You can also choose from several example routes between popular locations in New York."
)
)
if __name__ == "__main__":
iface.launch()
|