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.
+32
View File
@@ -0,0 +1,32 @@
"""Export API: enriched GPX / KML downloads."""
from __future__ import annotations
import re
from fastapi import APIRouter, HTTPException, Query
from fastapi.responses import Response
from app.deps import get_store
from app.export.gpx_writer import write_gpx
from app.export.kml_writer import write_kml
router = APIRouter(prefix="/api/routes", tags=["export"])
@router.get("/{route_id}/export")
def export_route(route_id: str, format: str = Query("gpx", pattern="^(gpx|kml)$")):
store = get_store()
route = store.get_route(route_id)
if route is None:
raise HTTPException(404, "route not found")
guide = store.get_trail_guide(route.trail_guide_id) if route.trail_guide_id else None
safe_name = re.sub(r"[^A-Za-z0-9_-]+", "_", route.name).strip("_") or "route"
if format == "gpx":
body, media = write_gpx(route, guide), "application/gpx+xml"
else:
body, media = write_kml(route, guide), "application/vnd.google-earth.kml+xml"
return Response(
content=body, media_type=media,
headers={"Content-Disposition": f'attachment; filename="{safe_name}.{format}"'},
)
+71
View File
@@ -0,0 +1,71 @@
"""Offline map pack API: estimate, create, list, status, delete, tile serving."""
from __future__ import annotations
from fastapi import APIRouter, HTTPException
from fastapi.responses import FileResponse
from pydantic import BaseModel, Field
from app.deps import get_offline_maps, get_store
from app.services.offline_maps import estimate_tile_count
router = APIRouter(prefix="/api/offline-maps", tags=["offline-maps"])
AVG_TILE_BYTES = 25_000 # rough raster tile size for the pre-download estimate
class PackBody(BaseModel):
name: str = "Offline area"
bbox: list[float] = Field(min_length=4, max_length=4) # [min_lon, min_lat, max_lon, max_lat]
min_zoom: int = Field(8, ge=0, le=16)
max_zoom: int = Field(14, ge=0, le=16)
layers: list[str] = Field(default_factory=lambda: ["base", "terrain"])
@router.post("/estimate")
def estimate(body: PackBody):
if body.max_zoom < body.min_zoom:
raise HTTPException(400, "max_zoom must be >= min_zoom")
count = estimate_tile_count(body.bbox, body.min_zoom, body.max_zoom) * len(body.layers)
return {"tile_count": count, "estimated_bytes": count * AVG_TILE_BYTES}
@router.post("")
def create_pack(body: PackBody):
if body.max_zoom < body.min_zoom:
raise HTTPException(400, "max_zoom must be >= min_zoom")
try:
return get_offline_maps().create_pack(
body.name, body.bbox, body.min_zoom, body.max_zoom, body.layers
)
except ValueError as e:
raise HTTPException(400, str(e))
@router.get("")
def list_packs():
return get_store().list_map_packs()
@router.get("/{pack_id}")
def get_pack(pack_id: str):
pack = get_store().get_map_pack(pack_id)
if pack is None:
raise HTTPException(404, "map pack not found")
return pack
@router.delete("/{pack_id}")
def delete_pack(pack_id: str):
if not get_offline_maps().delete_pack(pack_id):
raise HTTPException(404, "map pack not found")
return {"deleted": pack_id}
@router.get("/tiles/{layer}/{z}/{x}/{y}.png")
def serve_tile(layer: str, z: int, x: int, y: int):
"""Serve a tile from any ready pack (the UI's offline tile source)."""
path = get_offline_maps().find_tile(layer, z, x, y)
if path is None:
raise HTTPException(404, "tile not in any offline pack")
return FileResponse(path, media_type="image/png")
+37
View File
@@ -0,0 +1,37 @@
"""Sync API: manual trigger + bundle exchange endpoints (PLAN.md Phase 7)."""
from __future__ import annotations
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from app.config import settings
from app.deps import get_store
from app.sync.sync_daemon import build_bundle, merge_bundle, sync_with_peer
router = APIRouter(prefix="/api/sync", tags=["sync"])
@router.get("/bundle")
def get_bundle():
return build_bundle(get_store())
@router.post("/bundle")
def post_bundle(bundle: dict):
return {"applied": merge_bundle(get_store(), bundle)}
class SyncBody(BaseModel):
peer_url: str | None = None
@router.post("")
def trigger_sync(body: SyncBody | None = None):
peer = (body.peer_url if body else None) or settings.sync.peer_url
if not peer:
raise HTTPException(400, "no peer_url given and sync.peer_url not configured")
try:
return sync_with_peer(get_store(), peer)
except Exception as e:
raise HTTPException(502, f"sync with {peer} failed: {e}")
+83
View File
@@ -0,0 +1,83 @@
"""Trail guide API: scrape, PDF extraction (drafts), review/save, CRUD."""
from __future__ import annotations
from pathlib import Path
from fastapi import APIRouter, HTTPException, UploadFile
from pydantic import BaseModel
from pypdf import PdfReader
from app.config import settings
from app.deps import get_llm, get_store
from app.models.trail_guide import TrailGuide
from app.services.scraper import guide_from_extraction, scrape_trail_guide
router = APIRouter(prefix="/api/trails", tags=["trails"])
class ScrapeBody(BaseModel):
url: str
@router.post("/scrape")
def scrape(body: ScrapeBody) -> TrailGuide:
"""Returns a DRAFT guide for review; client saves it via POST /api/trails."""
try:
return scrape_trail_guide(body.url, get_llm())
except Exception as e:
raise HTTPException(502, f"scrape failed: {e}")
@router.post("/upload-pdf")
async def upload_pdf(file: UploadFile) -> TrailGuide:
"""PDF -> pypdf text -> LLM extraction -> DRAFT guide for review."""
if not (file.filename or "").lower().endswith(".pdf"):
raise HTTPException(400, "expected a .pdf file")
raw = await file.read()
pdf_dir = Path(settings.pdf_dir)
pdf_dir.mkdir(parents=True, exist_ok=True)
pdf_path = pdf_dir / Path(file.filename).name
pdf_path.write_bytes(raw)
try:
reader = PdfReader(str(pdf_path))
text = "\n".join((page.extract_text() or "") for page in reader.pages)
except Exception as e:
raise HTTPException(400, f"could not read PDF: {e}")
llm = get_llm()
extracted: dict = {}
if llm.configured and text.strip():
try:
extracted = llm.extract_trail_data(text)
except Exception:
pass # user reviews from raw text instead
return guide_from_extraction(
extracted, source="pdf", pdf_path=str(pdf_path),
raw_text=text[:50000], fallback_name=Path(file.filename).stem,
)
@router.post("")
def save_guide(guide: TrailGuide) -> TrailGuide:
"""Save a reviewed/edited guide (the manual-review confirmation step)."""
return get_store().save_trail_guide(guide)
@router.get("")
def list_guides():
return get_store().list_trail_guides()
@router.get("/{guide_id}")
def get_guide(guide_id: str) -> TrailGuide:
guide = get_store().get_trail_guide(guide_id)
if guide is None:
raise HTTPException(404, "trail guide not found")
return guide
@router.delete("/{guide_id}")
def delete_guide(guide_id: str):
if not get_store().delete_trail_guide(guide_id):
raise HTTPException(404, "trail guide not found")
return {"deleted": guide_id}
+98
View File
@@ -0,0 +1,98 @@
"""Route API: upload, list, get, delete, trail-guide linking, generators."""
from __future__ import annotations
from fastapi import APIRouter, HTTPException, UploadFile
from pydantic import BaseModel
from app.deps import get_elevation, get_store
from app.generators import GENERATORS, GeneratorError
from app.ingest.gpx_parser import parse_gpx
from app.ingest.segmenter import build_segments, compute_stats
router = APIRouter(prefix="/api/routes", tags=["routes"])
@router.post("/upload")
async def upload_gpx(file: UploadFile):
if not (file.filename or "").lower().endswith(".gpx"):
raise HTTPException(400, "expected a .gpx file")
raw = await file.read()
try:
route = parse_gpx(raw, filename=file.filename)
except Exception as e:
raise HTTPException(400, f"could not parse GPX: {e}")
if not route.points:
raise HTTPException(400, "GPX contains no track or route points")
# Fill elevations from terrain tiles when the exporting app omitted them.
if any(p.ele is None for p in route.points):
try:
if get_elevation().fill_missing_elevations(route.points):
route.segments = build_segments(route)
route.stats = compute_stats(route)
except Exception:
pass # offline or tiles unavailable; elevation stays absent
return get_store().save_route(route)
@router.get("")
def list_routes():
return [
{"id": r.id, "name": r.name, "source": r.source,
"trail_guide_id": r.trail_guide_id, "stats": r.stats,
"bounds": r.bounds(), "created_at": r.created_at}
for r in get_store().list_routes()
]
@router.get("/{route_id}")
def get_route(route_id: str):
route = get_store().get_route(route_id)
if route is None:
raise HTTPException(404, "route not found")
return route
@router.delete("/{route_id}")
def delete_route(route_id: str):
if not get_store().delete_route(route_id):
raise HTTPException(404, "route not found")
return {"deleted": route_id}
class LinkBody(BaseModel):
trail_guide_id: str | None = None
@router.put("/{route_id}/trail-guide")
def link_trail_guide(route_id: str, body: LinkBody):
try:
route = get_store().link_trail_guide(route_id, body.trail_guide_id)
except KeyError as e:
raise HTTPException(404, str(e))
if route is None:
raise HTTPException(404, "route not found")
return route
@router.post("/{route_id}/generate/{generator_name}")
def generate_asset(route_id: str, generator_name: str):
store = get_store()
route = store.get_route(route_id)
if route is None:
raise HTTPException(404, "route not found")
gen_cls = GENERATORS.get(generator_name)
if gen_cls is None:
raise HTTPException(404, f"unknown generator; available: {sorted(GENERATORS)}")
guide = store.get_trail_guide(route.trail_guide_id) if route.trail_guide_id else None
weather = store.get_weather(route_id)
try:
asset = gen_cls().generate(route, guide, weather)
except GeneratorError as e:
raise HTTPException(409, str(e))
return store.save_asset(asset)
@router.get("/{route_id}/assets")
def list_assets(route_id: str):
return get_store().list_assets(route_id)
+34
View File
@@ -0,0 +1,34 @@
"""Weather API: manual refresh + cached read (PLAN.md 4c: no auto-refetch)."""
from __future__ import annotations
from fastapi import APIRouter, HTTPException, Query
from app.deps import get_store
from app.services.weather import fetch_route_weather
router = APIRouter(prefix="/api/routes", tags=["weather"])
@router.post("/{route_id}/refresh-weather")
def refresh_weather(route_id: str, days: int = Query(7)):
store = get_store()
route = store.get_route(route_id)
if route is None:
raise HTTPException(404, "route not found")
if days not in (7, 10):
raise HTTPException(400, "days must be 7 or 10")
try:
weather = fetch_route_weather(route, days)
except Exception as e:
raise HTTPException(502, f"weather fetch failed: {e}")
store.save_weather(route_id, weather)
return store.get_weather(route_id)
@router.get("/{route_id}/weather")
def get_weather(route_id: str):
weather = get_store().get_weather(route_id)
if weather is None:
raise HTTPException(404, "no cached weather; refresh first")
return weather