Spaces:
Sleeping
Sleeping
File size: 5,759 Bytes
37cac80 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 | 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"<p style='color:red'>Invalid tower JSON: {e}</p>", "Error parsing input"
if not api_key.strip():
return "<p style='color:red'>Please enter your OpenCelliD API key.</p>", "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 "<p style='color:orange'>No position available yet. Enter tower data first.</p>", "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() |