Initial commit - Trekker V2 source

This commit is contained in:
Cortex committed 2026-06-10 11:03:37 -04:00
commit d71faf19e3
65 files changed
+3615

No files matched your search

View File
Whitespace-only changes.
+18
View File
@@ -0,0 +1,18 @@
from pathlib import Path
import pytest
from app.storage.database import connect
from app.storage.route_store import Store
FIXTURES = Path(__file__).parent / "fixtures"
@pytest.fixture
def fixtures() -> Path:
return FIXTURES
@pytest.fixture
def store(tmp_path) -> Store:
return Store(connect(str(tmp_path / "test.db")))
+21
View File
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="GaiaGPS for Android"
xmlns="http://www.topografix.com/GPX/1/1"
xmlns:topografix="http://www.topografix.com/GPX/Private/TopoGrafix/0/1">
<metadata><name>Windrock Loop</name></metadata>
<wpt lat="36.2000" lon="-84.3600"><name>Trailhead</name><sym>Trail Head</sym></wpt>
<wpt lat="36.2030" lon="-84.3600"><name>Water Crossing</name><desc>About 1 ft deep</desc></wpt>
<wpt lat="36.2060" lon="-84.3600"><name>Camp</name><sym>Campground</sym></wpt>
<trk>
<name>Windrock Loop</name>
<trkseg>
<trkpt lat="36.2000" lon="-84.3600"><ele>400.0</ele><time>2026-06-01T10:00:00Z</time></trkpt>
<trkpt lat="36.2010" lon="-84.3600"><ele>410.0</ele><time>2026-06-01T10:05:00Z</time></trkpt>
<trkpt lat="36.2020" lon="-84.3600"><ele>425.0</ele><time>2026-06-01T10:10:00Z</time></trkpt>
<trkpt lat="36.2030" lon="-84.3600"><ele>430.0</ele><time>2026-06-01T10:15:00Z</time></trkpt>
<trkpt lat="36.2040" lon="-84.3600"><ele>420.0</ele><time>2026-06-01T10:20:00Z</time></trkpt>
<trkpt lat="36.2050" lon="-84.3600"><ele>445.0</ele><time>2026-06-01T10:25:00Z</time></trkpt>
<trkpt lat="36.2060" lon="-84.3600"><ele>460.0</ele><time>2026-06-01T10:30:00Z</time></trkpt>
</trkseg>
</trk>
</gpx>
+9
View File
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="hand" xmlns="http://www.topografix.com/GPX/1/1">
<trk>
<trkseg>
<trkpt lat="36.1000" lon="-84.5000"></trkpt>
<trkpt lat="36.1010" lon="-84.5000"></trkpt>
</trkseg>
</trk>
</gpx>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<gpx version="1.1" creator="onXmaps offroad android"
xmlns="http://www.topografix.com/GPX/1/1"
xmlns:onx="http://wwww.onxmaps.com/">
<trk>
<name>Ridge Run</name>
<trkseg>
<trkpt lat="36.3000" lon="-84.4000"><ele>500.0</ele></trkpt>
<trkpt lat="36.3010" lon="-84.4000"><ele>520.0</ele></trkpt>
<trkpt lat="36.3020" lon="-84.4000"><ele>515.0</ele></trkpt>
</trkseg>
</trk>
</gpx>
+103
View File
@@ -0,0 +1,103 @@
import pytest
from fastapi.testclient import TestClient
@pytest.fixture
def client(tmp_path, monkeypatch, fixtures):
from app import config, deps
monkeypatch.setattr(config.settings, "data_dir", str(tmp_path))
deps.get_store.cache_clear()
deps.get_llm.cache_clear()
deps.get_elevation.cache_clear()
deps.get_offline_maps.cache_clear()
from app.main import app
with TestClient(app) as c:
yield c
deps.get_store.cache_clear()
def test_health(client):
resp = client.get("/api/health")
assert resp.status_code == 200
assert resp.json()["status"] == "ok"
def test_upload_list_get_export_delete(client, fixtures):
resp = client.post(
"/api/routes/upload",
files={"file": ("gaia.gpx", (fixtures / "gaia.gpx").read_bytes(), "application/gpx+xml")},
)
assert resp.status_code == 200, resp.text
route = resp.json()
assert route["source"] == "gaia"
rid = route["id"]
assert len(client.get("/api/routes").json()) == 1
assert client.get(f"/api/routes/{rid}").json()["name"] == "Windrock Loop"
gpx = client.get(f"/api/routes/{rid}/export?format=gpx")
assert gpx.status_code == 200
assert "grade_pct" in gpx.text
kml = client.get(f"/api/routes/{rid}/export?format=kml")
assert "LineString" in kml.text
assert client.delete(f"/api/routes/{rid}").status_code == 200
assert client.get(f"/api/routes/{rid}").status_code == 404
def test_upload_rejects_non_gpx(client):
resp = client.post("/api/routes/upload", files={"file": ("x.txt", b"hi", "text/plain")})
assert resp.status_code == 400
def test_guide_save_and_link(client, fixtures):
rid = client.post(
"/api/routes/upload",
files={"file": ("onx.gpx", (fixtures / "onx.gpx").read_bytes(), "application/gpx+xml")},
).json()["id"]
guide = client.post("/api/trails", json={"name": "Ridge guide", "difficulty": "hard"}).json()
linked = client.put(f"/api/routes/{rid}/trail-guide", json={"trail_guide_id": guide["id"]})
assert linked.json()["trail_guide_id"] == guide["id"]
missing = client.put(f"/api/routes/{rid}/trail-guide", json={"trail_guide_id": "nope"})
assert missing.status_code == 404
def test_generate_trail_card(client, fixtures):
rid = client.post(
"/api/routes/upload",
files={"file": ("gaia.gpx", (fixtures / "gaia.gpx").read_bytes(), "application/gpx+xml")},
).json()["id"]
resp = client.post(f"/api/routes/{rid}/generate/trail_card")
assert resp.status_code == 200
assert resp.json()["data"]["route_name"] == "Windrock Loop"
# weather overlay requires cached weather -> 409
resp = client.post(f"/api/routes/{rid}/generate/weather_overlay")
assert resp.status_code == 409
assert client.post(f"/api/routes/{rid}/generate/bogus").status_code == 404
def test_offline_pack_estimate_and_cap(client):
body = {"name": "t", "bbox": [-84.4, 36.1, -84.3, 36.2], "min_zoom": 10, "max_zoom": 12,
"layers": ["base"]}
est = client.post("/api/offline-maps/estimate", json=body).json()
assert est["tile_count"] > 0
huge = dict(body, bbox=[-90.0, 30.0, -80.0, 40.0], min_zoom=0, max_zoom=16)
resp = client.post("/api/offline-maps", json=huge)
assert resp.status_code == 400
assert "cap" in resp.json()["detail"]
def test_sync_bundle_endpoints(client, fixtures):
client.post(
"/api/routes/upload",
files={"file": ("onx.gpx", (fixtures / "onx.gpx").read_bytes(), "application/gpx+xml")},
)
bundle = client.get("/api/sync/bundle").json()
assert len(bundle["routes"]) == 1
resp = client.post("/api/sync/bundle", json=bundle)
assert resp.json()["applied"] == {"routes": 0, "trail_guides": 0}
+38
View File
@@ -0,0 +1,38 @@
from app.export.gpx_writer import write_gpx
from app.export.kml_writer import write_kml
from app.ingest.gpx_parser import parse_gpx
from app.models.trail_guide import TrailGuide, WaterCrossing
def test_gpx_round_trip(fixtures):
original = parse_gpx((fixtures / "gaia.gpx").read_bytes())
exported = write_gpx(original)
reimported = parse_gpx(exported)
assert len(reimported.points) == len(original.points)
assert len(reimported.waypoints) == len(original.waypoints)
assert [w.name for w in reimported.waypoints] == [w.name for w in original.waypoints]
assert [p.ele for p in reimported.points] == [p.ele for p in original.points]
# segments regenerate identically from preserved waypoints
assert len(reimported.segments) == len(original.segments)
assert [s.distance_m for s in reimported.segments] == [s.distance_m for s in original.segments]
def test_gpx_enrichment_fields(fixtures):
route = parse_gpx((fixtures / "gaia.gpx").read_bytes())
guide = TrailGuide(
name="g", difficulty="moderate",
water_crossings=[WaterCrossing(name="Creek", depth_ft=1.0)],
)
out = write_gpx(route, guide)
assert "grade_pct" in out
assert 'depth_ft="1.0"' in out
assert "moderate" in out
def test_kml_output(fixtures):
route = parse_gpx((fixtures / "gaia.gpx").read_bytes())
out = write_kml(route)
assert "<" + "?xml" in out or out.startswith("<?xml")
assert "LineString" in out
assert "Trailhead" in out
assert out.count("Placemark") >= 2 # track + waypoints
+67
View File
@@ -0,0 +1,67 @@
import pytest
from app.generators import GENERATORS
from app.generators.base import GeneratorError
from app.generators.elevation_map import grade_color
from app.generators.trail_card import TrailCardGenerator
from app.generators.weather_overlay import WeatherOverlayGenerator
from app.ingest.gpx_parser import parse_gpx
from app.models.trail_guide import TrailGuide
WEATHER = {
"days": 7,
"segments": {
"0": {"daily": [{"date": "2026-06-10", "temp_min_f": 60, "temp_max_f": 85,
"precip_prob_max": 70, "precip_sum_in": 0.4,
"wind_max_kmh": 45, "lightning_risk": True}]},
"1": {"daily": [{"date": "2026-06-10", "temp_min_f": 60, "temp_max_f": 85,
"precip_prob_max": 10, "precip_sum_in": 0.0,
"wind_max_kmh": 10, "lightning_risk": False}]},
},
}
def test_registry_names():
assert set(GENERATORS) == {"trail_card", "elevation_map", "weather_overlay"}
def test_trail_card_degrades_without_guide(fixtures):
route = parse_gpx((fixtures / "gaia.gpx").read_bytes())
asset = TrailCardGenerator().generate(route, None, None)
assert asset.data["guide"] is None
assert len(asset.data["segments"]) == 2
assert asset.data["segments"][0]["weather_today"] is None
def test_trail_card_with_guide_and_weather(fixtures):
route = parse_gpx((fixtures / "gaia.gpx").read_bytes())
guide = TrailGuide(name="WG", difficulty="difficult", gate_codes=["1234"])
asset = TrailCardGenerator().generate(route, guide, WEATHER)
assert asset.data["guide"]["gate_codes"] == ["1234"]
assert asset.data["segments"][0]["difficulty"] == "difficult"
assert asset.data["segments"][0]["weather_today"]["precip_prob_max"] == 70
def test_weather_overlay_requires_weather(fixtures):
route = parse_gpx((fixtures / "gaia.gpx").read_bytes())
with pytest.raises(GeneratorError):
WeatherOverlayGenerator().generate(route, None, None)
asset = WeatherOverlayGenerator().generate(route, None, WEATHER)
segs = asset.data["segments"]
assert segs[0]["wind_advisory"] is True
assert segs[0]["lightning_risk"] is True
assert segs[1]["wind_advisory"] is False
def test_elevation_map(fixtures):
route = parse_gpx((fixtures / "gaia.gpx").read_bytes())
asset = GENERATORS["elevation_map"]().generate(route, None, None)
assert len(asset.data["segments"]) == 2
assert {c["type"] for c in asset.data["callouts"]} == {"summit", "low_point"}
summit = next(c for c in asset.data["callouts"] if c["type"] == "summit")
assert summit["ele_m"] == 460.0
def test_grade_colors():
assert grade_color(2) == "#2ecc71"
assert grade_color(30) == "#e74c3c"
+31
View File
@@ -0,0 +1,31 @@
from app.ingest.gpx_parser import detect_source, parse_gpx
def test_gaia_parse(fixtures):
route = parse_gpx((fixtures / "gaia.gpx").read_bytes(), filename="gaia.gpx")
assert route.source == "gaia"
assert route.name == "Windrock Loop"
assert len(route.points) == 7
assert len(route.waypoints) == 3
assert route.points[0].ele == 400.0
assert route.points[0].time.startswith("2026-06-01T10:00:00")
def test_onx_parse(fixtures):
route = parse_gpx((fixtures / "onx.gpx").read_bytes())
assert route.source == "onx"
assert route.name == "Ridge Run"
assert len(route.points) == 3
assert route.waypoints == []
def test_minimal_parse(fixtures):
route = parse_gpx((fixtures / "minimal.gpx").read_bytes(), filename="minimal.gpx")
assert route.source == "manual"
assert route.name == "minimal"
assert all(p.ele is None for p in route.points)
def test_detect_source_namespace_fallback():
assert detect_source(None, '<gpx xmlns:onx="http://wwww.onxmaps.com/">') == "onx"
assert detect_source("Some App", "<gpx>") == "manual"
+42
View File
@@ -0,0 +1,42 @@
from app.ingest.gpx_parser import parse_gpx
from app.ingest.segmenter import haversine_m
def test_haversine_known_distance():
# ~111.2 km per degree of latitude
d = haversine_m(36.0, -84.0, 37.0, -84.0)
assert 110_000 < d < 112_500
def test_waypoint_driven_segments(fixtures):
route = parse_gpx((fixtures / "gaia.gpx").read_bytes())
# Trailhead (idx 0), Water Crossing (idx 3), Camp (idx 6) -> two segments
assert len(route.segments) == 2
s1, s2 = route.segments
assert s1.start_wpt == "Trailhead" and s1.end_wpt == "Water Crossing"
assert s2.start_wpt == "Water Crossing" and s2.end_wpt == "Camp"
assert s1.start_idx == 0 and s1.end_idx == 3
assert s2.start_idx == 3 and s2.end_idx == 6
# each leg covers 0.003 deg lat ~ 334m
assert 300 < s1.distance_m < 370
assert s1.elevation_gain_m == 30.0
assert s1.duration_s == 900.0
assert s2.elevation_gain_m == 40.0 # 430->420 (-10), 420->445 (+25), 445->460 (+15)
assert s2.elevation_loss_m == 10.0
def test_no_waypoints_single_segment(fixtures):
route = parse_gpx((fixtures / "onx.gpx").read_bytes())
assert len(route.segments) == 1
seg = route.segments[0]
assert seg.start_idx == 0 and seg.end_idx == 2
assert seg.elevation_gain_m == 20.0
assert seg.elevation_loss_m == 5.0
def test_route_stats(fixtures):
route = parse_gpx((fixtures / "gaia.gpx").read_bytes())
assert route.stats.elevation_min_m == 400.0
assert route.stats.elevation_max_m == 460.0
assert route.stats.elevation_gain_m == 70.0
assert route.stats.duration_s == 1800.0
+34
View File
@@ -0,0 +1,34 @@
import pytest
from app.ingest.gpx_parser import parse_gpx
from app.models.trail_guide import TrailGuide
def test_route_crud(store, fixtures):
route = parse_gpx((fixtures / "gaia.gpx").read_bytes())
store.save_route(route)
loaded = store.get_route(route.id)
assert loaded == route
assert [r.id for r in store.list_routes()] == [route.id]
assert store.delete_route(route.id)
assert store.get_route(route.id) is None
def test_trail_guide_link(store, fixtures):
route = store.save_route(parse_gpx((fixtures / "onx.gpx").read_bytes()))
guide = store.save_trail_guide(TrailGuide(name="Ridge guide", difficulty="moderate"))
linked = store.link_trail_guide(route.id, guide.id)
assert linked.trail_guide_id == guide.id
unlinked = store.link_trail_guide(route.id, None)
assert unlinked.trail_guide_id is None
with pytest.raises(KeyError):
store.link_trail_guide(route.id, "nonexistent")
def test_weather_cache(store, fixtures):
route = store.save_route(parse_gpx((fixtures / "onx.gpx").read_bytes()))
assert store.get_weather(route.id) is None
store.save_weather(route.id, {"days": 7, "segments": {}})
cached = store.get_weather(route.id)
assert cached["days"] == 7
assert "fetched_at" in cached
+30
View File
@@ -0,0 +1,30 @@
from app.ingest.gpx_parser import parse_gpx
from app.models.trail_guide import TrailGuide
from app.storage.database import connect
from app.storage.route_store import Store
from app.sync.sync_daemon import build_bundle, merge_bundle
def test_bundle_merge_newest_wins(tmp_path, fixtures):
home = Store(connect(str(tmp_path / "home.db")))
neutron = Store(connect(str(tmp_path / "neutron.db")))
route = parse_gpx((fixtures / "gaia.gpx").read_bytes())
home.save_route(route)
home.save_trail_guide(TrailGuide(name="Guide A"))
applied = merge_bundle(neutron, build_bundle(home))
assert applied == {"routes": 1, "trail_guides": 1}
assert neutron.get_route(route.id).name == route.name
# neutron edits the route -> newer updated_at -> wins on merge back
edited = neutron.get_route(route.id)
edited.name = "Renamed on Neutron"
neutron.save_route(edited)
applied = merge_bundle(home, build_bundle(neutron))
assert applied["routes"] == 1
assert home.get_route(route.id).name == "Renamed on Neutron"
# re-merging identical data is a no-op
applied = merge_bundle(home, build_bundle(neutron))
assert applied == {"routes": 0, "trail_guides": 0}
+45
View File
@@ -0,0 +1,45 @@
from app.services.weather import THUNDER_CODES, build_tiers
RAW = {
"hourly": {
"time": [f"2026-06-10T{h:02d}:00" for h in range(24)],
"temperature_2m": [60 + h for h in range(24)],
"precipitation_probability": [10] * 12 + [80] * 12,
"precipitation": [0.0] * 12 + [0.1] * 12,
"wind_speed_10m": [10] * 23 + [50],
"wind_gusts_10m": [15] * 24,
"weather_code": [1] * 23 + [95],
},
"daily": {
"time": ["2026-06-10"],
"temperature_2m_max": [83],
"temperature_2m_min": [60],
"precipitation_probability_max": [80],
"precipitation_sum": [1.2],
"wind_speed_10m_max": [50],
"weather_code": [95],
},
}
def test_build_tiers_buckets():
tiers = build_tiers(RAW)
assert len(tiers["hourly"]) == 24
assert len(tiers["6h"]) == 4
assert len(tiers["12h"]) == 2
assert len(tiers["daily"]) == 1
def test_tier_aggregation():
tiers = build_tiers(RAW)
first12, last12 = tiers["12h"]
assert first12["precip_prob_max"] == 10
assert last12["precip_prob_max"] == 80
assert last12["wind_advisory"] is True
assert last12["lightning_risk"] is True
assert first12["lightning_risk"] is False
assert tiers["daily"][0]["lightning_risk"] is True
def test_thunder_codes():
assert 95 in THUNDER_CODES and 99 in THUNDER_CODES