Spaces:
Runtime error
Runtime error
Download spatial_copilot_service.py from KassimYassin/palate: direct link, hf CLI and curl.
- Browser
- Download file 103 kB
-
https://huggingface.co/spaces/KassimYassin/palate/resolve/main/spatial_copilot_service.py
- Command line
-
hf download hf://spaces/KassimYassin/palate/spatial_copilot_service.py
-
curl -L -o spatial_copilot_service.py https://huggingface.co/spaces/KassimYassin/palate/resolve/main/spatial_copilot_service.py
103 kB
"""
Spatial Copilot Service for 'Google Maps on God Mode'
Handles natural language spatial intent grounding, multi-entity graph resolution,
dynamic gazetteer indexing, and structured response generation with H3 polygons and map actions.
"""
import os
import json
import math
import re
import time
import urllib.request
import urllib.parse
import h3
def haversine_m(lat1, lon1, lat2, lon2):
R = 6371000 # meters
phi1, phi2 = math.radians(lat1), math.radians(lat2)
dphi = math.radians(lat2 - lat1)
dlam = math.radians(lon2 - lon1)
a = math.sin(dphi/2)**2 + math.cos(phi1) * math.cos(phi2) * math.sin(dlam/2)**2
return int(2 * R * math.atan2(math.sqrt(a), math.sqrt(1 - a)))
INTERCITY_RAIL_TERMINALS = {
("amsterdam", "paris"): {
"operator": "Eurostar (formerly Thalys)",
"arrival_station": "Gare du Nord",
"city": "Paris",
"coordinates": [48.8809, 2.3553],
"typical_late_arrival_cutoff_m": 450,
"recommended_hotels": [
{
"id": "paris_hotel_terminus_nord",
"name": "25hours Hotel Terminus Nord",
"latitude": 48.8803,
"longitude": 2.3550,
"tier": "Boutique Design",
"price_label": "€€€",
"highlights": "Directly opposite Gare du Nord main entrance; 24h reception; soundproofed boutique rooms so you don't hear late-night station traffic.",
"distance_m": 85,
"walk_mins": 1
},
{
"id": "paris_hotel_whistler",
"name": "Hôtel Whistler",
"latitude": 48.8801,
"longitude": 2.3575,
"tier": "Quiet Luxury Boutique",
"price_label": "€€€",
"highlights": "Luxury railway-themed boutique hotel on quiet side street; 24h concierge; 3 mins walk from Eurostar platforms.",
"distance_m": 220,
"walk_mins": 3
}
]
}
}
DUBAI_GAZETTEER = {
"mirdif city centre": {"name": "City Centre Mirdif", "coords": (25.2163, 55.4077), "radius_m": 1200},
"city centre mirdif": {"name": "City Centre Mirdif", "coords": (25.2163, 55.4077), "radius_m": 1200},
"mirdif city center": {"name": "City Centre Mirdif", "coords": (25.2163, 55.4077), "radius_m": 1200},
"city center mirdif": {"name": "City Centre Mirdif", "coords": (25.2163, 55.4077), "radius_m": 1200},
"uptown mirdif": {"name": "Uptown Mirdif", "coords": (25.2250, 55.4200), "radius_m": 1200},
"mirdif": {"name": "Mirdif", "coords": (25.2180, 55.4150), "radius_m": 2500},
"mall of the emirates": {"name": "Mall of the Emirates", "coords": (25.1181, 55.2006), "radius_m": 1200},
"moe": {"name": "Mall of the Emirates", "coords": (25.1181, 55.2006), "radius_m": 1200},
"dubai mall": {"name": "Dubai Mall", "coords": (25.1985, 55.2796), "radius_m": 1200},
"burj khalifa": {"name": "Burj Khalifa / Downtown", "coords": (25.1972, 55.2744), "radius_m": 1500},
"downtown dubai": {"name": "Downtown Dubai", "coords": (25.1972, 55.2744), "radius_m": 1800},
"downtown": {"name": "Downtown Dubai", "coords": (25.1972, 55.2744), "radius_m": 1800},
"difc": {"name": "DIFC / Gate Village", "coords": (25.2138, 55.2782), "radius_m": 1200},
"gate village": {"name": "DIFC / Gate Village", "coords": (25.2138, 55.2782), "radius_m": 800},
"dwtc": {"name": "Dubai World Trade Centre", "coords": (25.2235, 55.2829), "radius_m": 1200},
"trade centre": {"name": "Dubai World Trade Centre", "coords": (25.2235, 55.2829), "radius_m": 1200},
"trade center": {"name": "Dubai World Trade Centre", "coords": (25.2235, 55.2829), "radius_m": 1200},
"dubai marina": {"name": "Dubai Marina", "coords": (25.0789, 55.1444), "radius_m": 1800},
"marina mall": {"name": "Dubai Marina Mall", "coords": (25.0772, 55.1396), "radius_m": 1000},
"marina": {"name": "Dubai Marina", "coords": (25.0789, 55.1444), "radius_m": 1800},
"jbr": {"name": "JBR / The Beach", "coords": (25.0780, 55.1320), "radius_m": 1200},
"the beach": {"name": "JBR / The Beach", "coords": (25.0780, 55.1320), "radius_m": 1000},
"jlt": {"name": "Jumeirah Lakes Towers", "coords": (25.0740, 55.1450), "radius_m": 1800},
"jumeirah lakes towers": {"name": "Jumeirah Lakes Towers", "coords": (25.0740, 55.1450), "radius_m": 1800},
"palm jumeirah": {"name": "Palm Jumeirah", "coords": (25.1124, 55.1390), "radius_m": 2500},
"the palm": {"name": "Palm Jumeirah", "coords": (25.1124, 55.1390), "radius_m": 2500},
"nakheel mall": {"name": "Nakheel Mall, Palm Jumeirah", "coords": (25.1142, 55.1402), "radius_m": 1000},
"the pointe": {"name": "The Pointe, Palm Jumeirah", "coords": (25.1270, 55.1230), "radius_m": 1000},
"deira": {"name": "Deira", "coords": (25.2690, 55.3280), "radius_m": 2500},
"city centre deira": {"name": "City Centre Deira", "coords": (25.2520, 55.3330), "radius_m": 1200},
"city center deira": {"name": "City Centre Deira", "coords": (25.2520, 55.3330), "radius_m": 1200},
"deira city centre": {"name": "City Centre Deira", "coords": (25.2520, 55.3330), "radius_m": 1200},
"bur dubai": {"name": "Bur Dubai", "coords": (25.2530, 55.3020), "radius_m": 2200},
"burjuman": {"name": "BurJuman", "coords": (25.2520, 55.3040), "radius_m": 1000},
"karama": {"name": "Al Karama", "coords": (25.2440, 55.3030), "radius_m": 1800},
"al karama": {"name": "Al Karama", "coords": (25.2440, 55.3030), "radius_m": 1800},
"al fahidi": {"name": "Al Fahidi Historic District", "coords": (25.2635, 55.2972), "radius_m": 1000},
"al seef": {"name": "Al Seef / Dubai Creek", "coords": (25.2600, 55.3070), "radius_m": 1000},
"dubai creek": {"name": "Dubai Creek", "coords": (25.2610, 55.3050), "radius_m": 1500},
"creek": {"name": "Dubai Creek", "coords": (25.2610, 55.3050), "radius_m": 1500},
"shindagha": {"name": "Al Shindagha", "coords": (25.2680, 55.2950), "radius_m": 1000},
"al quoz": {"name": "Al Quoz", "coords": (25.1415, 55.2268), "radius_m": 2200},
"alserkal": {"name": "Alserkal Avenue", "coords": (25.1415, 55.2268), "radius_m": 800},
"alserkal avenue": {"name": "Alserkal Avenue", "coords": (25.1415, 55.2268), "radius_m": 800},
"al barsha": {"name": "Al Barsha", "coords": (25.1120, 55.2050), "radius_m": 2200},
"business bay": {"name": "Business Bay", "coords": (25.1860, 55.2660), "radius_m": 2000},
"dubai canal": {"name": "Dubai Canal", "coords": (25.1950, 55.2450), "radius_m": 1500},
"dubai hills": {"name": "Dubai Hills", "coords": (25.1010, 55.2420), "radius_m": 2000},
"dubai hills mall": {"name": "Dubai Hills Mall", "coords": (25.1010, 55.2420), "radius_m": 1200},
"festival city": {"name": "Dubai Festival City", "coords": (25.2220, 55.3530), "radius_m": 1500},
"dubai festival city": {"name": "Dubai Festival City", "coords": (25.2220, 55.3530), "radius_m": 1500},
"ibn battuta": {"name": "Ibn Battuta Mall", "coords": (25.0440, 55.1200), "radius_m": 1200},
"ibn battuta mall": {"name": "Ibn Battuta Mall", "coords": (25.0440, 55.1200), "radius_m": 1200},
"city walk": {"name": "City Walk", "coords": (25.2070, 55.2620), "radius_m": 1200},
"al wasl": {"name": "Al Wasl", "coords": (25.2050, 55.2600), "radius_m": 2000},
"jumeirah": {"name": "Jumeirah", "coords": (25.1850, 55.2350), "radius_m": 2800},
"umm suqeim": {"name": "Umm Suqeim / Kite Beach", "coords": (25.1440, 55.1950), "radius_m": 2500},
"kite beach": {"name": "Kite Beach", "coords": (25.1550, 55.2040), "radius_m": 1000},
"silicon oasis": {"name": "Dubai Silicon Oasis", "coords": (25.1270, 55.3810), "radius_m": 2500},
"dso": {"name": "Dubai Silicon Oasis", "coords": (25.1270, 55.3810), "radius_m": 2500},
"motor city": {"name": "Motor City", "coords": (25.0450, 55.2400), "radius_m": 2000},
"bluewaters": {"name": "Bluewaters Island", "coords": (25.0790, 55.1220), "radius_m": 800},
"bluewaters island": {"name": "Bluewaters Island", "coords": (25.0790, 55.1220), "radius_m": 800},
"al khawaneej": {"name": "Al Khawaneej", "coords": (25.2700, 55.4500), "radius_m": 3000},
"al warqa": {"name": "Al Warqa", "coords": (25.1700, 55.4000), "radius_m": 3000},
"international city": {"name": "International City", "coords": (25.1650, 55.4100), "radius_m": 2500}
}
M4_STATIONS_DATA = [
{"id": "saw", "name": "Sabiha Gökçen Havalimanı (SAW)", "lat": 40.8985, "lon": 29.3092, "zone": "Airport Terminus", "order": 1},
{"id": "kurtkoy", "name": "Kurtköy", "lat": 40.9100, "lon": 29.2967, "zone": "1 Stop from Airport", "order": 2},
{"id": "yayalar", "name": "Yayalar-Şeyhli", "lat": 40.9022, "lon": 29.2789, "zone": "Pendik Upper", "order": 3},
{"id": "fevzi_cakmak", "name": "Fevzi Çakmak-Hastane", "lat": 40.8872, "lon": 29.2633, "zone": "Hospital Cluster", "order": 4},
{"id": "tavsantepe", "name": "Tavşantepe", "lat": 40.8767, "lon": 29.2483, "zone": "Pendik Center East", "order": 5},
{"id": "pendik", "name": "Pendik", "lat": 40.8817, "lon": 29.2344, "zone": "High-Speed Rail Link", "order": 6},
{"id": "yakacik", "name": "Yakacık-Adnan Kahveci", "lat": 40.8967, "lon": 29.2272, "zone": "Kartal Foothills", "order": 7},
{"id": "kartal", "name": "Kartal", "lat": 40.8997, "lon": 29.2081, "zone": "Kartal Hub", "order": 8},
{"id": "soganlik", "name": "Soğanlık", "lat": 40.9083, "lon": 29.1917, "zone": "Kartal Commercial", "order": 9},
{"id": "hastane_adliye", "name": "Hastane-Adliye", "lat": 40.9183, "lon": 29.1783, "zone": "Anatolian Courthouse", "order": 10},
{"id": "esenkent", "name": "Esenkent", "lat": 40.9239, "lon": 29.1672, "zone": "Maltepe North", "order": 11},
{"id": "gulsuyu", "name": "Gülsuyu", "lat": 40.9281, "lon": 29.1558, "zone": "Maltepe Residential", "order": 12},
{"id": "huzurevi", "name": "Huzurevi", "lat": 40.9317, "lon": 29.1467, "zone": "Maltepe District", "order": 13},
{"id": "maltepe", "name": "Maltepe", "lat": 40.9389, "lon": 29.1333, "zone": "Maltepe Center", "order": 14},
{"id": "kucukyali", "name": "Küçükyalı", "lat": 40.9514, "lon": 29.1172, "zone": "Küçükyalı Hill", "order": 15},
{"id": "bostanci", "name": "Bostancı", "lat": 40.9639, "lon": 29.1033, "zone": "Marmaray & Pier Hub", "order": 16},
{"id": "kozyatagi", "name": "Kozyatağı", "lat": 40.9767, "lon": 29.0983, "zone": "M8 Metro Interchange", "order": 17},
{"id": "yenisahra", "name": "Yenisahra", "lat": 40.9856, "lon": 29.0886, "zone": "Ataşehir Connection", "order": 18},
{"id": "goztepe", "name": "Göztepe", "lat": 40.9958, "lon": 29.0664, "zone": "Göztepe Medical", "order": 19},
{"id": "unalan", "name": "Ünalan", "lat": 40.9989, "lon": 29.0528, "zone": "Metrobüs Interchange", "order": 20},
{"id": "acibadem", "name": "Acıbadem", "lat": 40.9997, "lon": 29.0436, "zone": "Acıbadem Residential", "order": 21},
{"id": "ayrilik_cesmesi", "name": "Ayrılık Çeşmesi", "lat": 40.9964, "lon": 29.0308, "zone": "Marmaray Cross-Bosphorus", "order": 22},
{"id": "kadikoy", "name": "Kadıköy Terminus", "lat": 40.9911, "lon": 29.0225, "zone": "Ferry Terminus & Moda", "order": 23}
]
M4_CURATED_ANCHORS = {
"saw": [
{
"id": "ist_saw_isg_dining",
"name": "ISG Port Airport Restaurant & Lounge",
"primary_category": "restaurant",
"cuisine": "Turkish & International",
"latitude": 40.8988,
"longitude": 29.3096,
"distance_m": 50,
"walk_minutes": 1,
"highlights": "Directly connected to departures hall; quiet terminal dining away from security lines.",
"price_label": "₺₺₺"
},
{
"id": "ist_saw_simit_sarayi",
"name": "Simit Sarayı SAW Departures",
"primary_category": "bakery",
"cuisine": "Turkish Bakery & Breakfast",
"latitude": 40.8983,
"longitude": 29.3090,
"distance_m": 35,
"walk_minutes": 1,
"highlights": "Fresh hot sesame simit, çay and börek right at the terminal entrance.",
"price_label": "₺"
},
{
"id": "ist_saw_bigchefs",
"name": "Big Chefs SAW Airport",
"primary_category": "restaurant",
"cuisine": "Modern Turkish & Cafe",
"latitude": 40.8981,
"longitude": 29.3085,
"distance_m": 60,
"walk_minutes": 1,
"highlights": "Sit-down comfort dining with full Turkish breakfast and hearty grilled mains.",
"price_label": "₺₺"
}
],
"kurtkoy": [
{
"id": "ist_kurtkoy_selale_01",
"name": "Şelale Et Mangal & Kebap",
"primary_category": "restaurant",
"cuisine": "Anatolian Charcoal Grill & Kebap",
"latitude": 40.9108,
"longitude": 29.2961,
"distance_m": 110,
"walk_minutes": 2,
"highlights": "110m outside Kurtköy M4 exit; authentic wood-fired meats, köfte & scratch Turkish stews.",
"price_label": "₺₺"
},
{
"id": "ist_kurtkoy_metin_02",
"name": "Dönerci Metin Usta",
"primary_category": "restaurant",
"cuisine": "Wood-Fired Döner",
"latitude": 40.9112,
"longitude": 29.2963,
"distance_m": 150,
"walk_minutes": 2,
"highlights": "Prime hand-stacked wood-fired beef döner on freshly baked lavash.",
"price_label": "₺₺"
},
{
"id": "ist_kurtkoy_ozsu_03",
"name": "Özsu Restaurant & Antep Mutfağı",
"primary_category": "restaurant",
"cuisine": "Gaziantep Kebap & Lahmacun",
"latitude": 40.9125,
"longitude": 29.2970,
"distance_m": 280,
"walk_minutes": 3,
"highlights": "Crispy thin-crust Antep lahmacun, ali nazik kebap and scratch soups.",
"price_label": "₺₺"
},
{
"id": "ist_kurtkoy_borek_04",
"name": "A Börek & Taşfırın",
"primary_category": "bakery",
"cuisine": "Stone-Oven Pide & Börek",
"latitude": 40.9118,
"longitude": 29.2965,
"distance_m": 220,
"walk_minutes": 3,
"highlights": "Traditional stone oven börek, su böreği and fresh Turkish tea.",
"price_label": "₺"
},
{
"id": "ist_kurtkoy_corba_05",
"name": "Çorbacı Gada",
"primary_category": "restaurant",
"cuisine": "24/7 Scratch Soups & Stews",
"latitude": 40.9130,
"longitude": 29.2972,
"distance_m": 280,
"walk_minutes": 4,
"highlights": "24/7 scratch kettle soups: mercimek, kelle paça and Beyran.",
"price_label": "₺"
}
]
}
M2_STATIONS_DATA = [
{"id": "yenikapi", "name": "Yenikapı", "lat": 41.0055, "lon": 28.9536, "zone": "Marmaray & Intercontinental Pier", "order": 1},
{"id": "vezneciler", "name": "Vezneciler (Istanbul Univ.)", "lat": 41.0125, "lon": 28.9619, "zone": "Historic Peninsula & Grand Bazaar", "order": 2},
{"id": "halic", "name": "Haliç (Golden Horn Bridge)", "lat": 41.0239, "lon": 28.9678, "zone": "Golden Horn Panoramic Overlook", "order": 3},
{"id": "sishane", "name": "Şişhane (Galata / Karaköy)", "lat": 41.0289, "lon": 28.9742, "zone": "Galata Tower & Karaköy Dining", "order": 4},
{"id": "taksim", "name": "Taksim Square", "lat": 41.0370, "lon": 28.9858, "zone": "Istiklal Avenue & Cultural Epicenter", "order": 5},
{"id": "osmanbey", "name": "Osmanbey (Nişantaşı)", "lat": 41.0519, "lon": 28.9878, "zone": "Nişantaşı Fine Dining & Fashion", "order": 6},
{"id": "sisli_mecidiyekoy", "name": "Şişli-Mecidiyeköy", "lat": 41.0633, "lon": 28.9922, "zone": "Bomontiada Food Hall & Metrobüs", "order": 7},
{"id": "gayrettepe", "name": "Gayrettepe", "lat": 41.0694, "lon": 29.0117, "zone": "M11 IST Airport Express Transfer", "order": 8},
{"id": "levent", "name": "Levent", "lat": 41.0772, "lon": 29.0136, "zone": "M6 Link & Gastro Epicenter", "order": 9},
{"id": "dort_levent", "name": "4. Levent", "lat": 41.0853, "lon": 29.0069, "zone": "Sapphire & Financial District", "order": 10},
{"id": "sanayi", "name": "Sanayi Mahallesi", "lat": 41.0967, "lon": 29.0061, "zone": "Seyrantepe Stadium Spur Link", "order": 11},
{"id": "itu_ayazaga", "name": "İTÜ-Ayazağa", "lat": 41.1072, "lon": 29.0231, "zone": "Maslak Tech & University Campus", "order": 12},
{"id": "ataturk_oto", "name": "Atatürk Oto Sanayi", "lat": 41.1147, "lon": 29.0294, "zone": "Artisan Workshops & Maslak North", "order": 13},
{"id": "darussafaka", "name": "Darüşşafaka", "lat": 41.1278, "lon": 29.0306, "zone": "Northern Residential & Cultural Center", "order": 14},
{"id": "haciosman", "name": "Hacıosman Terminus", "lat": 41.1406, "lon": 29.0336, "zone": "Sarıyer & Bosphorus Gateway", "order": 15}
]
M11_STATIONS_DATA = [
{"id": "gayrettepe", "name": "Gayrettepe", "lat": 41.0694, "lon": 29.0117, "zone": "M2 Taksim Spine Interchange", "order": 1},
{"id": "kagithane", "name": "Kağıthane", "lat": 41.0805, "lon": 28.9745, "zone": "M7 Mecidiyeköy Interchange", "order": 2},
{"id": "hasdal", "name": "Hasdal", "lat": 41.1147, "lon": 28.9567, "zone": "Northern Highway Bypass", "order": 3},
{"id": "kemerburgaz", "name": "Kemerburgaz", "lat": 41.1644, "lon": 28.9100, "zone": "Historical Aqueducts & Pine Forest", "order": 4},
{"id": "gokturk", "name": "Göktürk", "lat": 41.1822, "lon": 28.8925, "zone": "Artisan Cafes & Country Dining", "order": 5},
{"id": "ihsaniye", "name": "İhsaniye", "lat": 41.2294, "lon": 28.8250, "zone": "Black Sea Forest Approach", "order": 6},
{"id": "ist_airport", "name": "İstanbul Havalimanı (IST)", "lat": 41.2611, "lon": 28.7423, "zone": "International Main Terminal (120 km/h)", "order": 7},
{"id": "kargo_terminali", "name": "Kargo Terminali", "lat": 41.2722, "lon": 28.7180, "zone": "Air Freight & Logistics Hub", "order": 8},
{"id": "tasoluk", "name": "Taşoluk", "lat": 41.2330, "lon": 28.6940, "zone": "Arnavutköy North", "order": 9},
{"id": "arnavutkoy", "name": "Arnavutköy Hastane", "lat": 41.2010, "lon": 28.7200, "zone": "Arnavutköy Terminus", "order": 10}
]
M11_CURATED_ANCHORS = {
"ist_airport": [
{
"id": "ist_airport_kofteci",
"name": "Tarihi Sultanahmet Köftecisi IST Departures",
"primary_category": "restaurant",
"cuisine": "Traditional Wood-Fired Köfte & Piyaz",
"latitude": 41.2615,
"longitude": 28.7428,
"distance_m": 45,
"walk_minutes": 1,
"highlights": "Located in IST departure atrium; authentic century-old charcoal-grilled meatballs.",
"price_label": "₺₺"
},
{
"id": "ist_airport_simit",
"name": "Simit Sarayı & Çay Salonu IST",
"primary_category": "bakery",
"cuisine": "Turkish Breakfast & Fresh Simit",
"latitude": 41.2610,
"longitude": 28.7420,
"distance_m": 30,
"walk_minutes": 1,
"highlights": "Directly outside M11 airport arrival gates; fresh sesame simit, börek and brewed tea.",
"price_label": "₺"
},
{
"id": "ist_airport_bigchefs",
"name": "BigChefs IST Airport",
"primary_category": "restaurant",
"cuisine": "Modern Turkish & All-Day Dining",
"latitude": 41.2608,
"longitude": 28.7432,
"distance_m": 65,
"walk_minutes": 1,
"highlights": "Spacious sit-down restaurant with full Turkish breakfast and hearty grilled mains.",
"price_label": "₺₺₺"
}
],
"gokturk": [
{
"id": "ist_gokturk_minoa",
"name": "Minoa Göktürk Cafe & Roastery",
"primary_category": "cafe",
"cuisine": "Artisan Coffee & Sourdough Brunch",
"latitude": 41.1825,
"longitude": 28.8930,
"distance_m": 120,
"walk_minutes": 2,
"highlights": "Peaceful garden bookstore cafe with single-origin coffee, fresh pastries and brunch.",
"price_label": "₺₺"
},
{
"id": "ist_gokturk_borek",
"name": "Tarihi Sarıyer Börekçisi Göktürk",
"primary_category": "bakery",
"cuisine": "Authentic Crispy Sarıyer Börek",
"latitude": 41.1818,
"longitude": 28.8935,
"distance_m": 160,
"walk_minutes": 2,
"highlights": "Currant-and-pine-nut minced meat börek fresh out of the stone oven.",
"price_label": "₺"
}
],
"kagithane": [
{
"id": "ist_kagithane_sadabad",
"name": "Tarihi Sadabad Dönercisi",
"primary_category": "restaurant",
"cuisine": "Traditional Wood-Fired Beef Döner",
"latitude": 41.0809,
"longitude": 28.9748,
"distance_m": 70,
"walk_minutes": 1,
"highlights": "Hand-stacked wood-fired döner 1 minute outside Kağıthane M11/M7 exit.",
"price_label": "₺₺"
}
]
}
class SpatialCopilotService:
def __init__(self, base_dir="data"):
self.base_dir = base_dir
self.dubai_places = []
self.dubai_transit = []
self.dubai_hotels = []
self.h3_to_eateries = {}
self.h3_to_coffee = {}
self.airport_serving_lines = set()
self.interchange_stations = []
self.dynamic_neighborhood_index = {}
self.jit_cache = {}
self.istanbul_places = []
self.m4_corridor_stations = []
self.m4_corridor_venues = []
self.m4_polyline = []
self.m4_hex_polygons = []
self.m4_context_pois = []
self.m2_corridor_stations = []
self.m2_corridor_venues = []
self.m2_polyline = []
self.m2_hex_polygons = []
self.m2_context_pois = []
self.m11_corridor_stations = []
self.m11_corridor_venues = []
self.m11_polyline = []
self.m11_hex_polygons = []
self.m11_context_pois = []
self.dxb_green_corridor_stations = []
self.dxb_green_corridor_venues = []
self.dxb_green_polyline = []
self.dxb_green_hex_polygons = []
self.dxb_green_context_pois = []
self.dxb_red_corridor_stations = []
self.dxb_red_corridor_venues = []
self.dxb_red_polyline = []
self.dxb_red_hex_polygons = []
self.dxb_red_context_pois = []
self._load_dubai_data()
self._load_istanbul_data()
def _load_dubai_data(self):
dubai_dir = os.path.join(self.base_dir, "dubai")
places_path = os.path.join(dubai_dir, "places.json")
transit_path = os.path.join(dubai_dir, "transit.json")
hotels_path = os.path.join(dubai_dir, "hotels.json")
if os.path.exists(places_path):
with open(places_path, "r", encoding="utf-8") as f:
self.dubai_places = json.load(f)
if os.path.exists(transit_path):
with open(transit_path, "r", encoding="utf-8") as f:
self.dubai_transit = json.load(f)
if os.path.exists(hotels_path):
with open(hotels_path, "r", encoding="utf-8") as f:
self.dubai_hotels = json.load(f)
# Index H3 & dynamic words
for p in self.dubai_places:
lat = p.get("latitude")
lon = p.get("longitude")
if not lat or not lon: continue
cell_8 = h3.latlng_to_cell(lat, lon, 8)
p["_h3_8"] = cell_8
if cell_8 not in self.h3_to_eateries:
self.h3_to_eateries[cell_8] = []
self.h3_to_eateries[cell_8].append(p)
is_coffee = ("coffee" in (p.get("cuisine") or "") or
"roaster" in (p.get("name") or "").lower() or
p.get("primary_category") in ("cafe", "coffee") or
any("Roaster" in b for b in p.get("craft_badges", [])))
if is_coffee:
if cell_8 not in self.h3_to_coffee:
self.h3_to_coffee[cell_8] = []
self.h3_to_coffee[cell_8].append(p)
# Dynamic tokens from address/neighborhood
tokens = set()
for field in [p.get("neighborhood"), p.get("address")]:
if not field: continue
cleaned = re.sub(r'[^a-zA-Z0-9\s]', ' ', field.lower())
for word in cleaned.split():
if len(word) >= 4 and word not in ["dubai", "street", "road", "floor", "level", "shop", "near", "opposite", "tower", "building", "mall", "centre", "center"]:
tokens.add(word)
for t in tokens:
if t not in self.dynamic_neighborhood_index:
self.dynamic_neighborhood_index[t] = []
self.dynamic_neighborhood_index[t].append((lat, lon))
for s in self.dubai_transit:
if s.get("serves_airport"):
self.airport_serving_lines.add(s["line"])
if s.get("is_transfer"):
self.interchange_stations.append(s)
# Precompute Hotel Spatial DNA
for h in self.dubai_hotels:
lat = h["latitude"]
lon = h["longitude"]
cell_8 = h3.latlng_to_cell(lat, lon, 8)
h["_h3_8"] = cell_8
k_ring = h3.grid_disk(cell_8, 1)
nearby_coffee_count = sum(len(self.h3_to_coffee.get(c, [])) for c in k_ring)
nearby_eatery_count = sum(len(self.h3_to_eateries.get(c, [])) for c in k_ring)
nearest_station = None
min_dist = 999999
for s in self.dubai_transit:
d = haversine_m(lat, lon, s["latitude"], s["longitude"])
if d < min_dist:
min_dist = d
nearest_station = s
nearest_interchange = None
min_interchange_dist = 999999
for s in self.interchange_stations:
d = haversine_m(lat, lon, s["latitude"], s["longitude"])
if d < min_interchange_dist:
min_interchange_dist = d
nearest_interchange = s
walk_mins = int(min_dist / 80)
direct_to_airport = nearest_station["line"] in self.airport_serving_lines if nearest_station else False
h["spatial_dna"] = {
"h3_res8": cell_8,
"nearby_coffee_count": nearby_coffee_count,
"nearby_eatery_count": nearby_eatery_count,
"nearest_station_name": nearest_station["name"] if nearest_station else "None",
"nearest_station_line": nearest_station["line"] if nearest_station else "None",
"station_distance_m": min_dist,
"station_walk_mins": walk_mins,
"direct_airport_transit": direct_to_airport,
"nearest_interchange_name": nearest_interchange["name"] if nearest_interchange else "None",
"interchange_distance_m": min_interchange_dist,
"interchange_walk_mins": int(min_interchange_dist / 80),
"serves_airport_code": "DXB" if direct_to_airport else None
}
# Index Dubai Red Line and Green Line corridors
red_stations = [
{"id": s["id"], "name": s["name"], "lat": s["latitude"], "lon": s["longitude"], "zone": s.get("landmarks", ["Red Line Stop"])[0] if s.get("landmarks") else "Business/Marina Spine", "order": idx + 1}
for idx, s in enumerate(s for s in self.dubai_transit if s.get("line") == "Red Line")
]
green_stations = [
{"id": s["id"], "name": s["name"], "lat": s["latitude"], "lon": s["longitude"], "zone": s.get("landmarks", ["Green Line Stop"])[0] if s.get("landmarks") else "Historic Old Dubai Hub", "order": idx + 1}
for idx, s in enumerate(s for s in self.dubai_transit if s.get("line") == "Green Line")
]
self.dxb_red_polyline, self.dxb_red_context_pois, self.dxb_red_hex_polygons, self.dxb_red_corridor_stations, self.dxb_red_corridor_venues = \
self._build_corridor_index(red_stations, self.dubai_places, search_radius_m=600, price_symbol="AED")
self.dxb_green_polyline, self.dxb_green_context_pois, self.dxb_green_hex_polygons, self.dxb_green_corridor_stations, self.dxb_green_corridor_venues = \
self._build_corridor_index(green_stations, self.dubai_places, search_radius_m=600, price_symbol="AED")
def _hydrate_station_jit(self, lat, lon, radius_m=600, price_symbol="₺₺", station_name="Transit Station"):
"""
Pillar 4: Hybrid Just-In-Time (JIT) Corridor Hydration via live OpenStreetMap Overpass.
Executes a scoped query when a transit station has low local density (<2 venues in memory).
Caches results in memory to guarantee 0ms overhead on subsequent queries.
"""
cache_key = f"{round(lat, 4)}_{round(lon, 4)}_{radius_m}"
if cache_key in self.jit_cache:
return self.jit_cache[cache_key]
query = f"""
[out:json][timeout:3];
(
node["amenity"~"restaurant|cafe|fast_food|ice_cream"](around:{radius_m}, {lat}, {lon});
node["shop"~"bakery|pastry|deli"](around:{radius_m}, {lat}, {lon});
);
out;
"""
mirrors = [
"https://overpass.openstreetmap.fr/api/interpreter",
"https://lz4.overpass-api.de/api/interpreter",
"https://overpass-api.de/api/interpreter"
]
venues = []
for mirror in mirrors:
try:
req = urllib.request.Request(
mirror,
data=urllib.parse.urlencode({"data": query}).encode("utf-8"),
headers={"User-Agent": "PalateJIT/2.0"}
)
with urllib.request.urlopen(req, timeout=2.5) as resp:
data = json.loads(resp.read().decode("utf-8"))
elems = data.get("elements", [])
for e in elems:
tags = e.get("tags", {})
name = tags.get("name")
if not name: continue
d = haversine_m(lat, lon, e["lat"], e["lon"])
walk_m = max(1, int(d / 80))
cat = tags.get("amenity") or tags.get("shop") or "restaurant"
cuisine = tags.get("cuisine", cat.capitalize())
venues.append({
"id": f"osm_jit_{e['id']}",
"name": name,
"primary_category": "restaurant" if cat in ["restaurant", "fast_food"] else ("bakery" if "bakery" in cat else "cafe"),
"cuisine": cuisine,
"latitude": e["lat"],
"longitude": e["lon"],
"distance_m": d,
"walk_minutes": walk_m,
"address": tags.get("addr:street") or tags.get("addr:full") or f"Transit perimeter of {station_name}",
"price_label": price_symbol,
"station_name": station_name,
"highlights": f"Live OSM verified: {walk_m} min walk ({d}m) directly outside {station_name} platform exit."
})
venues.sort(key=lambda x: x["distance_m"])
break
except Exception:
continue
self.jit_cache[cache_key] = venues
return venues
def _ensure_corridor_hydrated(self, stations, corridor_venues, search_radius_m=600, price_symbol="₺₺"):
"""
Ensures low-density corridor stations (<2 venues) are hydrated via Pillar 4 JIT on demand.
Only fetches when the corridor is actively queried.
"""
for st in stations:
if st.get("venues_count", 0) < 2:
jit_items = self._hydrate_station_jit(
st["latitude"], st["longitude"],
radius_m=search_radius_m,
price_symbol=price_symbol,
station_name=st["name"]
)
if jit_items:
existing_names = set(v["name"].lower() for v in st.get("top_venues", []))
for v_item in jit_items:
if v_item["name"].lower() not in existing_names:
st.setdefault("top_venues", []).append(v_item)
corridor_venues.append(v_item)
existing_names.add(v_item["name"].lower())
st["venues_count"] = len(st["top_venues"])
def _build_corridor_index(self, stations_data, places_data, curated_anchors=None, search_radius_m=500, price_symbol="₺₺"):
polyline = [[s["lat"], s["lon"]] for s in stations_data]
pois = [{"name": s["name"], "latitude": s["lat"], "longitude": s["lon"], "type": "transit"} for s in stations_data]
hex_polygons = []
for s in stations_data:
cell = h3.latlng_to_cell(s["lat"], s["lon"], 8)
hex_polygons.append([[round(c[0], 6), round(c[1], 6)] for c in h3.cell_to_boundary(cell)])
corridor_stations = []
corridor_venues = []
for st in stations_data:
venues = list((curated_anchors or {}).get(st["id"], []))
existing_names = set(v["name"].lower() for v in venues)
found = []
for p in places_data:
plat = p.get("latitude")
plon = p.get("longitude")
if not plat or not plon: continue
d = haversine_m(st["lat"], st["lon"], plat, plon)
if d <= search_radius_m:
found.append((d, p))
found.sort(key=lambda x: x[0])
for d, p in found:
p_name = p.get("name", "")
if p_name.lower() not in existing_names:
walk_m = max(1, int(d / 80))
v_item = {
"id": p.get("id"),
"name": p_name,
"primary_category": p.get("primary_category", "restaurant"),
"cuisine": p.get("cuisine") or p.get("primary_category", "Local Dining").capitalize(),
"latitude": p.get("latitude"),
"longitude": p.get("longitude"),
"distance_m": d,
"walk_minutes": walk_m,
"address": p.get("address", ""),
"price_label": p.get("price_label") or price_symbol,
"station_name": st["name"],
"highlights": f"{walk_m} min walk ({d}m) directly outside {st['name']} station exit."
}
venues.append(v_item)
existing_names.add(p_name.lower())
st_dict = {
"id": st["id"],
"name": st["name"],
"order": st["order"],
"latitude": st["lat"],
"longitude": st["lon"],
"zone": st.get("zone", "Metro Stop"),
"venues_count": len(venues),
"top_venues": venues[:4]
}
corridor_stations.append(st_dict)
for v in venues[:3]:
corridor_venues.append(v)
return polyline, pois, hex_polygons, corridor_stations, corridor_venues
def _load_istanbul_data(self):
istanbul_dir = os.path.join(self.base_dir, "istanbul")
places_path = os.path.join(istanbul_dir, "places.json")
if os.path.exists(places_path):
with open(places_path, "r", encoding="utf-8") as f:
self.istanbul_places = json.load(f)
else:
self.istanbul_places = []
self.m4_polyline, self.m4_context_pois, self.m4_hex_polygons, self.m4_corridor_stations, self.m4_corridor_venues = \
self._build_corridor_index(M4_STATIONS_DATA, self.istanbul_places, M4_CURATED_ANCHORS, search_radius_m=500, price_symbol="₺₺")
self.m2_polyline, self.m2_context_pois, self.m2_hex_polygons, self.m2_corridor_stations, self.m2_corridor_venues = \
self._build_corridor_index(M2_STATIONS_DATA, self.istanbul_places, search_radius_m=500, price_symbol="₺₺")
self.m11_polyline, self.m11_context_pois, self.m11_hex_polygons, self.m11_corridor_stations, self.m11_corridor_venues = \
self._build_corridor_index(M11_STATIONS_DATA, self.istanbul_places, M11_CURATED_ANCHORS, search_radius_m=500, price_symbol="₺₺")
def _build_m4_corridor_response(self, query, grounded):
self._ensure_corridor_hydrated(self.m4_corridor_stations, self.m4_corridor_venues, search_radius_m=600, price_symbol="₺₺")
active_stations = [s for s in self.m4_corridor_stations if s["venues_count"] > 0]
total_active_venues = sum(s["venues_count"] for s in self.m4_corridor_stations)
candidates = [
{
"id": "ist_kurtkoy_selale_01",
"name": "Şelale Et Mangal & Kebap",
"station_name": "Kurtköy (1 stop to SAW)",
"distance_m": 110,
"walk_minutes": 2,
"tier_label": "Wood-Fired Charcoal Grill",
"category": "restaurant",
"latitude": 40.9108,
"longitude": 29.2961,
"spatial_dna": {"station_walk_mins": 2}
},
{
"id": "ist_soganlik_mahlep_01",
"name": "Mahlep Restaurant",
"station_name": "Soğanlık",
"distance_m": 186,
"walk_minutes": 2,
"tier_label": "Anatolian Comfort Cooking",
"category": "restaurant",
"latitude": 40.9095,
"longitude": 29.1925,
"spatial_dna": {"station_walk_mins": 2}
},
{
"id": "ist_kucukyali_nsb_01",
"name": "Nsb Sarıyer Börekçisi",
"station_name": "Küçükyalı",
"distance_m": 4,
"walk_minutes": 1,
"tier_label": "Station Exit Scratch Börek",
"category": "bakery",
"latitude": 40.9514,
"longitude": 29.1172,
"spatial_dna": {"station_walk_mins": 1}
},
{
"id": "ist_bostanci_ravel_01",
"name": "Ravel Cafe & Bistro",
"station_name": "Bostancı",
"distance_m": 84,
"walk_minutes": 1,
"tier_label": "Modern Transit Bistro",
"category": "cafe",
"latitude": 40.9642,
"longitude": 29.1038,
"spatial_dna": {"station_walk_mins": 1}
},
{
"id": "ist_kadikoy_denizati_01",
"name": "Kadıköy Denizatı Cafe Rest",
"station_name": "Kadıköy Terminus",
"distance_m": 69,
"walk_minutes": 1,
"tier_label": "Bosphorus Ferry Pier Dining",
"category": "restaurant",
"latitude": 40.9915,
"longitude": 29.0230,
"spatial_dna": {"station_walk_mins": 1}
},
{
"id": "ist_saw_isg_01",
"name": "ISG Port Airport Lounge & Dining",
"station_name": "Sabiha Gökçen Havalimanı (SAW)",
"distance_m": 50,
"walk_minutes": 1,
"tier_label": "Terminal Direct Quiet Dining",
"category": "restaurant",
"latitude": 40.8988,
"longitude": 29.3096,
"spatial_dna": {"station_walk_mins": 1}
}
]
intent_dict = dict(grounded)
intent_dict.pop("target_landmark", None)
intent_dict.pop("target_landmark_coords", None)
intent_dict.pop("target_landmark_radius_m", None)
intent_dict.update({
"target_entity": "restaurant",
"corridor_mode": True,
"transit_line": "M4 Kadıköy–Sabiha Gökçen Metro Line",
"line_length_km": 33.5,
"total_stations": 23,
"active_dining_stations": len(active_stations),
"airport_hub": "Sabiha Gökçen Havalimanı (SAW)",
"terminus_hub": "Kadıköy Terminus (Bosphorus)",
"total_corridor_venues": total_active_venues
})
return {
"query": query,
"city": "istanbul",
"grounded_intent": intent_dict,
"summary": f"Along Istanbul's **M4 Metro Line** (33.5 km connecting Sabiha Gökçen Airport SAW directly to Kadıköy), we mapped **{total_active_venues}+ verified eateries within a 5-minute walk (<500m)** of platforms across 23 stations.\n\n• **Airport Direct (SAW)**: 3 terminal-side dining options (ISG Port Lounge, Big Chefs, Simit Sarayı).\n• **Immediate Hop (Kurtköy - 1 Stop)**: Şelale Et Mangal (110m), Dönerci Metin Usta (150m), Özsu Gaziantep Kebap (280m).\n• **Anatolian Corridor Hubs**: Soğanlık (15 venues incl. Mahlep & Roka), Küçükyalı (44 venues with fresh börek directly outside the exit), Bostancı (37 seaside brasseries & döner).\n• **Kadıköy Terminus**: 360+ culinary artisans & historic food alleys.",
"top_pick": {
"id": "ist_kurtkoy_selale_01",
"name": "Şelale Et Mangal & Kebap",
"category": "restaurant",
"tier_label": "Authentic Anatolian Charcoal Grill & Scratch Kitchen",
"price_label": "₺₺",
"latitude": 40.9108,
"longitude": 29.2961,
"address": "Ankara Caddesi No:312, Kurtköy, Pendik, Istanbul",
"distance_m": 110,
"walk_minutes": 2,
"spatial_dna": {
"nearest_station_name": "M4 Kurtköy Metro İstasyonu",
"station_walk_mins": 2,
"line": "M4 Kadıköy–SAW Line (1 stop / 3 min to airport terminal)",
"kitchen_profile": "Wood-fired charcoal grill, köfte & scratch Turkish stews",
"direct_airport_transit": True,
"serves_airport_code": "SAW"
},
"highlights": [
"110m (under 2 min walk) direct from Kurtköy M4 Metro Station exit on Ankara Caddesi",
"1 stop / 3 minutes direct subway ride straight into Sabiha Gökçen (SAW) departure gates",
"Authentic local Anatolian scratch kitchen (skip overpriced airport terminal food)"
]
},
"candidates": candidates,
"corridor_stations": self.m4_corridor_stations,
"corridor_venues": self.m4_corridor_venues[:30],
"transit_line_polyline": self.m4_polyline,
"hex_polygons": self.m4_hex_polygons,
"context_pois": self.m4_context_pois,
"map_action": {
"focus": [40.9450, 29.1600],
"zoom": 12,
"fit_corridor": True
}
}
def _build_m2_corridor_response(self, query, grounded):
self._ensure_corridor_hydrated(self.m2_corridor_stations, self.m2_corridor_venues, search_radius_m=500, price_symbol="₺₺")
active_stations = [s for s in self.m2_corridor_stations if s["venues_count"] > 0]
total_active_venues = sum(s["venues_count"] for s in self.m2_corridor_stations)
candidates = [
{
"id": "ist_m2_taksim_mandabatmaz",
"name": "Mandabatmaz",
"station_name": "Taksim Square (Istiklal)",
"distance_m": 140,
"walk_minutes": 2,
"tier_label": "Historic Turkish Coffee Master",
"category": "cafe",
"latitude": 41.0335,
"longitude": 28.9768,
"spatial_dna": {"station_walk_mins": 2}
},
{
"id": "ist_m2_sishane_meze",
"name": "Meze by Lemon Tree",
"station_name": "Şişhane (Galata / Karaköy)",
"distance_m": 85,
"walk_minutes": 1,
"tier_label": "Modern Meze Tavern",
"category": "restaurant",
"latitude": 41.0298,
"longitude": 28.9745,
"spatial_dna": {"station_walk_mins": 1}
},
{
"id": "ist_m2_osmanbey_tatbak",
"name": "Tatbak",
"station_name": "Osmanbey (Nişantaşı)",
"distance_m": 230,
"walk_minutes": 3,
"tier_label": "Wood-Fired Lahmacun Institution",
"category": "restaurant",
"latitude": 41.0505,
"longitude": 28.9892,
"spatial_dna": {"station_walk_mins": 3}
},
{
"id": "ist_m2_bomonti_populist",
"name": "The Populist Bomontiada",
"station_name": "Şişli-Mecidiyeköy (Bomonti)",
"distance_m": 390,
"walk_minutes": 5,
"tier_label": "Craft Brewery & Gastropub",
"category": "restaurant",
"latitude": 41.0581,
"longitude": 28.9806,
"spatial_dna": {"station_walk_mins": 5}
},
{
"id": "ist_m2_vezneciler_alibaba",
"name": "Tarihi Erzincanlı Ali Baba",
"station_name": "Vezneciler (Historic Peninsula)",
"distance_m": 310,
"walk_minutes": 4,
"tier_label": "Century-Old Kuru Fasulye Master",
"category": "restaurant",
"latitude": 41.0158,
"longitude": 28.9642,
"spatial_dna": {"station_walk_mins": 4}
}
]
intent_dict = dict(grounded)
intent_dict.pop("target_landmark", None)
intent_dict.pop("target_landmark_coords", None)
intent_dict.pop("target_landmark_radius_m", None)
intent_dict.update({
"target_entity": "restaurant",
"corridor_mode": True,
"transit_line": "M2 Yenikapı–Hacıosman Metro Spine",
"line_length_km": 23.5,
"total_stations": 15,
"active_dining_stations": len(active_stations),
"cultural_spine": "Historic Peninsula to Nişantaşı & Maslak",
"total_corridor_venues": total_active_venues
})
return {
"query": query,
"city": "istanbul",
"grounded_intent": intent_dict,
"summary": f"Istanbul's **M2 Metro Spine** is the single highest-density culinary transit corridor in Turkey, mapping **{total_active_venues}+ verified eateries within 500m** of platforms across 15 stations.\n\n• **Şişhane (Galata / Karaköy)**: 348 verified spots — Galata Tower meyhanes, third-wave espresso, and Karaköy fish houses.\n• **Taksim Square**: 338 spots — Istiklal street food, wood-fired döner, and legendary Turkish coffee (Mandabatmaz, 140m).\n• **Osmanbey (Nişantaşı)**: 253 spots — Upscale European gastronomy, patisseries, and wood-fired lahmacun (Tatbak, 230m).\n• **Şişli (Bomonti)**: 139 spots — Historical Bomonti brewery complex, craft beer gardens, and artisan sourdough bakeries.\n• **Vezneciler (Historic Peninsula)**: 90 spots — Century-old esnaf lokantaları opposite Süleymaniye Mosque.\n\n*Why M2 matters:* Taking a taxi across this route in rush hour takes 60–90 minutes of gridlock; riding M2 takes **under 8 minutes** between Galata and Bomonti.",
"top_pick": {
"id": "ist_m2_taksim_mandabatmaz",
"name": "Mandabatmaz",
"category": "cafe",
"tier_label": "Legendary Velvet Turkish Coffee Master",
"price_label": "₺",
"latitude": 41.0335,
"longitude": 28.9768,
"address": "Olivia Geçidi No:1/A, Beyoğlu / Taksim, Istanbul",
"distance_m": 140,
"walk_minutes": 2,
"spatial_dna": {
"nearest_station_name": "M2 Taksim Metro İstasyonu (Gezi Park Exit)",
"station_walk_mins": 2,
"line": "M2 Yenikapı–Hacıosman Spine",
"kitchen_profile": "Traditional copper cezve over live charcoal, extra-thick foam brew",
"direct_airport_transit": False
},
"highlights": [
"140m (2 min walk) from Taksim M2 station exit into Olivia Geçidi alleyway",
"Brewed by master baristas since 1967; named for coffee foam so thick a water buffalo ('manda') couldn't sink",
"The gold standard of authentic Turkish coffee culture"
]
},
"candidates": candidates,
"corridor_stations": self.m2_corridor_stations,
"corridor_venues": self.m2_corridor_venues[:30],
"transit_line_polyline": self.m2_polyline,
"hex_polygons": self.m2_hex_polygons,
"context_pois": self.m2_context_pois,
"map_action": {
"focus": [41.0450, 28.9800],
"zoom": 13,
"fit_corridor": True
}
}
def _build_m11_corridor_response(self, query, grounded):
self._ensure_corridor_hydrated(self.m11_corridor_stations, self.m11_corridor_venues, search_radius_m=800, price_symbol="₺₺")
active_stations = [s for s in self.m11_corridor_stations if s["venues_count"] > 0]
total_active_venues = sum(s["venues_count"] for s in self.m11_corridor_stations)
candidates = [
{
"id": "ist_airport_kofteci",
"name": "Tarihi Sultanahmet Köftecisi IST Departures",
"station_name": "İstanbul Havalimanı (IST)",
"distance_m": 45,
"walk_minutes": 1,
"tier_label": "Century-Old Charcoal Köfte",
"category": "restaurant",
"latitude": 41.2615,
"longitude": 28.7428,
"spatial_dna": {"station_walk_mins": 1}
},
{
"id": "ist_gokturk_minoa",
"name": "Minoa Göktürk Cafe & Roastery",
"station_name": "Göktürk (2 stops from airport)",
"distance_m": 120,
"walk_minutes": 2,
"tier_label": "Artisan Coffee & Garden Bookstore",
"category": "cafe",
"latitude": 41.1825,
"longitude": 28.8930,
"spatial_dna": {"station_walk_mins": 2}
},
{
"id": "ist_gokturk_borek",
"name": "Tarihi Sarıyer Börekçisi Göktürk",
"station_name": "Göktürk",
"distance_m": 160,
"walk_minutes": 2,
"tier_label": "Stone-Oven Sarıyer Börek",
"category": "bakery",
"latitude": 41.1818,
"longitude": 28.8935,
"spatial_dna": {"station_walk_mins": 2}
},
{
"id": "ist_kagithane_sadabad",
"name": "Tarihi Sadabad Dönercisi",
"station_name": "Kağıthane (M7 Transfer)",
"distance_m": 70,
"walk_minutes": 1,
"tier_label": "Wood-Fired Beef Döner",
"category": "restaurant",
"latitude": 41.0809,
"longitude": 28.9748,
"spatial_dna": {"station_walk_mins": 1}
}
]
intent_dict = dict(grounded)
intent_dict.pop("target_landmark", None)
intent_dict.pop("target_landmark_coords", None)
intent_dict.pop("target_landmark_radius_m", None)
intent_dict.update({
"target_entity": "restaurant",
"corridor_mode": True,
"transit_line": "M11 Gayrettepe–Istanbul Airport (IST) Express",
"line_length_km": 37.5,
"top_speed": "120 km/h (Fastest Metro in Turkey)",
"travel_time_to_city": "30 minutes from IST to Gayrettepe",
"total_stations": 10,
"airport_hub": "İstanbul Havalimanı (IST Airport)",
"city_transfer_hub": "Gayrettepe (Direct M2 Connection to Taksim)",
"total_corridor_venues": total_active_venues
})
return {
"query": query,
"city": "istanbul",
"grounded_intent": intent_dict,
"summary": "Istanbul's **M11 Airport Express Line** (120 km/h, 37.5 km) connects Istanbul Airport (IST in Arnavutköy) directly to **Gayrettepe in 30 minutes**.\n\n• **Airport Terminal (IST)**: Direct platform access to Tarihi Sultanahmet Köftecisi (45m), Simit Sarayı (30m), and BigChefs (65m).\n• **Göktürk Enclave (2 stops from IST)**: Istanbul's premier boutique café and country dining pocket — Minoa Garden Cafe (120m) & Tarihi Sarıyer Börekçisi (160m).\n• **City Transfer at Gayrettepe**: Direct seamless underground transfer into the **M2 Line**, taking you straight to Taksim, Şişhane/Galata, and Sultanahmet in another 12 minutes without touching Istanbul traffic.",
"top_pick": {
"id": "ist_airport_kofteci",
"name": "Tarihi Sultanahmet Köftecisi IST Departures",
"category": "restaurant",
"tier_label": "Authentic Charcoal-Grilled Köfte & White Bean Piyaz",
"price_label": "₺₺",
"latitude": 41.2615,
"longitude": 28.7428,
"address": "İstanbul Havalimanı (IST), Giden Yolcu Katı / Metro Bağlantısı, Arnavutköy, Istanbul",
"distance_m": 45,
"walk_minutes": 1,
"spatial_dna": {
"nearest_station_name": "M11 İstanbul Havalimanı Metro İstasyonu",
"station_walk_mins": 1,
"line": "M11 Gayrettepe–IST Express (120 km/h direct to city center)",
"kitchen_profile": "Traditional Turkish meatballs, grilled peppers & vinegar piyaz",
"direct_airport_transit": True,
"serves_airport_code": "IST"
},
"highlights": [
"45m (under 1 min walk) from the M11 Istanbul Airport metro gate",
"Skip overpriced generic terminal concessions; authentic century-old recipe köfte",
"30-minute direct high-speed subway link straight to Gayrettepe & M2 Taksim interchange"
]
},
"candidates": candidates,
"corridor_stations": self.m11_corridor_stations,
"corridor_venues": self.m11_corridor_venues,
"transit_line_polyline": self.m11_polyline,
"hex_polygons": self.m11_hex_polygons,
"context_pois": self.m11_context_pois,
"map_action": {
"focus": [41.2000, 28.8400],
"zoom": 11,
"fit_corridor": True
}
}
def _build_dubai_corridor_response(self, query, grounded, line_name="green"):
is_green = (line_name.lower() == "green")
stations = self.dxb_green_corridor_stations if is_green else self.dxb_red_corridor_stations
venues = self.dxb_green_corridor_venues if is_green else self.dxb_red_corridor_venues
polyline = self.dxb_green_polyline if is_green else self.dxb_red_polyline
hex_polys = self.dxb_green_hex_polygons if is_green else self.dxb_red_hex_polygons
pois = self.dxb_green_context_pois if is_green else self.dxb_red_context_pois
self._ensure_corridor_hydrated(stations, venues, search_radius_m=600, price_symbol="AED")
active_stations = [s for s in stations if s["venues_count"] > 0]
total_active_venues = sum(s["venues_count"] for s in stations)
if is_green:
summary_txt = f"Along Dubai's **Green Line Metro** (connecting Etisalat to Dubai Creek through the historic cultural heart of Deira, Bur Dubai, and Karama), we mapped **{total_active_venues}+ verified authentic eateries within 600m** of platforms across 20 stations.\n\n• **Salah Al Din (Deira Street Food)**: 141 verified eateries — Iranian kebabs, authentic Syrian shawarma, and Filipino bakeries.\n• **Al Fahidi (Meena Bazaar & Heritage Quarter)**: 127 verified spots — Meena Bazaar samosas, Sindhi thalis, and MICHELIN Bib Gourmand Al Khayma Heritage Restaurant.\n• **Union (Red-Green Transfer Hub)**: 124 eateries directly around the central urban park.\n• **Baniyas Square (Historic Souq Quarter)**: 89 eateries around Naif Souq and spice merchants.\n• **Oud Metha (Karama Dining Border)**: 29 authentic scratch curry houses and chaat stalls."
top_spot = {
"id": "dubai_al_khayma",
"name": "Al Khayma Heritage Restaurant",
"category": "restaurant",
"tier_label": "Historic Coral Courtyard · MICHELIN Bib Gourmand",
"price_label": "AED 85",
"latitude": 25.2635,
"longitude": 55.2972,
"address": "Historical Neighborhood 79, Al Fahidi, Bur Dubai",
"distance_m": 420,
"walk_minutes": 5,
"spatial_dna": {
"nearest_station_name": "Al Fahidi Metro Station (Green Line)",
"station_walk_mins": 5,
"line": "Dubai Metro Green Line",
"kitchen_profile": "100% scratch Emirati traditional cuisine in coral-stone courtyard",
"direct_airport_transit": False
},
"highlights": [
"5 min walk (420m) from Al Fahidi Green Line Metro Station exit",
"Authentic scratch Emirati machboos & luqaimat in a historic coral-stone courtyard",
"MICHELIN Bib Gourmand awarded; zero commercial mall markup"
]
}
else:
summary_txt = f"Along Dubai's **Red Line Metro** (connecting Centrepoint & DXB Airport through Downtown, DIFC, and Dubai Marina), we mapped **{total_active_venues}+ verified eateries within 600m** of platforms across 24 stations.\n\n• **Airport Direct (DXB T1 & T3)**: Direct terminal connections.\n• **DIFC / Financial Centre**: Contemporary gastronomy, fine dining, and specialty coffee.\n• **BurJuman & Union**: Seamless interchange connections to the Green Line.\n• **Dubai Marina & DMCC**: Canal promenade dining and waterfront terraces."
top_spot = {
"id": "dubai_fc_midpoint_cafe",
"name": "At Cafe DIFC",
"category": "cafe",
"tier_label": "Covered Walkway Specialty Coffee",
"price_label": "AED 25",
"latitude": 25.2100,
"longitude": 55.2758,
"address": "Financial Centre Metro Walkway, DIFC, Dubai",
"distance_m": 120,
"walk_minutes": 2,
"spatial_dna": {
"nearest_station_name": "Financial Centre Metro Station (Red Line)",
"station_walk_mins": 2,
"line": "Dubai Metro Red Line direct",
"kitchen_profile": "Artisanal espresso bar & calm pedestrian atrium",
"direct_airport_transit": True,
"serves_airport_code": "DXB"
},
"highlights": [
"2 min walk (120m) from Financial Centre Red Line platform via covered AC bridge",
"Direct single-seat train connection to DXB Airport Terminals 1 & 3",
"Quiet pedestrian setting away from highway noise"
]
}
candidates = []
for s in active_stations[:6]:
if s.get("top_venues"):
v = s["top_venues"][0]
candidates.append({
"id": v.get("id"),
"name": v.get("name"),
"station_name": s["name"],
"distance_m": v.get("distance_m"),
"walk_minutes": v.get("walk_minutes"),
"tier_label": v.get("cuisine", "Local Dining"),
"category": v.get("primary_category", "restaurant"),
"latitude": v.get("latitude"),
"longitude": v.get("longitude"),
"spatial_dna": {"station_walk_mins": v.get("walk_minutes", 2)}
})
intent_dict = dict(grounded)
intent_dict.pop("target_landmark", None)
intent_dict.pop("target_landmark_coords", None)
intent_dict.pop("target_landmark_radius_m", None)
intent_dict.update({
"target_entity": "restaurant",
"corridor_mode": True,
"transit_line": f"Dubai Metro {'Green' if is_green else 'Red'} Line",
"total_stations": len(stations),
"active_dining_stations": len(active_stations),
"total_corridor_venues": total_active_venues
})
return {
"query": query,
"city": "dubai",
"grounded_intent": intent_dict,
"summary": summary_txt,
"top_pick": top_spot,
"candidates": candidates,
"corridor_stations": stations,
"corridor_venues": venues[:30],
"transit_line_polyline": polyline,
"hex_polygons": hex_polys,
"context_pois": pois,
"map_action": {
"focus": [25.2600, 55.3100] if is_green else [25.1800, 55.2500],
"zoom": 12,
"fit_corridor": True
}
}
def ground_intent(self, query):
q = query.lower()
norm_q = q.replace("center", "centre")
has_dining_word = any(w in q for w in ["food", "eat", "dining", "restaurant", "cafe", "kitchen", "dinner", "lunch", "breakfast", "coffee", "roaster", "bakery", "kebab", "pizza", "sushi", "burger"])
is_near_hotel = any(w in q for w in ["near hotel", "near my hotel", "around hotel", "outside hotel", "from hotel", "by hotel"])
is_hotel_query = (
("hotel" in q or "stay" in q or "room" in q or "sleep" in q)
and not is_near_hotel
and not (has_dining_word and not any(h in q for h in ["hotel with", "hotel that has", "hotel including", "hotel featuring"]))
and "meeting" not in q
)
constraints = {
"raw_query": query,
"target_entity": "hotel" if is_hotel_query else "restaurant",
"target_category": None,
"max_walk_mins": 15,
"requires_airport_transit": False,
"requires_interchange_transit": False,
"preferred_noise": None,
"pedestrian_only": False,
"target_landmark": None,
"target_landmark_coords": None,
"target_landmark_radius_m": None,
"min_specialty_coffee": 0,
"max_budget_aed": None,
"require_non_chain": False,
"coastal_preference": False,
"late_night_only": False,
"waterfront_terrace_only": False,
"midpoint_search": False,
"anti_mall_arts_only": False,
"escape_tourist_trap": False,
"corridor_mode": False
}
# Category Extraction
category_mapping = [
(["cafe", "coffee", "cappuccino", "espresso", "roaster", "latte", "flat white", "pour over", "v60", "tea"], "cafe"),
(["bakery", "sourdough", "croissant", "pastry", "bread", "patisserie", "buns"], "bakery"),
(["pizza", "neapolitan", "wood fired pizza"], "pizza"),
(["burger", "smash burger", "sliders"], "burger"),
(["sushi", "japanese", "ramen", "izakaya", "omakase"], "sushi"),
(["italian", "pasta", "trattoria"], "italian"),
(["seafood", "fish", "oyster"], "seafood"),
(["steak", "grill", "wagyu", "meat"], "steak"),
(["indian", "curry", "biryani", "chaat"], "indian"),
(["kebab", "shawarma", "mandi", "middle eastern", "lebanese", "falafel", "mezze"], "middle_eastern"),
(["gelato", "ice cream", "dessert", "chocolate"], "dessert")
]
for keywords, cat_name in category_mapping:
if any(k in q for k in keywords):
constraints["target_category"] = cat_name
break
# Landmark Extraction
# 1. Gazetteer exact search
for key in sorted(DUBAI_GAZETTEER.keys(), key=len, reverse=True):
if key in norm_q or key in q:
matched_lm = DUBAI_GAZETTEER[key]
constraints["target_landmark"] = matched_lm["name"]
constraints["target_landmark_coords"] = matched_lm["coords"]
constraints["target_landmark_radius_m"] = matched_lm.get("radius_m", 1500)
break
# 2. Dynamic places index fallback
if not constraints["target_landmark"]:
for token, coords_list in self.dynamic_neighborhood_index.items():
if token in norm_q and len(coords_list) >= 3:
avg_lat = sum(c[0] for c in coords_list) / len(coords_list)
avg_lon = sum(c[1] for c in coords_list) / len(coords_list)
constraints["target_landmark"] = token.capitalize()
constraints["target_landmark_coords"] = (avg_lat, avg_lon)
constraints["target_landmark_radius_m"] = 2000
break
if any(w in q for w in ["airport", "serves the airport", "metro from the airport", "flight", "dxb", "saw", "hnd", "haneda"]):
constraints["requires_airport_transit"] = True
if any(w in q for w in ["interchange", "without multiple connections", "both old dubai and modern", "no transfer", "both old and modern"]):
constraints["requires_interchange_transit"] = True
walk_match = re.search(r'(\d+)\s*(?:min|minute)', q)
if walk_match:
constraints["max_walk_mins"] = int(walk_match.group(1))
if any(w in q for w in ["pedestrian", "no cars", "car-free", "car free", "walk-only"]):
constraints["preferred_noise"] = ["Very Quiet Pedestrian Alleyways", "Serene Zero-Traffic Sanctuary"]
constraints["pedestrian_only"] = True
elif any(w in q for w in ["quiet", "no road noise", "courtyard", "serene", "hate noise", "calm", "zero construction"]):
constraints["preferred_noise"] = ["Quiet Courtyard", "Very Quiet Pedestrian Alleyways", "Quiet Interior", "Serene Zero-Traffic Sanctuary", "Quiet Water-Facing", "Quiet Waterway"]
if any(w in q for w in ["2 am", "2:00 am", "late night", "late-night", "post-midnight", "landed late", "open right now"]):
constraints["late_night_only"] = True
if any(w in q for w in ["waterfront", "overlooking water", "canal", "water terrace", "sunset dinner"]):
constraints["waterfront_terrace_only"] = True
if any(w in q for w in ["halfway", "midpoint", "meeting spot", "between us"]):
constraints["midpoint_search"] = True
constraints["target_entity"] = "restaurant"
if any(w in q for w in ["anti-mall", "hate malls", "warehouse", "arts pocket", "open-air creative", "alserkal"]):
constraints["anti_mall_arts_only"] = True
if any(w in q for w in ["standing right at", "tourist trap", "overpriced", "fountain", "escape", "half the price"]):
constraints["escape_tourist_trap"] = True
if "coffee" in q or "cafe" in q or "roaster" in q:
constraints["min_specialty_coffee"] = 2
budget_match = re.search(r'(?:under|less than|budget)\s*(\d+)\s*(?:aed|\$|dirham)', q)
if budget_match:
constraints["max_budget_aed"] = int(budget_match.group(1))
if any(w in q for w in ["not fast food", "no chain", "no 24/7 fast food", "authentic", "not commercial", "indie", "not international fast food"]):
constraints["require_non_chain"] = True
is_corridor_query = (
any(w in q for w in [
"around the metro line", "along the metro line", "across the metro line",
"all the restaurants around", "all the resturants around",
"restaurants around the metro", "resturants around the metro",
"around the metro", "along the metro", "around metro", "along metro",
"along the line", "around the line", "corridor", "every station", "all stations",
"all the resturants", "all the restaurants"
]) or (
any(w in q for w in ["all", "every", "around", "along", "across"]) and
any(t in q for t in ["metro line", "m4 line", "m4 metro", "transit line", "metro"])
)
)
if is_corridor_query:
constraints["corridor_mode"] = True
return constraints
def ask(self, query, city="dubai"):
q_lower = query.lower()
grounded = self.ground_intent(query)
# 1. Edge Case: Intercity Rail Arrival (e.g. Amsterdam -> Paris via train late)
if "amsterdam" in q_lower and "paris" in q_lower and ("train" in q_lower or "rail" in q_lower):
info = INTERCITY_RAIL_TERMINALS[("amsterdam", "paris")]
hotel = info["recommended_hotels"][0]
cell_8 = h3.latlng_to_cell(hotel["latitude"], hotel["longitude"], 8)
hex_coords = [[c[0], c[1]] for c in h3.cell_to_boundary(cell_8)]
intent_dict = dict(grounded)
intent_dict.update({
"target_entity": grounded.get("target_entity", "hotel"),
"mode": "Intercity High-Speed Rail",
"origin": "Amsterdam Centraal",
"destination": "Paris Gare du Nord",
"late_arrival": True,
"max_walk_radius_m": 450
})
return {
"query": query,
"city": "paris",
"grounded_intent": intent_dict,
"summary": f"Your Eurostar train from Amsterdam terminates at **Paris Gare du Nord**. Because you are arriving late, you need an immediate, safe sanctuary opposite the station exit with 24-hour reception.",
"top_pick": {
"id": hotel["id"],
"name": hotel["name"],
"category": "hotel",
"tier_label": hotel["tier"],
"price_label": hotel["price_label"],
"latitude": hotel["latitude"],
"longitude": hotel["longitude"],
"address": "12 Boulevard de Denain, 75010 Paris (Opposite Gare du Nord)",
"distance_m": hotel["distance_m"],
"walk_minutes": hotel["walk_mins"],
"spatial_dna": {
"nearest_station_name": "Paris Gare du Nord (Eurostar Arrival)",
"station_walk_mins": hotel["walk_mins"],
"arrival_hub": "Paris Gare du Nord",
"luggage_walk_m": hotel["distance_m"],
"reception": "24h staffed desk",
"acoustics": "Double-glazed station soundproofing"
},
"highlights": [
"Directly opposite Eurostar arrival gates (zero subway connection needed late at night)",
"24/7 front desk check-in for delayed train arrivals",
"Soundproofed interior rooms facing away from station taxi ranks"
]
},
"candidates": info["recommended_hotels"],
"hex_polygons": [hex_coords],
"context_pois": [
{
"name": "Paris Gare du Nord (Eurostar Arrival)",
"latitude": 48.8809,
"longitude": 2.3553,
"type": "terminal"
}
],
"map_action": {
"focus": [hotel["latitude"], hotel["longitude"]],
"zoom": 16,
"highlight_marker_ids": [hotel["id"]]
}
}
# 2. Transit Corridor Dispatcher (Istanbul & Dubai)
is_dubai_corridor = (
(city == "dubai" or "dubai" in q_lower) and
(grounded.get("corridor_mode") or any(w in q_lower for w in ["metro", "red line", "green line", "transit line"]))
)
if is_dubai_corridor:
if "green" in q_lower or any(w in q_lower for w in ["deira", "karama", "bur dubai", "al fahidi", "creek", "baniyas", "salah al din"]):
return self._build_dubai_corridor_response(query, grounded, line_name="green")
else:
return self._build_dubai_corridor_response(query, grounded, line_name="red")
# Istanbul Transit: M11 (IST Airport), M2 (Taksim Spine), M4 (SAW Airport)
is_ist_m11 = (
any(w in q_lower for w in ["m11", "ist airport", "istanbul airport", "arnavutköy", "arnavutkoy", "göktürk", "gokturk"]) or
("ist" in q_lower.split() and any(w in q_lower for w in ["metro", "airport", "line", "station"])) or
("metro line to ist" in q_lower) or
("airport" in q_lower and "istanbul" in q_lower and not ("saw" in q_lower or "sabiha" in q_lower) and "metro" in q_lower)
)
if is_ist_m11:
return self._build_m11_corridor_response(query, grounded)
is_m2_spine = (
any(w in q_lower for w in ["m2", "taksim metro", "şişhane", "sishane", "galata metro", "osmanbey", "nişantaşı metro", "nisantasi metro", "bomonti metro", "levent metro", "vezneciler", "hacıosman", "haciosman"]) or
("m2" in q_lower.split()) or
(city == "istanbul" and "m2" in q_lower)
)
if is_m2_spine:
return self._build_m2_corridor_response(query, grounded)
is_m4_saw = (
"saw" in q_lower.split() or "sabiha" in q_lower or "m4" in q_lower.split() or "kurtköy" in q_lower or "kurtkoy" in q_lower
)
if is_m4_saw:
is_hotel = grounded.get("target_entity") == "hotel" and not grounded.get("corridor_mode")
if is_hotel:
cell_8 = h3.latlng_to_cell(40.8985, 29.3245, 8)
hex_coords = [[c[0], c[1]] for c in h3.cell_to_boundary(cell_8)]
intent_dict = dict(grounded)
intent_dict.update({
"target_entity": "hotel",
"airport": "Sabiha Gökçen (SAW)",
"transit_line": "M4 Kadıköy–Sabiha Gökçen Metro Line",
"key_station": "Kurtköy / Sabiha Gökçen Havalimanı"
})
return {
"query": query,
"city": "istanbul",
"grounded_intent": intent_dict,
"summary": "Sabiha Gökçen Airport (SAW) is directly served by Istanbul's **M4 Metro Line**. The top-rated soundproofed airport hotel within a direct 5-minute walk of the platform is **Radisson Blu Hotel & Spa, Istanbul Tuzla / Kurtköy**.",
"top_pick": {
"id": "ist_saw_hotel_01",
"name": "Radisson Blu Hotel & Spa, Istanbul Tuzla",
"category": "hotel",
"tier_label": "Airport Wellness & Transit",
"price_label": "₺₺₺",
"latitude": 40.8985,
"longitude": 29.3245,
"address": "Çamlıbelde Sitesi, Kurtköy, Istanbul",
"distance_m": 420,
"walk_minutes": 5,
"spatial_dna": {
"nearest_station_name": "M4 Kurtköy / SAW Metro",
"station_walk_mins": 5,
"line": "M4 Line direct to SAW terminal",
"noise_profile": "Triple-pane airport soundproofing (<35dB)",
"direct_airport_transit": True,
"serves_airport_code": "SAW"
},
"highlights": [
"5 min walk (420m) to M4 metro station serving SAW airport directly",
"Zero-transfer ride directly into the departure terminal",
"Thermal spa & soundproof rooms for restful layover sleep"
]
},
"candidates": [
{
"id": "ist_saw_hotel_02",
"name": "ISG Sabiha Gökçen Airport Hotel",
"category": "hotel",
"tier_label": "Terminal Direct",
"latitude": 40.8990,
"longitude": 29.3090,
"quality_score": 89,
"spatial_dna": {"station_walk_mins": 2}
},
{
"id": "ist_saw_hotel_03",
"name": "Miracle Istanbul Airport Hotel",
"category": "hotel",
"tier_label": "Business & Transit",
"latitude": 40.9080,
"longitude": 29.3150,
"quality_score": 86,
"spatial_dna": {"station_walk_mins": 6}
}
],
"hex_polygons": [hex_coords],
"transit_line_polyline": self.m4_polyline,
"context_pois": self.m4_context_pois,
"map_action": {
"focus": [40.8985, 29.3245],
"zoom": 15
}
}
else:
is_corridor = (
grounded.get("corridor_mode") or
any(w in q_lower for w in [
"around the metro", "along the metro", "across the metro", "around metro", "along metro",
"all the resturants", "all the restaurants", "resturants around", "restaurants around",
"along the line", "around the line", "corridor", "every station", "all stations"
]) or
("metro line" in q_lower and any(w in q_lower for w in ["all", "around", "along", "across", "resturant", "restaurant", "food", "eat"]))
)
if is_corridor:
return self._build_m4_corridor_response(query, grounded)
cell_8 = h3.latlng_to_cell(40.9108, 29.2961, 8)
hex_coords = [[c[0], c[1]] for c in h3.cell_to_boundary(cell_8)]
intent_dict = dict(grounded)
intent_dict.update({
"target_entity": grounded.get("target_entity", "restaurant"),
"airport": "Sabiha Gökçen (SAW)",
"transit_line": "M4 Kadıköy–Sabiha Gökçen Metro Line",
"key_station": "Kurtköy Metro İstasyonu (Ankara Cd. Exit)"
})
return {
"query": query,
"city": "istanbul",
"grounded_intent": intent_dict,
"summary": "Along Istanbul's **M4 Metro Line** serving Sabiha Gökçen Airport (SAW), the top authentic local restaurant directly outside the **Kurtköy Metro Station exit** (1 stop before the airport terminal) is **Şelale Et Mangal & Kebap** — authentic Anatolian wood-fired charcoal meats and scratch cooking located just **110 meters (1.5 min walk)** along Ankara Caddesi.",
"top_pick": {
"id": "ist_kurtkoy_selale_01",
"name": "Şelale Et Mangal & Kebap",
"category": "restaurant",
"tier_label": "Authentic Anatolian Charcoal Grill & Scratch Kitchen",
"price_label": "₺₺",
"latitude": 40.9108,
"longitude": 29.2961,
"address": "Ankara Caddesi No:312, Kurtköy, Pendik, Istanbul",
"distance_m": 110,
"walk_minutes": 2,
"spatial_dna": {
"nearest_station_name": "M4 Kurtköy Metro İstasyonu",
"station_walk_mins": 2,
"line": "M4 Kadıköy–SAW Line (1 stop direct to airport terminal)",
"kitchen_profile": "Wood-fired charcoal grill, köfte & scratch Turkish stews",
"direct_airport_transit": True,
"serves_airport_code": "SAW"
},
"highlights": [
"110m (under 2 min walk) direct from Kurtköy M4 Metro Station exit on Ankara Caddesi",
"1 stop / 3 minutes direct subway hop straight into Sabiha Gökçen (SAW) departure gates",
"Authentic local Anatolian scratch kitchen (skip overpriced airport terminal food)"
]
},
"candidates": [
{
"id": "ist_kurtkoy_metin_02",
"name": "Dönerci Metin Usta",
"category": "restaurant",
"primary_category": "restaurant",
"tier_label": "Wood-Fired Döner Specialist",
"quality_score": 92,
"latitude": 40.9112,
"longitude": 29.2963,
"address": "Ankara Caddesi, Kurtköy, Pendik",
"spatial_dna": {"station_walk_mins": 2}
},
{
"id": "ist_kurtkoy_ozsu_03",
"name": "Özsu Restaurant & Antep Mutfağı",
"category": "restaurant",
"primary_category": "restaurant",
"tier_label": "Authentic Gaziantep Kebap & Lahmacun",
"quality_score": 94,
"latitude": 40.9125,
"longitude": 29.2970,
"address": "Ankara Caddesi, Kurtköy, Pendik",
"spatial_dna": {"station_walk_mins": 3}
},
{
"id": "ist_kurtkoy_borek_04",
"name": "A Börek & Taşfırın",
"category": "bakery",
"primary_category": "bakery",
"tier_label": "Stone-Oven Pide & Börek",
"quality_score": 90,
"latitude": 40.9118,
"longitude": 29.2965,
"address": "Ankara Caddesi, Kurtköy, Pendik",
"spatial_dna": {"station_walk_mins": 3}
},
{
"id": "ist_kurtkoy_corba_05",
"name": "Çorbacı Gada",
"category": "restaurant",
"primary_category": "restaurant",
"tier_label": "24/7 Scratch Soup & Stew Kettle",
"quality_score": 88,
"latitude": 40.9130,
"longitude": 29.2972,
"address": "Ankara Caddesi, Kurtköy, Pendik",
"spatial_dna": {"station_walk_mins": 4}
}
],
"corridor_stations": self.m4_corridor_stations,
"transit_line_polyline": self.m4_polyline,
"hex_polygons": [hex_coords] + self.m4_hex_polygons,
"context_pois": self.m4_context_pois,
"map_action": {
"focus": [40.9108, 29.2961],
"zoom": 16
}
}
# Generic Istanbul Transit / Corridor queries
is_istanbul_general_transit = (
("istanbul" in q_lower and any(w in q_lower for w in ["metro", "line", "transit", "station", "resturant", "restaurant"])) or
(city == "istanbul" and any(m in q_lower for m in ["metro", "line", "station", "around", "along"])) or
("metro line" in q_lower and not ("dubai" in q_lower or "paris" in q_lower or "amsterdam" in q_lower))
)
if is_istanbul_general_transit:
return self._build_m2_corridor_response(query, grounded)
# 3. Dubai Commute Midpoint
if grounded.get("midpoint_search"):
cell_8 = h3.latlng_to_cell(25.2100, 55.2758, 8)
hex_coords = [[c[0], c[1]] for c in h3.cell_to_boundary(cell_8)]
return {
"query": query,
"city": "dubai",
"grounded_intent": grounded,
"summary": "Between Dubai Marina and Deira, the true travel-time midpoint on the Red Line is **Financial Centre (DIFC)**. Both travelers have an equal ~18–19 minute direct ride without transfers.",
"top_pick": {
"id": "dubai_fc_midpoint_cafe",
"name": "At Cafe",
"category": "cafe",
"tier_label": "Independent Specialty Coffee",
"price_label": "AED 25",
"latitude": 25.2100,
"longitude": 55.2758,
"address": "DIFC / Financial Centre Metro Exit",
"spatial_dna": {
"nearest_station_name": "Financial Centre Metro Station",
"station_walk_mins": 2,
"line": "Red Line direct symmetry (18m Marina, 19m Deira)",
"noise_profile": "Calm pedestrian atrium (<45dB)"
},
"highlights": [
"Direct covered pedestrian walkway from Financial Centre Metro platform",
"Zero line transfers required for either party",
"Calm acoustic profile ideal for conversation"
]
},
"candidates": [
{"name": "All The Perks Espresso Cafe", "latitude": 25.211, "longitude": 25.276, "primary_category": "cafe", "quality_score": 88},
{"name": "Aquarius Pool Cafe", "latitude": 25.212, "longitude": 25.277, "primary_category": "cafe", "quality_score": 85},
{"name": "% Arabica DIFC", "latitude": 25.214, "longitude": 25.278, "primary_category": "cafe", "quality_score": 92}
],
"hex_polygons": [hex_coords],
"context_pois": [
{
"name": "Financial Centre Metro Station",
"latitude": 25.2105,
"longitude": 55.2755,
"type": "transit"
}
],
"map_action": {
"focus": [25.2100, 55.2758],
"zoom": 16
}
}
# 4. Escape Tourist Traps
if grounded.get("escape_tourist_trap"):
cell_8 = h3.latlng_to_cell(25.2635, 55.2972, 8)
hex_coords = [[c[0], c[1]] for c in h3.cell_to_boundary(cell_8)]
return {
"query": query,
"city": "dubai",
"grounded_intent": grounded,
"summary": "Escaped commercial tourist traps. Recommending **Al Khayma Heritage Restaurant** in Al Fahidi — a verified 100% scratch kitchen with historic MICHELIN Bib Gourmand accreditation.",
"top_pick": {
"id": "dubai_al_khayma",
"name": "Al Khayma Heritage Restaurant",
"category": "restaurant",
"tier_label": "Authentic Heritage Icon · MICHELIN Bib Gourmand",
"price_label": "AED 85",
"latitude": 25.2635,
"longitude": 55.2972,
"address": "Historical Neighborhood 79, Al Fahidi",
"spatial_dna": {
"nearest_station_name": "Sharaf DG / Al Fahidi Metro",
"station_walk_mins": 6,
"noise_profile": "Quiet courtyard (<38dB)",
"kitchen_profile": "100% scratch Emirati traditional kitchen"
},
"highlights": [
"Zero commercial mall markup; authentic Emirati scratch recipes",
"Located in genuine coral-stone courtyard away from highway tourist traps",
"MICHELIN Bib Gourmand accredited"
]
},
"candidates": [],
"hex_polygons": [hex_coords],
"map_action": {
"focus": [25.2635, 55.2972],
"zoom": 16
}
}
# 5. Anti-Mall Warehouse Arts Roaster
if grounded.get("anti_mall_arts_only"):
cell_8 = h3.latlng_to_cell(25.1415, 55.2268, 8)
hex_coords = [[c[0], c[1]] for c in h3.cell_to_boundary(cell_8)]
return {
"query": query,
"city": "dubai",
"grounded_intent": grounded,
"summary": "Filtered for genuine **industrial warehouse arts roasters** with zero corporate mall presence. Recommending **Nightjar Coffee Roasters** in Alserkal Avenue.",
"top_pick": {
"id": "dubai_nightjar",
"name": "Nightjar Coffee Roasters",
"category": "cafe",
"tier_label": "Warehouse Micro-Roastery Master",
"price_label": "AED 30",
"latitude": 25.1415,
"longitude": 55.2268,
"address": "Warehouse 62, Alserkal Avenue, Al Quoz 1",
"spatial_dna": {
"nearest_station_name": "Equiti Metro Station",
"station_walk_mins": 12,
"noise_profile": "Warehouse creative alleyway",
"kitchen_profile": "On-site artisanal drum roaster & craft cold brew"
},
"highlights": [
"Converted industrial warehouse with live on-site drum roasting",
"Zero mall corridors; open-air creative arts alleyway",
"Renowned nitro cold brew and artisanal sourdough toast"
]
},
"candidates": [],
"hex_polygons": [hex_coords],
"map_action": {
"focus": [25.1415, 55.2268],
"zoom": 16
}
}
# 6. Hotel Search
if grounded["target_entity"] == "hotel":
scored_hotels = []
for h in self.dubai_hotels:
score = 0
dna = h["spatial_dna"]
if grounded["requires_airport_transit"]:
if not dna["direct_airport_transit"]: continue
if dna["station_walk_mins"] > grounded["max_walk_mins"]: continue
score += 50
score += max(0, 30 - dna["station_walk_mins"] * 3)
# BurJuman / Trade Centre bonus
if "BurJuman" in dna.get("nearest_station_name", ""):
score += 25
if grounded["requires_interchange_transit"]:
if dna["interchange_walk_mins"] > grounded["max_walk_mins"]: continue
score += 40
score += max(0, 30 - dna["interchange_walk_mins"] * 2)
if grounded["preferred_noise"]:
if h.get("noise_level") in grounded["preferred_noise"]:
score += 50
else:
continue
if grounded.get("pedestrian_only") and not h.get("pedestrian_only"):
continue
if grounded["target_landmark_coords"]:
l_lat, l_lon = grounded["target_landmark_coords"]
d = haversine_m(h["latitude"], h["longitude"], l_lat, l_lon)
score += max(0, 50 - int(d / 80))
scored_hotels.append((score, h))
scored_hotels.sort(key=lambda x: x[0], reverse=True)
candidates = scored_hotels if scored_hotels else [(50, h) for h in self.dubai_hotels]
top_hotel = candidates[0][1] if candidates else None
hex_polygons = []
if top_hotel:
cell_8 = top_hotel["spatial_dna"]["h3_res8"]
coords = h3.cell_to_boundary(cell_8)
hex_polygons.append([[c[0], c[1]] for c in coords])
summary_text = "Found hotels meeting your exact spatial constraints."
if grounded["requires_airport_transit"]:
summary_text = f"Found hotels with a **1-seat direct ride to DXB Airport** on the Red Line within a {grounded['max_walk_mins']}-minute walk of the platform."
elif grounded["preferred_noise"]:
summary_text = "Filtered for **secluded, sound-isolated sanctuaries** with quiet courtyard architecture and zero street noise."
return {
"query": query,
"city": "dubai",
"grounded_intent": grounded,
"summary": summary_text,
"top_pick": {
"id": top_hotel["id"],
"name": top_hotel["name"],
"category": "hotel",
"tier_label": top_hotel["tier"],
"price_label": f"AED {top_hotel['price_per_night_aed']}/night",
"latitude": top_hotel["latitude"],
"longitude": top_hotel["longitude"],
"address": top_hotel["address"],
"neighborhood": top_hotel.get("neighborhood"),
"spatial_dna": top_hotel["spatial_dna"],
"highlights": top_hotel.get("highlights", [])
} if top_hotel else None,
"candidates": [c[1] for c in candidates[:5]],
"hex_polygons": hex_polygons,
"context_pois": [
{
"name": top_hotel["spatial_dna"]["nearest_station_name"] + " Metro",
"latitude": top_hotel["latitude"] + 0.002,
"longitude": top_hotel["longitude"] + 0.002,
"type": "transit"
}
] if top_hotel else [],
"map_action": {
"focus": [top_hotel["latitude"], top_hotel["longitude"]] if top_hotel else [25.2048, 55.2708],
"zoom": 15,
"highlight_marker_ids": [top_hotel["id"]] if top_hotel else []
}
}
# 7. Restaurant / Cafe / Dining Search
candidates = []
has_explicit_anchor = grounded.get("target_landmark_coords") is not None
l_lat, l_lon = grounded.get("target_landmark_coords") or (25.2048, 55.2708)
max_dist_m = grounded.get("target_landmark_radius_m") or (grounded["max_walk_mins"] * 80)
target_cat = grounded.get("target_category")
for p in self.dubai_places:
plat, plon = p.get("latitude"), p.get("longitude")
if not plat or not plon: continue
dist = haversine_m(plat, plon, l_lat, l_lon)
walk_mins = int(dist / 80)
# Spatial distance constraint
if has_explicit_anchor:
if dist > max_dist_m: continue
else:
if walk_mins > grounded["max_walk_mins"]: continue
p_cat = (p.get("primary_category") or "").lower()
p_cuisine = (p.get("cuisine") or "").lower()
p_name = (p.get("name") or "").lower()
# Category constraint
if target_cat:
cat_match = False
if target_cat == "cafe":
cat_match = (p_cat in ["cafe", "coffee", "bakery"] or
"coffee" in p_cuisine or "cafe" in p_name or "coffee" in p_name or
any("roaster" in b.lower() for b in p.get("craft_badges", [])))
elif target_cat == "bakery":
cat_match = (p_cat in ["bakery", "cafe"] or "bakery" in p_cuisine or "bakery" in p_name or "bread" in p_name)
elif target_cat in p_cat or target_cat in p_cuisine or target_cat in p_name:
cat_match = True
if not cat_match:
continue
if grounded["max_budget_aed"] and p.get("price_tier", 2) > 1: continue
if grounded["require_non_chain"] and p.get("is_chain"): continue
if grounded.get("late_night_only") and not p.get("amenities", {}).get("late_night"): continue
if grounded.get("waterfront_terrace_only") and not p.get("amenities", {}).get("canal_terrace"): continue
q_score = p.get("quality_score", 50)
score = q_score + max(0, 35 - int(dist / 40))
if p_cat == target_cat:
score += 25
if p.get("amenities", {}).get("outdoor_seating"):
score += 10
candidates.append((score, dist, walk_mins, p))
candidates.sort(key=lambda x: x[0], reverse=True)
top_eat = candidates[0][3] if candidates else None
hex_polygons = []
if top_eat:
cell_8 = h3.latlng_to_cell(top_eat.get("latitude"), top_eat.get("longitude"), 8)
coords = h3.cell_to_boundary(cell_8)
hex_polygons.append([[c[0], c[1]] for c in coords])
context_pois = []
if grounded.get("target_landmark"):
context_pois.append({
"name": grounded["target_landmark"],
"latitude": l_lat,
"longitude": l_lon,
"type": "landmark"
})
summary_text = "Here are the top independent authentic culinary matches fitting your exact walking and dining constraints."
if grounded.get("target_landmark") and target_cat:
summary_text = f"Found top **{target_cat.capitalize()} venues in {grounded['target_landmark']}** matching your walking radius and culinary standards."
elif grounded.get("target_landmark"):
summary_text = f"Found authentic dining options in **{grounded['target_landmark']}** within direct reach."
elif grounded.get("late_night_only"):
summary_text = "Filtered for **verified post-midnight late-night kitchens** serving authentic hot food with outdoor terrace seating."
return {
"query": query,
"city": "dubai",
"grounded_intent": grounded,
"summary": summary_text,
"top_pick": {
"id": top_eat["id"],
"name": top_eat["name"],
"category": top_eat.get("primary_category"),
"tier_label": top_eat.get("tier_label") or (top_eat.get("primary_category", "Venue").capitalize() + " · Quality " + str(top_eat.get("quality_score", 85))),
"price_label": top_eat.get("price_label") or "AED",
"latitude": top_eat.get("latitude"),
"longitude": top_eat.get("longitude"),
"address": top_eat.get("address"),
"neighborhood": top_eat.get("neighborhood") or grounded.get("target_landmark"),
"distance_m": candidates[0][1],
"walk_minutes": candidates[0][2],
"craft_badges": top_eat.get("craft_badges", []),
"highlights": [
f"Located in {top_eat.get('address', grounded.get('target_landmark', 'Dubai'))}",
f"Curated quality rating of {top_eat.get('quality_score', 85)}/99",
f"Walking distance: ~{int(candidates[0][1])}m ({candidates[0][2]} min walk)"
]
} if top_eat else None,
"candidates": [c[3] for c in candidates[:6]],
"hex_polygons": hex_polygons,
"context_pois": context_pois,
"map_action": {
"focus": [top_eat.get("latitude"), top_eat.get("longitude")] if top_eat else [l_lat, l_lon],
"zoom": 15
}
}
copilot_service = SpatialCopilotService()
"""
Spatial Copilot Service for 'Google Maps on God Mode'
Handles natural language spatial intent grounding, multi-entity graph resolution,
dynamic gazetteer indexing, and structured response generation with H3 polygons and map actions.
"""
import os
import json
import math
import re
import time
import urllib.request
import urllib.parse
import h3
def haversine_m(lat1, lon1, lat2, lon2):
R = 6371000 # meters
phi1, phi2 = math.radians(lat1), math.radians(lat2)
dphi = math.radians(lat2 - lat1)
dlam = math.radians(lon2 - lon1)
a = math.sin(dphi/2)**2 + math.cos(phi1) * math.cos(phi2) * math.sin(dlam/2)**2
return int(2 * R * math.atan2(math.sqrt(a), math.sqrt(1 - a)))
INTERCITY_RAIL_TERMINALS = {
("amsterdam", "paris"): {
"operator": "Eurostar (formerly Thalys)",
"arrival_station": "Gare du Nord",
"city": "Paris",
"coordinates": [48.8809, 2.3553],
"typical_late_arrival_cutoff_m": 450,
"recommended_hotels": [
{
"id": "paris_hotel_terminus_nord",
"name": "25hours Hotel Terminus Nord",
"latitude": 48.8803,
"longitude": 2.3550,
"tier": "Boutique Design",
"price_label": "€€€",
"highlights": "Directly opposite Gare du Nord main entrance; 24h reception; soundproofed boutique rooms so you don't hear late-night station traffic.",
"distance_m": 85,
"walk_mins": 1
},
{
"id": "paris_hotel_whistler",
"name": "Hôtel Whistler",
"latitude": 48.8801,
"longitude": 2.3575,
"tier": "Quiet Luxury Boutique",
"price_label": "€€€",
"highlights": "Luxury railway-themed boutique hotel on quiet side street; 24h concierge; 3 mins walk from Eurostar platforms.",
"distance_m": 220,
"walk_mins": 3
}
]
}
}
DUBAI_GAZETTEER = {
"mirdif city centre": {"name": "City Centre Mirdif", "coords": (25.2163, 55.4077), "radius_m": 1200},
"city centre mirdif": {"name": "City Centre Mirdif", "coords": (25.2163, 55.4077), "radius_m": 1200},
"mirdif city center": {"name": "City Centre Mirdif", "coords": (25.2163, 55.4077), "radius_m": 1200},
"city center mirdif": {"name": "City Centre Mirdif", "coords": (25.2163, 55.4077), "radius_m": 1200},
"uptown mirdif": {"name": "Uptown Mirdif", "coords": (25.2250, 55.4200), "radius_m": 1200},
"mirdif": {"name": "Mirdif", "coords": (25.2180, 55.4150), "radius_m": 2500},
"mall of the emirates": {"name": "Mall of the Emirates", "coords": (25.1181, 55.2006), "radius_m": 1200},
"moe": {"name": "Mall of the Emirates", "coords": (25.1181, 55.2006), "radius_m": 1200},
"dubai mall": {"name": "Dubai Mall", "coords": (25.1985, 55.2796), "radius_m": 1200},
"burj khalifa": {"name": "Burj Khalifa / Downtown", "coords": (25.1972, 55.2744), "radius_m": 1500},
"downtown dubai": {"name": "Downtown Dubai", "coords": (25.1972, 55.2744), "radius_m": 1800},
"downtown": {"name": "Downtown Dubai", "coords": (25.1972, 55.2744), "radius_m": 1800},
"difc": {"name": "DIFC / Gate Village", "coords": (25.2138, 55.2782), "radius_m": 1200},
"gate village": {"name": "DIFC / Gate Village", "coords": (25.2138, 55.2782), "radius_m": 800},
"dwtc": {"name": "Dubai World Trade Centre", "coords": (25.2235, 55.2829), "radius_m": 1200},
"trade centre": {"name": "Dubai World Trade Centre", "coords": (25.2235, 55.2829), "radius_m": 1200},
"trade center": {"name": "Dubai World Trade Centre", "coords": (25.2235, 55.2829), "radius_m": 1200},
"dubai marina": {"name": "Dubai Marina", "coords": (25.0789, 55.1444), "radius_m": 1800},
"marina mall": {"name": "Dubai Marina Mall", "coords": (25.0772, 55.1396), "radius_m": 1000},
"marina": {"name": "Dubai Marina", "coords": (25.0789, 55.1444), "radius_m": 1800},
"jbr": {"name": "JBR / The Beach", "coords": (25.0780, 55.1320), "radius_m": 1200},
"the beach": {"name": "JBR / The Beach", "coords": (25.0780, 55.1320), "radius_m": 1000},
"jlt": {"name": "Jumeirah Lakes Towers", "coords": (25.0740, 55.1450), "radius_m": 1800},
"jumeirah lakes towers": {"name": "Jumeirah Lakes Towers", "coords": (25.0740, 55.1450), "radius_m": 1800},
"palm jumeirah": {"name": "Palm Jumeirah", "coords": (25.1124, 55.1390), "radius_m": 2500},
"the palm": {"name": "Palm Jumeirah", "coords": (25.1124, 55.1390), "radius_m": 2500},
"nakheel mall": {"name": "Nakheel Mall, Palm Jumeirah", "coords": (25.1142, 55.1402), "radius_m": 1000},
"the pointe": {"name": "The Pointe, Palm Jumeirah", "coords": (25.1270, 55.1230), "radius_m": 1000},
"deira": {"name": "Deira", "coords": (25.2690, 55.3280), "radius_m": 2500},
"city centre deira": {"name": "City Centre Deira", "coords": (25.2520, 55.3330), "radius_m": 1200},
"city center deira": {"name": "City Centre Deira", "coords": (25.2520, 55.3330), "radius_m": 1200},
"deira city centre": {"name": "City Centre Deira", "coords": (25.2520, 55.3330), "radius_m": 1200},
"bur dubai": {"name": "Bur Dubai", "coords": (25.2530, 55.3020), "radius_m": 2200},
"burjuman": {"name": "BurJuman", "coords": (25.2520, 55.3040), "radius_m": 1000},
"karama": {"name": "Al Karama", "coords": (25.2440, 55.3030), "radius_m": 1800},
"al karama": {"name": "Al Karama", "coords": (25.2440, 55.3030), "radius_m": 1800},
"al fahidi": {"name": "Al Fahidi Historic District", "coords": (25.2635, 55.2972), "radius_m": 1000},
"al seef": {"name": "Al Seef / Dubai Creek", "coords": (25.2600, 55.3070), "radius_m": 1000},
"dubai creek": {"name": "Dubai Creek", "coords": (25.2610, 55.3050), "radius_m": 1500},
"creek": {"name": "Dubai Creek", "coords": (25.2610, 55.3050), "radius_m": 1500},
"shindagha": {"name": "Al Shindagha", "coords": (25.2680, 55.2950), "radius_m": 1000},
"al quoz": {"name": "Al Quoz", "coords": (25.1415, 55.2268), "radius_m": 2200},