import gradio as gr import folium import json import time from locator import CellTower, lookup_tower, trilaterate from dead_reckoning import DeadReckoner, Fix # Global dead reckoner — persists across UI interactions reckoner = DeadReckoner() def build_map(fix, towers_with_pos): """Build a folium map centered on the estimated position.""" m = folium.Map(location=[fix.lat, fix.lon], zoom_start=13) # Accuracy circle folium.Circle( location=[fix.lat, fix.lon], radius=fix.accuracy_km * 1000, # convert km to meters color="#3b82f6", fill=True, fill_opacity=0.15, popup=f"Estimated position ({fix.source})\nAccuracy: ~{fix.accuracy_km:.1f} km" ).add_to(m) # Your estimated position folium.Marker( location=[fix.lat, fix.lon], popup=f"You are here (±{fix.accuracy_km:.1f} km)\nSource: {fix.source}", icon=folium.Icon(color="blue", icon="user", prefix="fa") ).add_to(m) # Draw each tower for t in towers_with_pos: folium.Marker( location=[t.lat, t.lon], popup=f"Tower {t.cid}\nSignal: {t.signal} dBm", icon=folium.Icon(color="red", icon="signal", prefix="fa") ).add_to(m) return m._repr_html_() def locate(api_key, towers_json, speed_kmh, bearing_deg): """Main function called by the UI.""" # ── Parse tower input ─────────────────────────────────────────────────── try: raw = json.loads(towers_json) towers = [CellTower(**t) for t in raw] except Exception as e: return f"
Invalid tower JSON: {e}
", "Error parsing input" if not api_key.strip(): return "Please enter your OpenCelliD API key.
", "No API key" # ── Look up each tower's coordinates ──────────────────────────────────── resolved = [] for t in towers: result = lookup_tower(t, api_key) if result: resolved.append(result) status_lines = [f"Resolved {len(resolved)}/{len(towers)} towers"] # ── Trilaterate ───────────────────────────────────────────────────────── if resolved: result = trilaterate(resolved) if result: lat, lon, accuracy = result fix = Fix(lat=lat, lon=lon, accuracy_km=accuracy, source="tower") reckoner.add_fix(fix) status_lines.append(f"Position: {lat:.5f}, {lon:.5f}") status_lines.append(f"Accuracy: ~{accuracy:.1f} km") map_html = build_map(fix, resolved) return map_html, "\n".join(status_lines) # ── Dead reckoning fallback ────────────────────────────────────────────── status_lines.append("No towers resolved — falling back to dead reckoning") dr_fix = reckoner.estimate_now(speed_kmh=speed_kmh, bearing_deg=bearing_deg) if dr_fix: status_lines.append(f"DR Position: {dr_fix.lat:.5f}, {dr_fix.lon:.5f}") status_lines.append(f"Accuracy: ~{dr_fix.accuracy_km:.1f} km (degraded)") map_html = build_map(dr_fix, []) return map_html, "\n".join(status_lines) return "No position available yet. Enter tower data first.
", "No fix" # ── Example tower data users can edit ─────────────────────────────────────── EXAMPLE_TOWERS = json.dumps([ {"mcc": 404, "mnc": 20, "lac": 1234, "cid": 56789, "signal": -75}, {"mcc": 404, "mnc": 20, "lac": 1234, "cid": 56790, "signal": -90}, {"mcc": 404, "mnc": 20, "lac": 1234, "cid": 56791, "signal": -105} ], indent=2) # ── Gradio UI ──────────────────────────────────────────────────────────────── with gr.Blocks(title="Cell Tower GPS", theme=gr.themes.Base()) as demo: gr.Markdown(""" # 📡 Cell Tower GPS Enter visible cell towers → get your position on a map. Falls back to **dead reckoning** if towers can't be resolved. Get a free API key at [opencellid.org](https://opencellid.org). """) with gr.Row(): with gr.Column(scale=1): api_key = gr.Textbox( label="OpenCelliD API Key", placeholder="your-api-key-here", type="password" ) towers_input = gr.Textbox( label="Visible Cell Towers (JSON)", value=EXAMPLE_TOWERS, lines=12 ) gr.Markdown("**Dead Reckoning Fallback** (used when towers fail)") speed = gr.Slider(0, 120, value=0, label="Speed (km/h)") bearing = gr.Slider(0, 359, value=0, label="Bearing (° from North)") locate_btn = gr.Button("📍 Locate Me", variant="primary") with gr.Column(scale=2): map_output = gr.HTML(label="Map") status_output = gr.Textbox(label="Status", lines=5, interactive=False) locate_btn.click( fn=locate, inputs=[api_key, towers_input, speed, bearing], outputs=[map_output, status_output] ) if __name__ == "__main__": demo.launch()