""" CoolRide Engine - Main Flask Application (Web Only) Contains: 1. Core Routing Logic (Sun/Shade/Surface) 2. Web App API (Auth/Feedback) 3. Field Ops (Sensor Logging + NEA Context) """ import os import time import math import uuid import threading import traceback import concurrent.futures import requests import pandas as pd import geopandas as gpd import networkx as nx import osmnx as ox import simplekml import numpy as np from flask import Flask, request, jsonify, render_template from flask_cors import CORS from shapely.geometry import Point, LineString from shapely.strtree import STRtree from datetime import datetime import pytz import pysolar.solar as solar from supabase import create_client, Client from groq import Groq # Import from our modules from config import ( SUPABASE_URL, SUPABASE_KEY, GROQ_API_KEY, APP_URL, MAX_ROUTE_DISTANCE_KM ) from helpers import calculate_eta, generate_directions, analyze_route_attributes, get_realtime_weather, get_realtime_humidity, is_in_singapore, log # ========================================== # 🚀 INITIALIZATION # ========================================== # Get the root directory (parent of src/) ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) app = Flask(__name__, template_folder=os.path.join(ROOT_DIR, 'templates'), static_folder=os.path.join(ROOT_DIR, 'static')) CORS(app) import time as startup_time _startup_begin = startup_time.time() print("🚀 COOLRIDE ENGINE V16.15 (MASTER) INITIALIZING...", flush=True) print(f" ⏱️ Startup timestamp: {startup_time.strftime('%Y-%m-%d %H:%M:%S')}", flush=True) # --- DATABASE --- supabase = None try: supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY) # Ping to check connection supabase.table('route_logs').select("*").limit(1).execute() print(" ✅ Connected to Supabase Database.", flush=True) except Exception as e: print(f" ⚠️ Database Connection Failed: {e}", flush=True) supabase = None # --- GROQ CLIENT --- groq_client = None if GROQ_API_KEY: groq_client = Groq(api_key=GROQ_API_KEY) print(" ✅ Groq API Initialized.", flush=True) else: print(" ⚠️ GROQ_API_KEY not set. Chatbot disabled.", flush=True) # Route cache for pre-calculated routes route_cache = {} ROUTE_CACHE_TTL = 1800 # 30 minutes _cache_lock = threading.Lock() # Concurrency guards for route computation ROUTE_TIMEOUT = 30 # seconds MAX_CONCURRENT_ROUTES = 3 _route_counter_lock = threading.Lock() _routes_in_progress = 0 _route_executor = concurrent.futures.ThreadPoolExecutor(max_workers=MAX_CONCURRENT_ROUTES) def cache_route(route_data): """Store route in cache and return unique ID.""" with _cache_lock: route_id = str(uuid.uuid4())[:8] route_cache[route_id] = { "data": route_data, "timestamp": time.time() } current_time = time.time() expired = [k for k, v in route_cache.items() if current_time - v["timestamp"] > ROUTE_CACHE_TTL] for k in expired: del route_cache[k] return route_id def get_cached_route(route_id): """Retrieve route from cache if it exists and hasn't expired.""" with _cache_lock: if route_id in route_cache: entry = route_cache[route_id] if time.time() - entry["timestamp"] < ROUTE_CACHE_TTL: return entry["data"] else: del route_cache[route_id] return None # Weather cache for route computation _weather_cache = {} _weather_cache_lock = threading.Lock() WEATHER_CACHE_TTL = 300 # 5 minutes def get_weather_for_route(lat, lon): """Fetch temp + humidity for route, cached by nearest station.""" cache_key = f"{round(lat, 2)},{round(lon, 2)}" now = time.time() with _weather_cache_lock: cached = _weather_cache.get(cache_key) if cached and now - cached["timestamp"] < WEATHER_CACHE_TTL: return cached["temp"], cached["humidity"], cached["station"] # Cache miss — fetch fresh temp, station = get_realtime_weather(lat, lon) humidity = get_realtime_humidity(lat, lon) store_time = time.time() with _weather_cache_lock: _weather_cache[cache_key] = { "temp": temp, "humidity": humidity, "station": station, "timestamp": store_time } # Evict old entries expired = [k for k, v in _weather_cache.items() if store_time - v["timestamp"] > WEATHER_CACHE_TTL] for k in expired: del _weather_cache[k] # Cap cache size to prevent unbounded growth if len(_weather_cache) > 100: oldest_key = min(_weather_cache, key=lambda k: _weather_cache[k]["timestamp"]) del _weather_cache[oldest_key] return temp, humidity, station # ========================================== # 📂 LOAD MAP & DATA # ========================================== MAP_PATH = os.path.join(ROOT_DIR, "Data/singapore_enriched.graphml.gz") if os.path.exists(MAP_PATH): print(f" 📂 Loading Graph: {MAP_PATH}...", flush=True) G = ox.load_graphml(MAP_PATH) print(f" ✅ Graph Loaded: {len(G.nodes):,} nodes.", flush=True) else: raise FileNotFoundError("CRITICAL: singapore_enriched.graphml.gz not found!") # Load Layers print(" 🌳 Indexing Layers...", flush=True) tree_index = None trees_gdf = None try: trees_df = pd.read_csv(os.path.join(ROOT_DIR, "Data/trees.csv")) geometry = [Point(xy) for xy in zip(trees_df.lng, trees_df.lat)] trees_gdf = gpd.GeoDataFrame(trees_df, geometry=geometry, crs="EPSG:4326") tree_index = STRtree(trees_gdf.geometry) print(f" ✅ Indexed {len(trees_gdf):,} Trees.", flush=True) except Exception as e: print(f" ⚠️ Tree load failed: {e}", flush=True) water_index = None water_gdf = None try: water_gdf = gpd.read_file(os.path.join(ROOT_DIR, "Data/URA_Waterbody.geojson")) water_index = STRtree(water_gdf.geometry) print(f" ✅ Indexed {len(water_gdf):,} Water Bodies.", flush=True) except Exception as e: print(f" ⚠️ Water load failed: {e}", flush=True) pcn_index = None pcn_gdf = None try: pcn_gdf = gpd.read_file(os.path.join(ROOT_DIR, "Data/ParkConnectorLoop.geojson")) pcn_index = STRtree(pcn_gdf.geometry) print(f" ✅ Indexed {len(pcn_gdf):,} PCN Segments.", flush=True) except Exception as e: print(f" ⚠️ PCN load failed: {e}", flush=True) amenities_data = [] try: hawkers = gpd.read_file(os.path.join(ROOT_DIR, "Data/hawker_centres.geojson")) for _, row in hawkers.iterrows(): name = row.get('Name', row.get('name', 'Hawker Centre')) pt = row.geometry.centroid amenities_data.append({"name": name, "lat": pt.y, "lon": pt.x, "type": "Hawker"}) marts = gpd.read_file(os.path.join(ROOT_DIR, "Data/supermarkets.geojson")) for _, row in marts.iterrows(): name = row.get('Name', row.get('name', 'Supermarket')) pt = row.geometry.centroid amenities_data.append({"name": name, "lat": pt.y, "lon": pt.x, "type": "Supermarket"}) print(f" ✅ Loaded {len(amenities_data)} Amenities.", flush=True) except Exception as e: print(f" ⚠️ Amenities load failed: {e}", flush=True) # ========================================== # 🧮 PRE-COMPUTE STATIC EDGE COSTS # ========================================== print(" 🧮 Pre-computing edge costs...", flush=True) edge_static_costs = {} _precomp_start = time.time() # Detect Shapely version for STRtree API compatibility import shapely _shapely_v2 = int(shapely.__version__.split('.')[0]) >= 2 for u, v, data in G.edges(data=True): length = data.get('length', 10) highway = data.get('highway', '') surface = data.get('surface', 'unknown') if isinstance(highway, list): highway = highway[0] if isinstance(surface, list): surface = surface[0] # Base weight (road type) base_weight = 1.0 if highway in ('cycleway', 'path', 'track'): base_weight = 0.8 elif highway in ('primary', 'trunk'): base_weight = 1.5 elif highway in ('residential', 'service'): base_weight = 1.1 # Surface penalty if surface in ('concrete', 'paving_stones'): base_weight += 0.1 elif surface == 'unpaved': base_weight += 0.3 # Midpoint for spatial queries if 'geometry' in data: midpoint = data['geometry'].interpolate(0.5, normalized=True) else: midpoint = Point(G.nodes[u]['x'], G.nodes[u]['y']) # ML-informed cooling bonus (Random Forest feature importances, n=15 pilot routes) # Weights: Water=0.325, PCN=0.257, Canopy=0.119, SVF=0.110 # Spatial thresholds preserved from original STRtree queries. ml_cooling_bonus = 0 if tree_index: if _shapely_v2: idx = tree_index.nearest(midpoint) if midpoint.distance(trees_gdf.geometry.iloc[idx]) < 0.00015: ml_cooling_bonus += 0.119 else: idx = tree_index.nearest(midpoint) if midpoint.distance(trees_gdf.iloc[idx].geometry) < 0.00015: ml_cooling_bonus += 0.119 if water_index: if _shapely_v2: idx = water_index.nearest(midpoint) if midpoint.distance(water_gdf.geometry.iloc[idx]) < 0.0003: ml_cooling_bonus += 0.325 else: idx = water_index.nearest(midpoint) if midpoint.distance(water_gdf.iloc[idx].geometry) < 0.0003: ml_cooling_bonus += 0.325 if pcn_index: if _shapely_v2: idx = pcn_index.nearest(midpoint) if midpoint.distance(pcn_gdf.geometry.iloc[idx]) < 0.0001: ml_cooling_bonus += 0.257 else: idx = pcn_index.nearest(midpoint) if midpoint.distance(pcn_gdf.iloc[idx].geometry) < 0.0001: ml_cooling_bonus += 0.257 # SVF proxy: primary/secondary roads in dense urban areas approximate low sky-view factor if highway in ('primary', 'secondary'): ml_cooling_bonus += 0.110 # Pre-compute bearing lat1, lon1 = G.nodes[u]['y'], G.nodes[u]['x'] lat2, lon2 = G.nodes[v]['y'], G.nodes[v]['x'] bearing = ox.bearing.calculate_bearing(lat1, lon1, lat2, lon2) # Pre-compute grade (slope) from elevation-enriched graph grade = float(data.get('grade', 0) or 0) edge_static_costs[(u, v)] = { 'length': length, 'base_weight': base_weight, 'ml_cooling_bonus': ml_cooling_bonus, 'bearing': bearing, 'grade': grade, } _precomp_time = time.time() - _precomp_start _grades = [v['grade'] for v in edge_static_costs.values() if v['grade'] != 0] print(f" ✅ Pre-computed costs for {len(edge_static_costs):,} edges in {_precomp_time:.1f}s", flush=True) print(f" ✅ Elevation-aware routing active: Uphill penalty factor = 15, edges with grade data = {len(_grades):,}", flush=True) del _grades # ========================================== # 🧠 ROUTING INTELLIGENCE # ========================================== def get_sun_position(dt): """Compute sun altitude and azimuth once per route request.""" altitude = solar.get_altitude(1.3521, 103.8198, dt) azimuth = solar.get_azimuth(1.3521, 103.8198, dt) return altitude, azimuth def calculate_sun_penalty(edge_bearing, sun_altitude, sun_azimuth): """Fast per-edge sun penalty using pre-computed sun position. No pysolar calls.""" if sun_altitude < 7: return 0 diff = abs(edge_bearing - sun_azimuth) if diff > 180: diff = 360 - diff return max(0, (90 - diff) / 90) * 0.2 def get_cool_cost_fast(u, v, data, sun_position, weather): """Fast cost function using pre-computed static values + dynamic sun/weather.""" static = edge_static_costs.get((u, v)) if not static: return data.get('length', 10) sun_altitude, sun_azimuth = sun_position sun_penalty = calculate_sun_penalty(static['bearing'], sun_altitude, sun_azimuth) temp, humidity = weather heat_index = max(0, (temp - 28) / 10) humidity_index = max(0, (humidity - 60) / 40) weather_amplifier = 1.0 + (heat_index + humidity_index) * 0.25 weight = static['base_weight'] - (static['ml_cooling_bonus'] * weather_amplifier) + sun_penalty # Elevation penalty ("Sweat Factor") # Uphill: metabolic heat scales with grade (factor 15, capped at 2.0) # Steep downhill (>5%): safety penalty (factor 3, capped at 0.6) # Gentle downhill / flat: no penalty grade = static['grade'] if grade > 0: grade_penalty = min(grade * 15, 2.0) elif grade < -0.05: grade_penalty = min(abs(grade) * 3, 0.6) else: grade_penalty = 0.0 return static['length'] * max(0.1, weight) * (1.0 + grade_penalty) def compute_route_internal(start_coords, end_coords, stop_coords=None, user_email='telegram'): """Internal route calculation function for use by Telegram bot.""" global _routes_in_progress # Stacking guard: reject if too many concurrent computations with _route_counter_lock: if _routes_in_progress >= MAX_CONCURRENT_ROUTES: print(f" ⚠️ Route rejected: {_routes_in_progress} already in progress", flush=True) return None _routes_in_progress += 1 try: start_pt = (float(start_coords[0]), float(start_coords[1])) end_pt = (float(end_coords[0]), float(end_coords[1])) stop_pt = (float(stop_coords[0]), float(stop_coords[1])) if stop_coords else None sgt = pytz.timezone('Asia/Singapore') now = datetime.now(sgt) orig = ox.distance.nearest_nodes(G, start_pt[1], start_pt[0]) dest = ox.distance.nearest_nodes(G, end_pt[1], end_pt[0]) stop = ox.distance.nearest_nodes(G, stop_pt[1], stop_pt[0]) if stop_pt else None log("⚙️", "Route computation started", user=user_email) t_start = time.time() # Fetch weather and sun position once per request current_temp, humidity, station_name = get_weather_for_route(start_pt[0], start_pt[1]) weather = (current_temp, humidity) sun_position = get_sun_position(now) def solve_path(u, v, metric='length'): if metric == 'cool': future = _route_executor.submit(nx.shortest_path, G, u, v, weight=lambda u, v, d: get_cool_cost_fast(u, v, d, sun_position, weather)) else: future = _route_executor.submit(nx.shortest_path, G, u, v, weight='length') try: return future.result(timeout=ROUTE_TIMEOUT) except concurrent.futures.TimeoutError: future.cancel() print(f" ⚠️ Route computation timed out after {ROUTE_TIMEOUT}s", flush=True) return None if stop: r_fast_1 = solve_path(orig, stop, 'length') r_fast_2 = solve_path(stop, dest, 'length') if r_fast_1 is None or r_fast_2 is None: return None r_fast = r_fast_1[:-1] + r_fast_2 r_cool_1 = solve_path(orig, stop, 'cool') r_cool_2 = solve_path(stop, dest, 'cool') if r_cool_1 is None or r_cool_2 is None: return None r_cool = r_cool_1[:-1] + r_cool_2 else: r_fast = solve_path(orig, dest, 'length') r_cool = solve_path(orig, dest, 'cool') if r_fast is None or r_cool is None: return None log("⚡", "Paths computed", fast_edges=len(r_fast), cool_edges=len(r_cool), ms=f"{(time.time()-t_start)*1000:.0f}") def process_path(route): coords = [] total_len = 0 for u, v in zip(route[:-1], route[1:]): d = G.get_edge_data(u, v)[0] total_len += d.get('length', 0) if 'geometry' in d: xs, ys = d['geometry'].xy coords.extend(list(zip(ys, xs))) else: coords.append((G.nodes[u]['y'], G.nodes[u]['x'])) coords.append((G.nodes[v]['y'], G.nodes[v]['x'])) return coords, total_len fast_coords, fast_len = process_path(r_fast) cool_coords, cool_len = process_path(r_cool) # current_temp, humidity, station_name already fetched via get_weather_for_route() above shade_gain = int(((fast_len - cool_len) / fast_len) * 100 * -1) if fast_len > 0 else 0 dist_diff = round((cool_len - fast_len) / 1000, 2) fast_eta = calculate_eta(fast_len) cool_eta = calculate_eta(cool_len) cool_steps = generate_directions(r_cool, G) fast_meta = analyze_route_attributes(r_fast, G) cool_meta = analyze_route_attributes(r_cool, G) if supabase: try: log_data = { "user_email": user_email, "start_point": str(start_pt), "end_point": str(end_pt), "via_point": str(stop_pt) if stop_pt else None, "fast_dist_km": round(fast_len/1000, 2), "cool_dist_km": round(cool_len/1000, 2), "dist_diff_km": dist_diff, "shade_gain_pct": shade_gain, "temp_c": current_temp, "weather_station": station_name } supabase.table('route_logs').insert(log_data).execute() print(" 📝 Route Logged to DB", flush=True) except Exception as e: print(f" ⚠️ DB Log Error: {e}", flush=True) kml = simplekml.Kml() ls1 = kml.newlinestring(name="Fastest Route") ls1.coords = [(lon, lat) for lat, lon in fast_coords] ls1.style.linestyle.color = simplekml.Color.red ls1.style.linestyle.width = 4 ls2 = kml.newlinestring(name="Cool Route") ls2.coords = [(lon, lat) for lat, lon in cool_coords] ls2.style.linestyle.color = simplekml.Color.green ls2.style.linestyle.width = 4 return { "status": "success", "fast_poly": fast_coords, "cool_poly": cool_coords, "stats": { "fast_dist": f"{fast_len/1000:.2f} km", "cool_dist": f"{cool_len/1000:.2f} km", "dist_diff": f"{'+' if dist_diff > 0 else ''}{dist_diff} km", "temp": current_temp, "station": station_name, "shade_gain": f"{shade_gain}%", "fast_eta": fast_eta, "cool_eta": cool_eta, "nav_steps": cool_steps, "fast_meta": fast_meta, "cool_meta": cool_meta }, "kml": kml.kml() } except Exception as e: print(f" ❌ Route calculation error: {e}", flush=True) return None finally: with _route_counter_lock: _routes_in_progress -= 1 # ========================================== # 🛣️ API ENDPOINTS # ========================================== @app.route('/') def index(): return render_template('index.html', owm_api_key=os.environ.get('OWM_API_KEY', '')) @app.route('/api/amenities', methods=['GET']) def get_amenities(): return jsonify(amenities_data) @app.route('/api/route/feedback', methods=['POST']) def submit_route_feedback(): """Store user feedback/rating for a completed route.""" data = request.json log("📥", "POST /api/route/feedback", user=data.get('email', 'guest')) email = data.get('email', 'guest') rating = data.get('rating', 0) comment = data.get('comment', '') if rating >= 4: sentiment = "positive" elif rating >= 3: sentiment = "neutral" else: sentiment = "negative" if not supabase: print(f" ⭐ Route feedback (no DB): {rating} stars - {comment}", flush=True) return jsonify({"status": "success", "message": "Feedback noted (DB not configured)"}) try: feedback_data = { "user_email": email or "guest", "sentiment": sentiment, "user_comment": f"[{rating}⭐] {comment}" if comment else f"[{rating}⭐ rating]", } supabase.table('feedback_logs').insert(feedback_data).execute() print(f" ⭐ Route feedback: {rating} stars from {email}", flush=True) return jsonify({"status": "success", "message": "Feedback saved"}) except Exception as e: print(f" ⚠️ Feedback error: {e}", flush=True) return jsonify({"status": "error", "message": str(e)}), 500 @app.route('/api/auth/signup', methods=['POST']) def signup(): if not supabase: return jsonify({"status": "error", "message": "DB Config Missing"}), 500 data = request.json log("📥", "POST /api/auth/signup", email=data.get('email', 'unknown')) try: res = supabase.auth.sign_up({"email": data['email'], "password": data['password']}) if res.user: log("📤", "Signup success", user=res.user.email) return jsonify({"status": "success", "user": res.user.email}) else: return jsonify({"status": "error", "message": "Signup failed"}), 400 except Exception as e: log("❌", "Signup error", error=str(e)) return jsonify({"status": "error", "message": str(e)}), 400 @app.route('/api/auth/login', methods=['POST']) def login(): if not supabase: return jsonify({"status": "error", "message": "DB Config Missing"}), 500 data = request.json log("📥", "POST /api/auth/login", email=data.get('email', 'unknown')) try: res = supabase.auth.sign_in_with_password({"email": data['email'], "password": data['password']}) if res.user: log("📤", "Login success", user=res.user.email) return jsonify({"status": "success", "token": res.session.access_token, "user": res.user.email}) else: return jsonify({"status": "error", "message": "Invalid credentials"}), 401 except Exception as e: log("❌", "Login error", error=str(e)) return jsonify({"status": "error", "message": str(e)}), 401 @app.route('/api/get_route/', methods=['GET']) def get_route(route_id): """Retrieve a pre-calculated route from cache.""" route_data = get_cached_route(route_id) if route_data: return jsonify(route_data) else: return jsonify({"status": "error", "message": "Route not found or expired"}), 404 @app.route('/api/geocode', methods=['GET']) def geocode(): """Geocode a place name using OneMap (Singapore) with OSMnx fallback.""" query = request.args.get('q', '').strip() if not query: return jsonify({"status": "error", "message": "No query provided"}), 400 from helpers import geocode_location coords = geocode_location(query) if coords: return jsonify({"status": "success", "lat": coords[0], "lon": coords[1]}) return jsonify({"status": "error", "message": "Location not found"}), 404 @app.route('/api/route', methods=['POST']) def calculate_route(): t0 = time.time() try: data = request.json user_email = data.get('user_email', 'guest') log("📥", "POST /api/route", user=user_email) start_pt = (float(data['start'][0]), float(data['start'][1])) end_pt = (float(data['end'][0]), float(data['end'][1])) # --- SINGAPORE SECURITY CHECK --- if not is_in_singapore(start_pt[0], start_pt[1]) or not is_in_singapore(end_pt[0], end_pt[1]): return jsonify({"status": "error", "message": "Route outside Singapore. Please select local points."}), 400 stop_pt = None if 'stop' in data and data['stop']: stop_pt = (float(data['stop'][0]), float(data['stop'][1])) result = compute_route_internal( data['start'], data['end'], data.get('stop'), user_email=data.get('user_email', 'guest') ) if result: route_id = cache_route(result) result['route_id'] = route_id log("📤", "POST /api/route done", ms=f"{(time.time()-t0)*1000:.0f}", route_id=route_id) return jsonify(result) else: log("⚠️", "POST /api/route failed", ms=f"{(time.time()-t0)*1000:.0f}") return jsonify({"status": "error"}), 500 except Exception as e: log("❌", "Error in /api/route", error=str(e)) traceback.print_exc() return jsonify({"status": "error", "message": str(e)}), 500 # --- NEW: SENSOR LOGGING ENDPOINT (V16.12) --- @app.route('/api/log/sensor', methods=['POST']) def log_sensor_data(): """Allows web app users to log WBGT data.""" t0 = time.time() data = request.json log("📥", "POST /api/log/sensor", user=data.get('user', 'unknown')) try: lat, lon = float(data.get('lat')), float(data.get('lon')) # Fetch NEA comparison data nea_temp, station = get_realtime_weather(lat, lon) if supabase: supabase.table('sensor_logs').insert({ "user_id": data.get('user', 'webapp_user'), "wbgt_value": float(data.get('wbgt')), "lat": lat, "lon": lon, "nea_temp": nea_temp, "weather_station": station, "notes": data.get('notes', 'Web App Log') }).execute() print(f" 📝 Web Sensor Log: {data.get('wbgt')} (NEA: {nea_temp})", flush=True) return jsonify({"status": "success", "nea": nea_temp}) return jsonify({"status": "error", "message": "DB offline"}), 503 except Exception as e: print(f" ⚠️ Sensor Log Error: {e}", flush=True) import traceback traceback.print_exc() return jsonify({"status": "error", "message": str(e)}), 500 @app.route('/manifest.json') def manifest(): return jsonify({ "name": "CoolRide SG", "short_name": "CoolRide", "start_url": "/", "display": "standalone", "background_color": "#ffffff", "theme_color": "#2563eb", "icons": [ { "src": "https://em-content.zobj.net/source/microsoft-teams/363/person-biking_1f6b4.png", "sizes": "192x192", "type": "image/png" }, { "src": "https://em-content.zobj.net/source/microsoft-teams/363/person-biking_1f6b4.png", "sizes": "512x512", "type": "image/png" } ] }) # ========================================== # 🚀 STARTUP # ========================================== if __name__ == '__main__': _startup_total = startup_time.time() - _startup_begin print(f"✅ COOLRIDE STARTUP COMPLETE: {_startup_total:.2f}s", flush=True) app.run(host='0.0.0.0', port=7860, threaded=True)