""" AP Smart Route Finder — Gradio Edition Run: pip install gradio networkx numpy folium python app_gradio.py """ from algorithms import run_dijkstra, run_grover import math, random, time import numpy as np import networkx as nx import gradio as gr # ══════════════════════════════════════════════════════════════════════════════ # CITY DATA # ══════════════════════════════════════════════════════════════════════════════ AP_CITIES = { "Visakhapatnam": (17.6868, 83.2185), "Vijayawada": (16.5062, 80.6480), "Guntur": (16.3067, 80.4365), "Nellore": (14.4426, 79.9865), "Kurnool": (15.8281, 78.0373), "Rajahmundry": (16.9891, 81.7837), "Tirupati": (13.6288, 79.4192), "Kadapa": (14.4674, 78.8241), "Kakinada": (16.9891, 82.2475), "Anantapur": (14.6819, 77.6006), "Amaravati": (16.5730, 80.3564), "Eluru": (16.7107, 81.0952), "Ongole": (15.5057, 80.0499), "Srikakulam": (18.2949, 83.8938), "Vizianagaram": (18.1066, 83.3956), "Chittoor": (13.2172, 79.1003), "Machilipatnam": (16.1875, 81.1386), "Narasaraopet": (16.2346, 80.0490), "Tenali": (16.2435, 80.6404), "Mangalagiri": (16.4307, 80.5525), "Bhimavaram": (16.5449, 81.5212), "Tadepalligudem": (16.8133, 81.5271), "Bapatla": (15.9049, 80.4671), "Chirala": (15.8264, 80.3538), "Narasapuram": (16.4344, 81.6958), "Palasa": (18.7726, 84.4083), "Bobbili": (18.5744, 83.3588), "Parvathipuram": (18.7828, 83.4253), "Rajam": (18.4730, 83.6469), "Anakapalle": (17.6910, 83.0000), "Yellamanchili": (17.5543, 82.8555), "Madanapalle": (13.5545, 78.5011), "Hindupur": (13.8294, 77.4911), "Dharmavaram": (14.4113, 77.7181), "Tadipatri": (14.9101, 78.0094), "Guntakal": (15.1712, 77.3726), "Adoni": (15.6279, 77.2744), "Nandyal": (15.4786, 78.4836), "Proddatur": (14.7500, 78.5500), "Rajampet": (14.1931, 79.1621), "Badvel": (14.7455, 79.0643), "Pulivendula": (14.4224, 78.2277), "Allagadda": (15.1417, 78.5304), "Srisailam": (16.0833, 78.8833), "Markapur": (15.7407, 79.2682), "Kandukur": (15.2143, 79.9057), "Kavali": (14.9165, 79.9932), "Gudur": (14.1459, 79.8516), "Sullurpeta": (13.7630, 79.8878), "Venkatagiri": (13.9617, 79.5812), "Srikalahasti": (13.7500, 79.6983), "Puttur": (13.4408, 79.5493), "Pileru": (13.6583, 79.1167), "Punganur": (13.3674, 78.5805), "Kuppam": (12.7500, 78.3333), "Peddapuram": (17.0786, 82.1360), "Samalkot": (17.0582, 82.1761), "Tuni": (17.3586, 82.5476), "Amalapuram": (16.5771, 82.0056), "Razole": (16.4784, 81.8413), "Mandapeta": (16.8667, 81.9333), "Kovvur": (17.0167, 81.7333), "Nidadavolu": (17.0578, 81.6728), "Tanuku": (16.8600, 81.6800), "Palakollu": (16.5155, 81.7301), "Nuzvid": (16.7853, 80.8459), "Gudivada": (16.4327, 80.9943), "Vuyyuru": (16.3618, 80.8459), "Repalle": (16.0186, 80.8306), "Vinukonda": (16.0500, 79.7333), "Sattenapalle": (16.3932, 80.1528), "Macherla": (16.4795, 79.4352), "Chilakaluripet": (16.0875, 80.1689), "Ongole": (15.5057, 80.0499), "Narasannapeta": (18.4148, 84.0419), } CITY_POIS = { "Visakhapatnam": { "malls": ["CMR Central Mall", "Jagadamba Junction Mall", "Pothys Mall"], "restaurants": ["Dwaraka Hotel", "Bamboo Bay", "Sea View Restaurant", "Hotel Meghalaya"], "landmarks": ["Kailasagiri", "Rishikonda Beach", "INS Kurusura Museum", "Araku Valley"], "petrol_bunks": ["HP Petrol Bunk - MVP Colony", "Indian Oil - Dwaraka Nagar", "BPCL - Gajuwaka", "Shell - Vizag Steel Area"], }, "Vijayawada": { "malls": ["PVP Square", "One Town Mall", "AMB Mall"], "restaurants": ["Hotel Swagath", "Minerva Coffee Shop", "Babai Hotel", "Curry Leaf"], "landmarks": ["Kanaka Durga Temple", "Prakasam Barrage", "Undavalli Caves", "Bhavani Island"], "petrol_bunks": ["HP Bunk - Governorpet", "Indian Oil - Benz Circle", "BPCL - Eluru Road", "Shell - Autonagar"], }, "Guntur": { "malls": ["KLM Fashion Mall", "Big Bazaar Guntur"], "restaurants": ["Nagarjuna Restaurant", "Hotel Dwaraka", "Udupi Hotel"], "landmarks": ["Undavalli Caves", "Amaravati Museum", "Kondaveedu Fort"], "petrol_bunks": ["HP - Brodipet", "Indian Oil - Arundelpet", "BPCL - Naaz Centre"], }, "Tirupati": { "malls": ["Leela Mahal Mall", "Star Mall Tirupati"], "restaurants": ["Hotel Bliss", "Annapurna Hotel", "Bhimas Deluxe"], "landmarks": ["Tirumala Temple", "Sri Padmavathi Temple", "Chandragiri Fort"], "petrol_bunks": ["HP - Alipiri", "Indian Oil - Renigunta Road", "BPCL - Tiruchanur"], }, "Nellore": { "malls": ["Leela Mall", "City Center Mall"], "restaurants": ["Hotel Sreyas", "Kamat Hotel", "Spice Garden"], "landmarks": ["Pulicat Lake", "Mypad Beach", "Sri Ranganathaswamy Temple"], "petrol_bunks": ["HP - Grand Trunk Road", "Indian Oil - Pogathota", "BPCL - Dargamitta"], }, "Rajahmundry": { "malls": ["Rajahmundry Mall", "City Center"], "restaurants": ["Hotel Anand", "Haritha Hotel", "Bay Leaf"], "landmarks": ["Godavari Bridge", "Dowleswaram Barrage", "Papikondalu"], "petrol_bunks": ["HP - Morampudi", "Indian Oil - Innespeta", "BPCL - Godavari Bund"], }, "Kadapa": { "malls": ["Urban Square Mall"], "restaurants": ["Hotel Sree Ram", "Haritha Hotel Kadapa"], "landmarks": ["Gandikota Fort", "Vontimitta Temple"], "petrol_bunks": ["HP - Railway Station Road", "Indian Oil - Beside Bus Stand", "BPCL - Cuddapah Bypass"], }, "Kurnool": { "malls": ["Kurnool Central Mall", "Forum Mall"], "restaurants": ["Hotel Srinivasa", "Minerva Restaurant"], "landmarks": ["Belum Caves", "Tungabhadra Dam", "Srisailam Temple"], "petrol_bunks": ["HP - NH-44", "Indian Oil - Dinne Bypass", "BPCL - Budhawarpet"], }, "Anantapur": { "malls": ["Anantapur City Center"], "restaurants": ["Hotel Surya", "MTR Anantapur"], "landmarks": ["Lepakshi Temple", "Thimmamma Marrimanu"], "petrol_bunks": ["HP - Bangalore Road", "Indian Oil - Subash Road", "BPCL - Anantapur Bypass"], }, "Chittoor": { "malls": ["Chittoor Mall"], "restaurants": ["Hotel Viswa", "Hotel Mayuri"], "landmarks": ["Horsley Hills", "Kailasakona Waterfall"], "petrol_bunks": ["HP - Madanapalle Road", "Indian Oil - Punganur Road"], }, } DEFAULT_POIS = { "malls": ["Local Shopping Centre", "Town Market"], "restaurants": ["Udupi Hotel", "Local Dhaba", "Annapoorna Restaurant"], "landmarks": ["Town Centre", "Local Temple", "Bus Stand"], "petrol_bunks": ["HP Petrol Bunk", "Indian Oil Bunk", "Local Petrol Station"], } # ══════════════════════════════════════════════════════════════════════════════ # GRAPH # ══════════════════════════════════════════════════════════════════════════════ def haversine_km(lat1, lon1, lat2, lon2): R = 6371.0 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 R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a)) def build_graph(max_dist_km=150.0): G = nx.Graph() city_list = list(AP_CITIES.items()) for name, (lat, lon) in city_list: G.add_node(name, lat=lat, lon=lon) for i in range(len(city_list)): n1, (la1, lo1) = city_list[i] for j in range(i + 1, len(city_list)): n2, (la2, lo2) = city_list[j] d = haversine_km(la1, lo1, la2, lo2) if d <= max_dist_km: road_d = round(d * 1.30, 1) G.add_edge(n1, n2, weight=road_d) return G G = build_graph() ALL_CITIES = sorted(AP_CITIES.keys()) # ══════════════════════════════════════════════════════════════════════════════ # ALGORITHMS # ══════════════════════════════════════════════════════════════════════════════ def run_dijkstra(G, source, target): import time t0 = time.perf_counter() try: path = nx.dijkstra_path(G, source, target, weight="weight") cost = nx.dijkstra_path_length(G, source, target, weight="weight") except Exception as e: return {"path": [], "cost": None, "time_ms": 0, "error": str(e)} elapsed = (time.perf_counter() - t0) * 1000 return { "path": path, "cost": round(cost, 1), "time_ms": round(elapsed, 3), # ✅ FIX "error": None } def _collect_paths(G, source, target, max_paths=256): try: optimal = nx.dijkstra_path(G, source, target, weight="weight") except: optimal = None paths = [] for p in nx.all_simple_paths(G, source, target, cutoff=7): paths.append(p) if len(paths) >= max_paths: break if optimal and optimal not in paths: paths.insert(0, optimal) return paths def _path_cost(G, path): return sum(G[path[i]][path[i+1]]["weight"] for i in range(len(path)-1)) def run_grover(G, source, target, max_paths=200): import time t0 = time.perf_counter() paths = _collect_paths(G, source, target, max_paths) N = len(paths) if N == 0: return {"path": [], "cost": None, "time_ms": 0, "oracle_calls": 0, "error": "No paths"} costs = np.array([_path_cost(G, p) for p in paths], dtype=np.float64) optimal_cost = costs.min() threshold = optimal_cost * 1.10 oracle_mask = (costs <= threshold).astype(np.float64) amplitudes = np.ones(N, dtype=np.float64) / math.sqrt(N) num_iter = max(1, round((math.pi / 4) * math.sqrt(N))) oracle_calls = 0 # ✅ NEW for _ in range(num_iter): oracle_calls += 1 amplitudes = amplitudes * (1 - 2 * oracle_mask) mean_amp = amplitudes.mean() amplitudes = 2 * mean_amp - amplitudes norm = np.linalg.norm(amplitudes) if norm > 1e-12: amplitudes /= norm probs = amplitudes ** 2 probs = np.clip(probs, 0, None) probs /= probs.sum() idx = int(np.random.choice(N, p=probs)) elapsed = (time.perf_counter() - t0) * 1000 return { "path": paths[idx], "cost": round(costs[idx], 1), "time_ms": round(elapsed, 3), # ✅ NEW "oracle_calls": oracle_calls, # ✅ NEW "error": None } def get_all_paths(G, source, target, limit=8): """Get several simple paths sorted by cost.""" all_paths = [] try: for p in nx.all_simple_paths(G, source, target, cutoff=6): cost = _path_cost(G, p) all_paths.append((p, round(cost, 1))) if len(all_paths) >= limit: break except: pass all_paths.sort(key=lambda x: x[1]) return all_paths def combined_shortest_path(G, source, target): d = run_dijkstra(G, source, target) g = run_grover(G, source, target) if d["error"] and g["error"]: return None, None, None candidates = [] if not d["error"]: candidates.append((d["path"], d["cost"])) if not g["error"]: candidates.append((g["path"], g["cost"])) candidates.sort(key=lambda x: x[1]) comparison = { "dijkstra_time": d.get("time_ms", 0), "grover_time": g.get("time_ms", 0), "grover_oracle_calls": g.get("oracle_calls", 0) } return candidates[0][0], candidates[0][1], comparison # ══════════════════════════════════════════════════════════════════════════════ # MAP BUILDER (Folium) # ══════════════════════════════════════════════════════════════════════════════ def build_folium_map(source, target, shortest_path, all_paths): try: import folium except ImportError: return "
Install folium: pip install folium
" src_ll = AP_CITIES.get(source, (16.0, 80.5)) tgt_ll = AP_CITIES.get(target, (16.0, 80.5)) centre = ((src_ll[0]+tgt_ll[0])/2, (src_ll[1]+tgt_ll[1])/2) m = folium.Map(location=centre, zoom_start=7, tiles="CartoDB positron", control_scale=True) # Draw all paths (faint) sp_set = set(zip(shortest_path[:-1], shortest_path[1:])) if shortest_path else set() drawn_edges = set() for path, cost in all_paths: is_shortest = (path == shortest_path) for i in range(len(path)-1): u, v = path[i], path[i+1] key = frozenset([u, v]) if key in drawn_edges and not is_shortest: continue drawn_edges.add(key) ll_u = AP_CITIES.get(u) ll_v = AP_CITIES.get(v) if not ll_u or not ll_v: continue if is_shortest: folium.PolyLine([ll_u, ll_v], color="#FF6B35", weight=6, opacity=0.95, tooltip=f"{u}→{v}").add_to(m) else: folium.PolyLine([ll_u, ll_v], color="#6B8FD4", weight=2.5, opacity=0.5, dash_array="8 4", tooltip=f"{u}→{v}").add_to(m) # All graph edges (very faint background) for u, v, data in G.edges(data=True): key = frozenset([u, v]) if key in drawn_edges: continue ll_u = AP_CITIES.get(u) ll_v = AP_CITIES.get(v) if not ll_u or not ll_v: continue folium.PolyLine([ll_u, ll_v], color="#CCCCCC", weight=1, opacity=0.15).add_to(m) # Markers for cities on path path_cities = set(shortest_path) if shortest_path else set() for city in path_cities: ll = AP_CITIES.get(city) if not ll: continue pois = CITY_POIS.get(city, DEFAULT_POIS) if city == source: icon_color, icon_name = "green", "play" elif city == target: icon_color, icon_name = "red", "flag" else: icon_color, icon_name = "orange", "map-marker" popup_html = f"""