import json import uuid from pathlib import Path import gradio as gr from fastapi import FastAPI, Request, Response from fastapi.middleware.cors import CORSMiddleware from starlette.staticfiles import StaticFiles DATA_FILE = Path("data/bike_paths.geojson") def normalize_feature(f: dict): props = f.setdefault("properties", {}) if not props.get("STATO"): props["STATO"] = "satisfactory" if not props.get("_fid"): props["_fid"] = uuid.uuid4().hex def load_geojson() -> dict: if DATA_FILE.exists(): try: obj = json.loads(DATA_FILE.read_text(encoding="utf-8")) if obj.get("type") == "FeatureCollection": for feat in obj.get("features", []): normalize_feature(feat) return obj except Exception: pass return {"type": "FeatureCollection", "features": []} # ---------- FastAPI ---------- fastapi_app = FastAPI() fastapi_app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @fastapi_app.get("/_load_geojson") async def _load_geojson(): return load_geojson() @fastapi_app.post("/_save_geojson") async def _save_geojson(request: Request): try: payload = await request.json() if not isinstance(payload, dict) or payload.get("type") != "FeatureCollection": return Response("Invalid GeoJSON (expect FeatureCollection)", status_code=400) for f in payload.get("features", []): normalize_feature(f) DATA_FILE.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8") return Response("OK", status_code=200) except Exception as e: return Response(f"Error: {e}", status_code=500) # Serve /static for the HTML/JS/CSS fastapi_app.mount("/static", StaticFiles(directory="static"), name="static") # ---------- Gradio shell (just an iframe) ---------- def demo_app(): with gr.Blocks(title="Bike Paths Editor", fill_height=True) as demo: gr.HTML( """ """, show_label=False, ) return demo demo = demo_app() app = gr.mount_gradio_app(fastapi_app, demo, path="/") if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)