Spaces:
Runtime error
Runtime error
Download app.py from Thermal-Optimizers/coolride-engine: direct link, hf CLI and curl.
- Browser
- Download file 15.7 kB
-
https://huggingface.co/spaces/Thermal-Optimizers/coolride-engine/resolve/main/app.py
- Command line
-
hf download hf://spaces/Thermal-Optimizers/coolride-engine/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Thermal-Optimizers/coolride-engine/resolve/main/app.py
15.7 kB
| import os | |
| import time | |
| import json | |
| import math | |
| 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 | |
| # ========================================== | |
| # π INITIALIZATION | |
| # ========================================== | |
| app = Flask(__name__) | |
| CORS(app) | |
| print("π COOLRIDE ENGINE V14.3 (SMART NAV) INITIALIZING...") | |
| # --- DATABASE --- | |
| SUPABASE_URL = "https://rromwbzxziguxyxbtzos.supabase.co" | |
| SUPABASE_KEY = "sb_publishable_l1rrLmeDidj0QldiLXBYyA_TbSsD35s" | |
| try: | |
| supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY) | |
| print(" β Connected to Supabase Database.") | |
| except Exception as e: | |
| print(f" β οΈ Database Connection Failed: {e}") | |
| supabase = None | |
| # 1. LOAD MAP | |
| MAP_PATH = "Data/singapore_final.graphml.gz" | |
| if os.path.exists(MAP_PATH): | |
| print(f" π Loading Graph: {MAP_PATH}...") | |
| G = ox.load_graphml(MAP_PATH) | |
| print(f" β Graph Loaded: {len(G.nodes):,} nodes.") | |
| else: | |
| raise FileNotFoundError("CRITICAL: singapore_final.graphml.gz not found!") | |
| # 2. LAYERS (Trees, Water, PCN, Amenities) | |
| # ... (Keep your existing layer loading code here, it is unchanged) ... | |
| print(" π³ Indexing Layers...") | |
| try: | |
| trees_df = pd.read_csv("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.") | |
| except Exception as e: | |
| print(f" β οΈ Tree load failed: {e}") | |
| tree_index = None | |
| try: | |
| water_gdf = gpd.read_file("Data/URA_Waterbody.geojson") | |
| water_index = STRtree(water_gdf.geometry) | |
| print(f" β Indexed {len(water_gdf):,} Water Bodies.") | |
| except: | |
| water_index = None | |
| print(" β οΈ Water load failed.") | |
| try: | |
| pcn_gdf = gpd.read_file("Data/ParkConnectorLoop.geojson") | |
| pcn_index = STRtree(pcn_gdf.geometry) | |
| print(f" β Indexed {len(pcn_gdf):,} PCN Segments.") | |
| except: | |
| pcn_index = None | |
| print(" β οΈ PCN load failed.") | |
| amenities_data = [] | |
| try: | |
| hawkers = gpd.read_file("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("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.") | |
| except: | |
| print(" β οΈ Amenities load failed.") | |
| # ========================================== | |
| # π§ INTELLIGENCE MODULES | |
| # ========================================== | |
| def get_realtime_weather(lat, lon): | |
| try: | |
| url = "https://api.data.gov.sg/v1/environment/air-temperature" | |
| resp = requests.get(url, timeout=2).json() | |
| stations = resp['metadata']['stations'] | |
| readings = resp['items'][0]['readings'] | |
| reading_map = {r['station_id']: r['value'] for r in readings} | |
| nearest_station = "General SG" | |
| nearest_temp = 31.5 | |
| min_dist = float('inf') | |
| for station in stations: | |
| s_lat = station['location']['latitude'] | |
| s_lon = station['location']['longitude'] | |
| dist = math.sqrt((lat - s_lat)**2 + (lon - s_lon)**2) | |
| if dist < min_dist and station['id'] in reading_map: | |
| min_dist = dist | |
| nearest_station = station['name'] | |
| nearest_temp = reading_map[station['id']] | |
| return nearest_temp, nearest_station | |
| except: | |
| return 31.5, "Fallback (Avg)" | |
| def calculate_sun_factor(edge_bearing, dt): | |
| if dt.hour < 7 or dt.hour > 19: return 0 | |
| altitude = solar.get_altitude(1.3521, 103.8198, dt) | |
| azimuth = solar.get_azimuth(1.3521, 103.8198, dt) | |
| if altitude < 0: return 0 | |
| diff = abs(edge_bearing - azimuth) | |
| if diff > 180: diff = 360 - diff | |
| return max(0, (90 - diff) / 90) * 0.2 | |
| def get_cool_cost(u, v, data, dt): | |
| length = data.get('length', 10) | |
| highway = data.get('highway', '') | |
| surface = data.get('surface', 'unknown') | |
| base_weight = 1.0 | |
| if highway in ['cycleway', 'path']: base_weight = 0.5 | |
| elif highway in ['primary']: base_weight = 1.2 | |
| if surface in ['concrete', 'grass']: base_weight -= 0.1 | |
| elif surface == 'asphalt': base_weight += 0.05 | |
| bonus = 0 | |
| if 'geometry' in data: | |
| midpoint = data['geometry'].interpolate(0.5, normalized=True) | |
| else: | |
| midpoint = Point(G.nodes[u]['x'], G.nodes[u]['y']) | |
| if tree_index: | |
| idx = tree_index.nearest(midpoint) | |
| if midpoint.distance(trees_gdf.iloc[idx].geometry) < 0.0002: bonus += 0.25 | |
| if water_index: | |
| idx = water_index.nearest(midpoint) | |
| if midpoint.distance(water_gdf.iloc[idx].geometry) < 0.0005: bonus += 0.15 | |
| if pcn_index: | |
| idx = pcn_index.nearest(midpoint) | |
| if midpoint.distance(pcn_gdf.iloc[idx].geometry) < 0.0001: bonus += 0.2 | |
| 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) | |
| sun_penalty = calculate_sun_factor(bearing, dt) | |
| final_weight = max(0.1, base_weight - bonus + sun_penalty) | |
| return length * final_weight | |
| # --- NAVIGATION & ANALYSIS HELPERS (UPDATED) --- | |
| def calculate_eta(length_m): | |
| minutes = math.ceil(length_m / 250) # 15km/h | |
| return f"{minutes} min" | |
| def get_bearing(lat1, lon1, lat2, lon2): | |
| dLon = math.radians(lon2 - lon1) | |
| y = math.sin(dLon) * math.cos(math.radians(lat2)) | |
| x = math.cos(math.radians(lat1)) * math.sin(math.radians(lat2)) \ | |
| - math.sin(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.cos(dLon) | |
| brng = math.degrees(math.atan2(y, x)) | |
| return (brng + 360) % 360 | |
| def generate_directions(path, G): | |
| steps = [] | |
| prev_name = None | |
| dist_accum = 0 | |
| for i in range(len(path) - 1): | |
| u = path[i] | |
| v = path[i+1] | |
| edge_data = G.get_edge_data(u, v)[0] | |
| name = edge_data.get('name', 'Path') | |
| length = edge_data.get('length', 0) | |
| if isinstance(name, list): name = name[0] | |
| if name != prev_name: | |
| if prev_name: | |
| # Calculate turn angle | |
| if i > 0: | |
| prev_u = path[i-1] | |
| lat1, lon1 = G.nodes[prev_u]['y'], G.nodes[prev_u]['x'] | |
| lat2, lon2 = G.nodes[u]['y'], G.nodes[u]['x'] | |
| lat3, lon3 = G.nodes[v]['y'], G.nodes[v]['x'] | |
| b1 = get_bearing(lat1, lon1, lat2, lon2) | |
| b2 = get_bearing(lat2, lon2, lat3, lon3) | |
| diff = (b2 - b1 + 180) % 360 - 180 | |
| turn = "Continue" | |
| if diff < -45: turn = "Turn Left" | |
| elif diff > 45: turn = "Turn Right" | |
| steps.append(f"{turn} onto {prev_name} ({int(dist_accum)}m)") | |
| else: | |
| steps.append(f"Start on {prev_name}") | |
| prev_name = name | |
| dist_accum = 0 | |
| dist_accum += length | |
| if prev_name: steps.append(f"Arrive at destination via {prev_name}") | |
| return steps[:10] # Top 10 steps | |
| def analyze_route_attributes(path, G): | |
| surfaces = {} | |
| highways = {} | |
| total_len = 0 | |
| for u, v in zip(path[:-1], path[1:]): | |
| data = G.get_edge_data(u, v)[0] | |
| length = data.get('length', 0) | |
| total_len += length | |
| surf = data.get('surface', 'paved') | |
| if isinstance(surf, list): surf = surf[0] | |
| surfaces[surf] = surfaces.get(surf, 0) + length | |
| hw = data.get('highway', 'road') | |
| if isinstance(hw, list): hw = hw[0] | |
| highways[hw] = highways.get(hw, 0) + length | |
| def get_dominant(d): | |
| if not d: return "Unknown" | |
| dom = max(d, key=d.get) | |
| pct = int((d[dom] / total_len) * 100) if total_len > 0 else 0 | |
| return f"{dom.title()} ({pct}%)" | |
| return { "surface": get_dominant(surfaces), "type": get_dominant(highways) } | |
| # ========================================== | |
| # π£οΈ API ENDPOINTS | |
| # ========================================== | |
| def index(): | |
| return render_template('index.html') | |
| def get_amenities(): | |
| return jsonify(amenities_data) | |
| def signup(): | |
| if not supabase: return jsonify({"status": "error", "message": "DB Config Missing"}), 500 | |
| data = request.json | |
| try: | |
| res = supabase.auth.sign_up({"email": data['email'], "password": data['password']}) | |
| if res.user: | |
| return jsonify({"status": "success", "user": res.user.email}) | |
| else: | |
| return jsonify({"status": "error", "message": "Signup failed"}), 400 | |
| except Exception as e: | |
| return jsonify({"status": "error", "message": str(e)}), 400 | |
| def login(): | |
| if not supabase: return jsonify({"status": "error", "message": "DB Config Missing"}), 500 | |
| data = request.json | |
| try: | |
| res = supabase.auth.sign_in_with_password({"email": data['email'], "password": data['password']}) | |
| if res.user: | |
| 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: | |
| return jsonify({"status": "error", "message": str(e)}), 401 | |
| def calculate_route(): | |
| try: | |
| data = request.json | |
| user_email = data.get('user_email', 'guest') | |
| start_pt = (float(data['start'][0]), float(data['start'][1])) | |
| end_pt = (float(data['end'][0]), float(data['end'][1])) | |
| stop_pt = None | |
| if 'stop' in data and data['stop']: | |
| stop_pt = (float(data['stop'][0]), float(data['stop'][1])) | |
| 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 | |
| print(f" βοΈ Calculating for {user_email}...") | |
| def solve_path(u, v, metric='length'): | |
| if metric == 'cool': | |
| return nx.shortest_path(G, u, v, weight=lambda u, v, d: get_cool_cost(u, v, d, now)) | |
| return nx.shortest_path(G, u, v, weight='length') | |
| if stop: | |
| r_fast = solve_path(orig, stop, 'length')[:-1] + solve_path(stop, dest, 'length') | |
| r_cool = solve_path(orig, stop, 'cool')[:-1] + solve_path(stop, dest, 'cool') | |
| else: | |
| r_fast = solve_path(orig, dest, 'length') | |
| r_cool = solve_path(orig, dest, 'cool') | |
| # Geometry | |
| 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) | |
| # Metrics | |
| current_temp, station_name = get_realtime_weather(start_pt[0], start_pt[1]) | |
| shade_gain = int(((fast_len - cool_len) / fast_len) * 100 * -1) | |
| 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() | |
| except Exception as e: | |
| print(f" β οΈ DB Log Error: {e}") | |
| # KML | |
| 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 jsonify({ | |
| "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"β Error: {e}") | |
| return jsonify({"status": "error", "message": str(e)}), 500 | |
| # --- PWA MANIFEST --- | |
| 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" | |
| } | |
| ] | |
| }) | |
| if __name__ == '__main__': | |
| app.run(host='0.0.0.0', port=7860) |