Spaces:
Running
Running
Download app.py from vikba/Bike_Paths_Palermo: direct link, hf CLI and curl.
- Browser
- Download file 2.51 kB
-
https://huggingface.co/spaces/vikba/Bike_Paths_Palermo/resolve/main/app.py
- Command line
-
hf download hf://spaces/vikba/Bike_Paths_Palermo/app.py
-
curl -L -o app.py https://huggingface.co/spaces/vikba/Bike_Paths_Palermo/resolve/main/app.py
2.51 kB
| 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=["*"], | |
| ) | |
| async def _load_geojson(): | |
| return load_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( | |
| """ | |
| <iframe src="/static/map.html" | |
| style="width:100%;height:720px;border:0;border-radius:8px" | |
| referrerpolicy="no-referrer"></iframe> | |
| """, | |
| 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) | |