-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlayover_api.py
More file actions
651 lines (553 loc) · 25.1 KB
/
layover_api.py
File metadata and controls
651 lines (553 loc) · 25.1 KB
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
#!/usr/bin/env python3
"""
Layover Legend API - FastAPI Backend
Provides REST endpoints for the layover planning system
"""
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List, Dict, Any, Optional, Tuple
from contextlib import asynccontextmanager
import json
import re
import os
import requests
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Import from layover system
import layover_system_final
from layover_system_final import (
setup_system, answer_layover_question, NYC_POIS, AIRPORTS
)
from crewai import Task, Crew, Process
# Global system state
llm = None
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Initialize and cleanup the system"""
global llm
try:
llm = setup_system()
if llm:
print("✅ Layover Legend API started successfully")
else:
print("❌ Failed to initialize system")
except Exception as e:
print(f"❌ Startup error: {e}")
yield
# Cleanup code would go here if needed
print("🔄 Shutting down Layover Legend API")
app = FastAPI(
title="Layover Legend API",
description="AI-powered layover planning with real-time routing",
version="1.0.0",
lifespan=lifespan
)
# CORS middleware for frontend integration
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Configure for production
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Request/Response Models
class LayoverRequest(BaseModel):
query: str
user_preferences: Optional[Dict[str, Any]] = {}
airport: Optional[str] = None
layover_hours: Optional[int] = None
arrival_time: Optional[str] = None
departure_time: Optional[str] = None
class POILocation(BaseModel):
name: str
address: str
category: str
description: str
latitude: float
longitude: float
class RouteSegment(BaseModel):
from_location: str
to_location: str
travel_time_minutes: int
distance_miles: float
mode: str
coordinates: List[List[float]] # [[lon, lat], [lon, lat], ...]
class LayoverResponse(BaseModel):
success: bool
text_response: str
locations: List[POILocation]
routes: List[RouteSegment]
total_cost_estimate: Dict[str, float]
arcgis_route_data: Optional[Dict[str, Any]] = None # Complete ArcGIS response for frontend mapping
frontend_ready: Optional[Dict[str, Any]] = None # Frontend-ready mapping data
route_analysis: Optional[Dict[str, Any]] = None # Route analysis data
class MultiStopRequest(BaseModel):
airport_code: str
poi_locations: List[Dict[str, Any]] # [{"name": "Empire State", "lat": 40.748, "lon": -73.985, "timecat": 1}]
mode: str = "driving" # "walking" or "driving"
@app.get("/")
async def root():
"""Health check endpoint"""
return {
"message": "Layover Legend API is running",
"status": "healthy",
"available_airports": list(AIRPORTS.keys()),
"total_pois": len(NYC_POIS)
}
@app.get("/airports")
async def get_airports():
"""Get available airports"""
return {
"airports": {
code: {
"name": info["name"],
"latitude": info["lat"],
"longitude": info["lon"]
}
for code, info in AIRPORTS.items()
}
}
@app.get("/pois")
async def get_pois():
"""Get all available POIs"""
return {
"pois": [
{
"name": poi["name"],
"address": poi["address"],
"category": poi["category"],
"description": poi["description"],
"latitude": poi["latitude"],
"longitude": poi["longitude"]
}
for poi in NYC_POIS
]
}
@app.post("/search-places")
async def api_search_places(query: str):
"""Search for places based on query"""
try:
# Access the global variables from the layover_system_final module
if not hasattr(layover_system_final, '_table') or not hasattr(layover_system_final, '_embedding_function'):
raise HTTPException(status_code=503, detail="System not initialized - database not available")
if layover_system_final._table is None or layover_system_final._embedding_function is None:
raise HTTPException(status_code=503, detail="System not initialized - database not ready")
# Perform semantic search directly
query_embedding = layover_system_final._embedding_function.embed_query(query)
results = layover_system_final._table.search(query_embedding).limit(8).to_list()
if not results:
return {
"success": True,
"query": query,
"locations": [],
"raw_result": "No places found"
}
# Convert results to POILocation format
locations = []
for result in results:
locations.append(POILocation(
name=result['name'],
address=result['address'],
category=result['category'],
description=result['description'],
latitude=result['latitude'],
longitude=result['longitude']
))
return {
"success": True,
"query": query,
"locations": locations,
"raw_result": f"Found {len(locations)} places"
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/calculate-route")
async def api_calculate_route(
origin_lat: float,
origin_lon: float,
dest_lat: float,
dest_lon: float,
mode: str = "driving"
):
"""Calculate route between two points using proper ArcGIS API"""
try:
from layover_system_final import call_arcgis_routing_api
token = os.getenv('ARCGIS_API_KEY')
airport_coords = (origin_lon, origin_lat) # lon, lat format for ArcGIS
poi_coords = [(dest_lon, dest_lat)]
route_data = call_arcgis_routing_api(token, airport_coords, poi_coords, mode)
if route_data:
time_min = route_data['total_travel_time_minutes']
distance_mi = route_data['total_distance_miles']
route_segment = RouteSegment(
from_location=f"{origin_lat:.4f},{origin_lon:.4f}",
to_location=f"{dest_lat:.4f},{dest_lon:.4f}",
travel_time_minutes=int(time_min),
distance_miles=float(distance_mi),
mode=mode,
coordinates=route_data['route_geometry_paths'][0] if route_data['route_geometry_paths'] else [[origin_lon, origin_lat], [dest_lon, dest_lat]]
)
return {
"success": True,
"route": route_segment.dict(),
"raw_result": f"✅ {mode.title()}: {time_min:.0f} minutes, {distance_mi:.1f} miles"
}
return {
"success": False,
"error": f"Could not calculate {mode} route",
"raw_result": f"❌ Could not calculate {mode} route"
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/plan-multi-stop-route")
async def api_plan_multi_stop_route(request: MultiStopRequest):
"""Plan optimized multi-stop route with complete ArcGIS response for frontend mapping"""
try:
from layover_system_final import call_arcgis_routing_api, get_visit_duration_by_timecat, AIRPORTS, get_last_arcgis_response
if request.airport_code not in AIRPORTS:
raise HTTPException(status_code=400, detail=f"Airport {request.airport_code} not supported")
airport = AIRPORTS[request.airport_code]
airport_coords = (airport['lon'], airport['lat'])
# Extract coordinates and calculate visit times
poi_coords_list = []
total_visit_time = 0
poi_details = []
for poi in request.poi_locations:
poi_coords_list.append((poi['lon'], poi['lat']))
visit_duration = get_visit_duration_by_timecat(poi.get('timecat', 2))
total_visit_time += visit_duration
poi_details.append({
"name": poi['name'],
"visit_duration": visit_duration,
"timecat": poi.get('timecat', 2),
"coordinates": [poi['lon'], poi['lat']]
})
# Use the updated call_arcgis_routing_api function with proper mode support
token = os.getenv('ARCGIS_API_KEY')
route_data = call_arcgis_routing_api(token, airport_coords, poi_coords_list, request.mode)
if not route_data:
return {
"success": False,
"error": "Failed to get route data from ArcGIS"
}
# Extract data from route_data
total_travel_time = route_data['total_travel_time_minutes']
total_distance_miles = route_data['total_distance_miles']
safety_buffer = 120 # 2 hours
total_time_needed = total_visit_time + total_travel_time + safety_buffer
# Build ArcGIS-compatible response structure for frontend
arcgis_compatible_response = {
"routes": {
"features": [{
"geometry": {"paths": route_data['route_geometry_paths']},
"attributes": {
"Total_TravelTime": total_travel_time,
"Total_Miles": total_distance_miles
}
}]
},
"stops": {"features": route_data['optimized_stops']},
"directions": [], # Would need to be extracted from ArcGIS if needed
"messages": []
}
# Return complete response with proper time calculations
return {
"success": True,
"arcgis_response": arcgis_compatible_response, # Frontend-compatible response
"time_analysis": {
"total_travel_time_minutes": total_travel_time,
"total_distance_miles": total_distance_miles,
"total_visit_time_minutes": total_visit_time,
"safety_buffer_minutes": safety_buffer,
"total_time_needed_minutes": total_time_needed,
"poi_details": poi_details
},
"time_breakdown": {
"travel": f"{total_travel_time:.1f} minutes",
"visits": f"{total_visit_time} minutes",
"buffer": f"{safety_buffer} minutes",
"total": f"{total_time_needed:.1f} minutes ({total_time_needed/60:.1f} hours)"
},
"frontend_ready": {
"routes": arcgis_compatible_response.get("routes"),
"directions": arcgis_compatible_response.get("directions", []),
"stops": arcgis_compatible_response.get("stops"),
"messages": arcgis_compatible_response.get("messages", [])
}
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.get("/test-arcgis-data")
async def test_arcgis_data():
"""Test endpoint to check if ArcGIS data is being stored"""
try:
from layover_system_final import get_last_arcgis_response
arcgis_data = get_last_arcgis_response()
return {
"has_arcgis_data": arcgis_data is not None,
"data_keys": list(arcgis_data.keys()) if arcgis_data else [],
"routes_available": bool(arcgis_data and arcgis_data.get('routes')),
"directions_available": bool(arcgis_data and arcgis_data.get('directions'))
}
except Exception as e:
return {"error": str(e)}
@app.post("/plan-layover", response_model=LayoverResponse)
async def plan_layover(request: LayoverRequest):
"""Main endpoint: Create complete layover plan"""
try:
if not llm:
raise HTTPException(status_code=503, detail="System not initialized")
# Extract preferences from query and user profile
preferences = extract_preferences(request.query, request.user_preferences)
# Extract transportation preference from query
transport_preference = "driving" # default
query_lower = request.query.lower()
if "walk" in query_lower or "walking" in query_lower:
transport_preference = "walking"
elif "drive" in query_lower or "driving" in query_lower:
transport_preference = "driving"
elif "taxi" in query_lower or "uber" in query_lower or "lyft" in query_lower:
transport_preference = "taxi"
# Add transportation preference to the query context
enhanced_query = f"{request.query}\n\nUser's preferred transportation: {transport_preference}"
# Use the answer_layover_question function directly
agent_output = answer_layover_question(enhanced_query, preferences)
# Parse the result and create response
locations, routes, total_cost = parse_layover_result(agent_output)
# Get the last ArcGIS response from the agent's tool calls
from layover_system_final import get_last_arcgis_response
arcgis_data = get_last_arcgis_response()
# Debug logging
print(f"🗺️ ArcGIS Data Available: {arcgis_data is not None}")
if arcgis_data:
print(f"🗺️ ArcGIS Data Keys: {list(arcgis_data.keys())}")
print(f"🗺️ Has Routes: {bool(arcgis_data.get('routes'))}")
print(f"🗺️ Has Directions: {bool(arcgis_data.get('directions'))}")
# If no ArcGIS data from agent, try to generate it from parsed locations
if not arcgis_data and locations:
print("🔧 Generating ArcGIS data from parsed locations...")
try:
from layover_system_final import call_arcgis_routing_api, AIRPORTS
# Extract transportation mode from query
mode = "walking" if "walk" in request.query.lower() else "driving"
# Get airport coordinates
airport_code = "LGA" # Default, could be extracted from query
if airport_code in AIRPORTS:
airport = AIRPORTS[airport_code]
airport_coords = (airport['lon'], airport['lat'])
# Convert locations to POI coordinates
poi_coords_list = [(loc.longitude, loc.latitude) for loc in locations]
# Generate route data
route_data = call_arcgis_routing_api(
token=os.getenv('ARCGIS_API_KEY'),
airport_coords=airport_coords,
poi_coords_list=poi_coords_list,
travel_mode=mode
)
if route_data:
arcgis_data = route_data.get('full_arcgis_response')
print(f"✅ Generated ArcGIS data with {len(poi_coords_list)} POIs")
except Exception as e:
print(f"❌ Failed to generate ArcGIS data: {e}")
# Create comprehensive response structure like plan-multi-stop-route endpoint
response_data = {
"success": True,
"text_response": agent_output,
"locations": [loc.dict() for loc in locations],
"routes": [route.dict() for route in routes],
"total_cost_estimate": total_cost,
"arcgis_route_data": arcgis_data
}
# Add frontend-ready mapping data if ArcGIS data is available
if arcgis_data:
response_data["frontend_ready"] = {
"routes": arcgis_data.get("routes"),
"directions": arcgis_data.get("directions", []),
"stops": arcgis_data.get("stops"),
"messages": arcgis_data.get("messages", [])
}
# Add route analysis
if arcgis_data.get("routes", {}).get("features"):
route_feature = arcgis_data["routes"]["features"][0]
attributes = route_feature.get("attributes", {})
response_data["route_analysis"] = {
"total_travel_time_minutes": attributes.get("Total_TravelTime", 0),
"total_distance_miles": attributes.get("Total_Miles", 0),
"geometry_paths": route_feature.get("geometry", {}).get("paths", [])
}
return LayoverResponse(**response_data)
except Exception as e:
print(f"❌ Error in plan_layover: {str(e)}")
return LayoverResponse(
success=False,
text_response=f"Error planning layover: {str(e)}",
locations=[],
routes=[],
total_cost_estimate={"taxi": 0.0, "subway": 0.0, "walking": 0.0},
arcgis_route_data=None
)
def extract_preferences(query: str, user_prefs: Dict[str, Any]) -> List[str]:
"""Extract preferences from query and user profile"""
preferences = []
# From query text
query_lower = query.lower()
if any(word in query_lower for word in ['coffee', 'cafe', 'espresso']):
preferences.append('cafes')
if any(word in query_lower for word in ['museum', 'art', 'gallery']):
preferences.append('museums')
if any(word in query_lower for word in ['food', 'restaurant', 'eat']):
preferences.append('food')
if any(word in query_lower for word in ['shop', 'shopping', 'store']):
preferences.append('shopping')
if any(word in query_lower for word in ['park', 'outdoor', 'green']):
preferences.append('parks')
if any(word in query_lower for word in ['authentic', 'local', 'non-touristy']):
preferences.append('authentic')
if any(word in query_lower for word in ['quick', 'fast', 'short']):
preferences.append('quick')
if any(word in query_lower for word in ['landmark', 'monument', 'famous']):
preferences.append('monuments')
# From user profile
if user_prefs:
interests = user_prefs.get('interests')
if interests:
if isinstance(interests, str):
preferences.append(interests)
elif isinstance(interests, list):
preferences.extend(interests)
else:
# Handle other dict values
for key, value in user_prefs.items():
if isinstance(value, str) and value in ['cafes', 'museums', 'parks', 'food', 'shopping', 'bars', 'monuments', 'authentic', 'quick', 'family']:
preferences.append(value)
if user_prefs.get('travel_style') == 'authentic':
preferences.append('authentic')
if user_prefs.get('time_preference') == 'quick':
preferences.append('quick')
return list(set(preferences)) if preferences else ['food', 'cafes']
def parse_search_results(result: str) -> List[POILocation]:
"""Parse search results into structured format"""
locations = []
# Split by location markers
sections = result.split('📍')
for section in sections[1:]: # Skip first empty section
try:
lines = section.strip().split('\n')
if len(lines) >= 5:
name = lines[0].strip()
category = lines[1].replace('Category:', '').strip()
address = lines[2].replace('Address:', '').strip()
visit_time_line = lines[3].replace('Visit Time:', '').strip()
visit_time = int(re.search(r'(\d+)', visit_time_line).group(1)) if re.search(r'(\d+)', visit_time_line) else 30
description = lines[4].replace('Description:', '').strip()
# Extract coordinates
coord_line = next((line for line in lines if 'Coordinates:' in line), '')
if coord_line:
coords = coord_line.replace('Coordinates:', '').strip().split(',')
if len(coords) == 2:
lat = float(coords[0].strip())
lon = float(coords[1].strip())
locations.append(POILocation(
name=name,
address=address,
category=category,
description=description,
latitude=lat,
longitude=lon
))
except Exception as e:
print(f"Error parsing location: {e}")
continue
return locations
def parse_route_result(result: str, origin_lat: float, origin_lon: float, dest_lat: float, dest_lon: float) -> RouteSegment:
"""Parse route calculation result"""
# Extract time and distance
time_match = re.search(r'(\d+) minutes', result)
distance_match = re.search(r'(\d+\.?\d*) miles', result)
mode_match = re.search(r'✅ (\w+):', result)
time_minutes = int(time_match.group(1)) if time_match else 0
distance_miles = float(distance_match.group(1)) if distance_match else 0.0
mode = mode_match.group(1).lower() if mode_match else 'driving'
# Create simple route coordinates (straight line for now)
coordinates = [[origin_lon, origin_lat], [dest_lon, dest_lat]]
return RouteSegment(
from_location=f"{origin_lat:.4f},{origin_lon:.4f}",
to_location=f"{dest_lat:.4f},{dest_lon:.4f}",
travel_time_minutes=time_minutes,
distance_miles=distance_miles,
mode=mode,
coordinates=coordinates
)
def parse_layover_result(agent_output: str) -> Tuple[List[POILocation], List[RouteSegment], Dict[str, float]]:
"""Parse agent output into structured response with proper data extraction"""
try:
locations = []
routes = []
total_cost = {"taxi": 50.0, "subway": 5.0, "walking": 0.0}
# Extract locations from agent output
import re
# Look for museum/POI mentions with addresses
address_patterns = [
r'Address[:\s]*([^\\n]+)',
r'📍\s*([^\\n]+?)(?:\s*\(|\\n)',
r'\*\*Address\*\*[:\s]*([^\\n]+)',
]
# Look for coordinates
coord_patterns = [
r'Coordinates[:\s]*([0-9.-]+),\s*([0-9.-]+)',
r'([0-9]{2}\.[0-9]+),\s*(-[0-9]{2}\.[0-9]+)',
]
# Extract addresses
addresses = []
for pattern in address_patterns:
matches = re.findall(pattern, agent_output, re.IGNORECASE)
addresses.extend(matches)
# Extract coordinates
coordinates = []
for pattern in coord_patterns:
matches = re.findall(pattern, agent_output)
coordinates.extend(matches)
# Extract POI names
poi_names = re.findall(r'(?:Queens Museum|Metropolitan Museum|Louis Armstrong|Louie Armstrong House Museum)', agent_output, re.IGNORECASE)
# Create location objects
if poi_names and coordinates:
for i, name in enumerate(poi_names[:len(coordinates)]):
if i < len(coordinates):
lat, lon = float(coordinates[i][0]), float(coordinates[i][1])
address = addresses[i] if i < len(addresses) else "Address from agent output"
locations.append(POILocation(
name=name,
address=address,
category="Museum" if "museum" in name.lower() else "Mixed",
description="Location from layover plan",
latitude=lat,
longitude=lon
))
# Extract travel times and create routes
walking_time_match = re.search(r'Walking[:\s]*([0-9]+)\s*minutes?', agent_output, re.IGNORECASE)
if walking_time_match:
walk_time = int(walking_time_match.group(1))
total_cost["walking"] = 0.0
if len(locations) >= 1:
# Create route from airport to POI
routes.append(RouteSegment(
from_location="LaGuardia Airport",
to_location=locations[0].name,
travel_time_minutes=walk_time,
distance_miles=2.4, # From agent output
mode="walking",
coordinates=[] # Will be filled by ArcGIS data
))
# Extract taxi costs
taxi_cost_match = re.search(r'taxi[:\s]*~?\$?([0-9]+)', agent_output, re.IGNORECASE)
if taxi_cost_match:
total_cost["taxi"] = float(taxi_cost_match.group(1))
return locations, routes, total_cost
except Exception as e:
print(f"Error parsing layover result: {e}")
return [], [], {"taxi": 0.0, "subway": 0.0, "walking": 0.0}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)