Spaces:
Running on Zero
Running on Zero
Commit ·
ba7017f
1
Parent(s): 879edd2
fix: replaced the old demo decorator with new one
Browse files- app.py +132 -93
- download_checkpoint.py +35 -14
- runner.py +1 -1
app.py
CHANGED
|
@@ -1,73 +1,117 @@
|
|
| 1 |
"""
|
| 2 |
-
FastAPI backend for the BanTRel web demo
|
|
|
|
| 3 |
|
| 4 |
Flow: POST /simulate returns a job_id immediately; the actual SUMO run
|
| 5 |
-
happens in a background task (
|
| 6 |
-
|
| 7 |
GET /simulate/{job_id} until status == "done" or "error".
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
"""
|
| 9 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
import traceback
|
| 12 |
import uuid
|
| 13 |
from typing import Literal, Optional
|
| 14 |
|
|
|
|
| 15 |
from fastapi import BackgroundTasks, FastAPI, HTTPException
|
| 16 |
from fastapi.middleware.cors import CORSMiddleware
|
| 17 |
from pydantic import BaseModel, field_validator
|
| 18 |
|
| 19 |
-
|
| 20 |
-
import spaces
|
| 21 |
-
except ImportError:
|
| 22 |
-
class DummySpaces:
|
| 23 |
-
def GPU(self, duration=None, *args, **kwargs):
|
| 24 |
-
def decorator(func):
|
| 25 |
-
return func
|
| 26 |
-
return decorator
|
| 27 |
-
spaces = DummySpaces()
|
| 28 |
-
|
| 29 |
from simulation.runner import run_simulation
|
| 30 |
|
| 31 |
-
BASE_DIR = os.path.dirname(__file__)
|
| 32 |
SUMO_CONFIG_DIR = os.path.join(BASE_DIR, "sumo_config")
|
| 33 |
NET_PATH = os.path.join(SUMO_CONFIG_DIR, "intersection.net.xml")
|
| 34 |
-
# Prefer an env var so you can swap checkpoints without a code change
|
| 35 |
-
# point at a path where you've downloaded the HF model file at build time.
|
| 36 |
CHECKPOINT_PATH = os.environ.get(
|
| 37 |
"BANTREL_CHECKPOINT", os.path.join(BASE_DIR, "model_files", "ppo_bangalore.pt")
|
| 38 |
)
|
| 39 |
|
| 40 |
-
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
| 44 |
if not os.path.exists(NET_PATH):
|
| 45 |
try:
|
| 46 |
os.makedirs(SUMO_CONFIG_DIR, exist_ok=True)
|
| 47 |
-
# Atomic lock creation prevents multiple workers from building concurrently
|
| 48 |
-
fd = os.open(LOCK_PATH, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
|
| 49 |
-
os.close(fd)
|
| 50 |
print("Building SUMO network...")
|
| 51 |
-
subprocess.run(
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
| 60 |
|
| 61 |
-
app = FastAPI(title="BanTRel Simulation API")
|
| 62 |
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
CORSMiddleware,
|
|
|
|
|
|
|
| 65 |
allow_origins=os.environ.get("BANTREL_CORS_ORIGINS", "*").split(","),
|
| 66 |
allow_methods=["*"],
|
| 67 |
allow_headers=["*"],
|
| 68 |
)
|
| 69 |
|
| 70 |
-
jobs: dict[str, dict] = {} # in-memory job store
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
|
| 73 |
class SimulateRequest(BaseModel):
|
|
@@ -103,42 +147,31 @@ class SimulateRequest(BaseModel):
|
|
| 103 |
"auto": self.autorickshaw_pct / 100}
|
| 104 |
|
| 105 |
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
n_runs=req.n_runs,
|
| 122 |
-
deterministic=req.deterministic,
|
| 123 |
-
seed=req.seed,
|
| 124 |
-
)
|
| 125 |
-
return json.dumps(result)
|
| 126 |
|
| 127 |
|
| 128 |
def _run_job(job_id: str, req: SimulateRequest) -> None:
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
from gradio_client import Client
|
| 137 |
-
import json
|
| 138 |
-
client = Client("http://127.0.0.1:7860/")
|
| 139 |
-
res_str = client.predict(req.model_dump_json(), api_name="/run_sim")
|
| 140 |
-
result = json.loads(res_str)
|
| 141 |
-
else:
|
| 142 |
result = run_simulation(
|
| 143 |
net_path=NET_PATH,
|
| 144 |
sumo_config_dir=SUMO_CONFIG_DIR,
|
|
@@ -152,28 +185,36 @@ def _run_job(job_id: str, req: SimulateRequest) -> None:
|
|
| 152 |
deterministic=req.deterministic,
|
| 153 |
seed=req.seed,
|
| 154 |
)
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
|
| 159 |
|
| 160 |
-
@
|
| 161 |
async def start_simulation(req: SimulateRequest, background_tasks: BackgroundTasks):
|
| 162 |
-
|
| 163 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
background_tasks.add_task(_run_job, job_id, req)
|
| 165 |
return {"job_id": job_id}
|
| 166 |
|
| 167 |
|
| 168 |
-
@
|
| 169 |
async def get_status(job_id: str):
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
|
|
|
| 174 |
|
| 175 |
|
| 176 |
-
@
|
| 177 |
async def health():
|
| 178 |
return {
|
| 179 |
"status": "ok",
|
|
@@ -181,20 +222,18 @@ async def health():
|
|
| 181 |
"checkpoint_found": os.path.exists(CHECKPOINT_PATH),
|
| 182 |
}
|
| 183 |
|
| 184 |
-
import gradio as gr
|
| 185 |
-
demo = gr.Blocks()
|
| 186 |
-
with demo:
|
| 187 |
-
gr.Markdown("BanTRel Backend API is running on ZeroGPU.")
|
| 188 |
-
in_box = gr.Textbox(visible=False)
|
| 189 |
-
out_box = gr.Textbox(visible=False)
|
| 190 |
-
btn = gr.Button("Run", visible=False)
|
| 191 |
-
btn.click(fn=run_simulation_gpu_wrapper, inputs=in_box, outputs=out_box, api_name="run_sim")
|
| 192 |
|
| 193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
|
|
|
| 1 |
"""
|
| 2 |
+
FastAPI backend for the BanTRel web demo, served from a Hugging Face Gradio
|
| 3 |
+
Space running on ZeroGPU.
|
| 4 |
|
| 5 |
Flow: POST /simulate returns a job_id immediately; the actual SUMO run
|
| 6 |
+
happens in a background task (anywhere from a few seconds to ~1-2 min
|
| 7 |
+
depending on n_runs and demand size). The frontend polls
|
| 8 |
GET /simulate/{job_id} until status == "done" or "error".
|
| 9 |
+
|
| 10 |
+
ZeroGPU notes
|
| 11 |
+
-------------
|
| 12 |
+
* ZeroGPU refuses to start a Space with no @spaces.GPU function, so a tiny
|
| 13 |
+
never-called function is declared below purely to satisfy that check.
|
| 14 |
+
* The simulation itself (SUMO + a small PPO policy) is CPU work and runs
|
| 15 |
+
directly in the background task. It is deliberately NOT wrapped in
|
| 16 |
+
@spaces.GPU, so it does not consume GPU quota.
|
| 17 |
+
* On a Gradio SDK Space the platform runs `python app.py`, so this file must
|
| 18 |
+
start the server itself (see the uvicorn.run call at the bottom).
|
| 19 |
"""
|
| 20 |
|
| 21 |
+
# `spaces` must be imported before torch (which simulation/ imports below).
|
| 22 |
+
try:
|
| 23 |
+
import spaces
|
| 24 |
+
except ImportError: # local development without the `spaces` package
|
| 25 |
+
class _NoSpaces:
|
| 26 |
+
@staticmethod
|
| 27 |
+
def GPU(*args, **kwargs):
|
| 28 |
+
if args and callable(args[0]) and not kwargs:
|
| 29 |
+
return args[0]
|
| 30 |
+
|
| 31 |
+
def decorator(func):
|
| 32 |
+
return func
|
| 33 |
+
|
| 34 |
+
return decorator
|
| 35 |
+
|
| 36 |
+
spaces = _NoSpaces()
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@spaces.GPU(duration=1)
|
| 40 |
+
def _zerogpu_keepalive() -> None:
|
| 41 |
+
"""Never called. Only satisfies ZeroGPU's startup check."""
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
|
| 45 |
import os
|
| 46 |
+
import subprocess
|
| 47 |
+
import sys
|
| 48 |
+
import threading
|
| 49 |
+
import time
|
| 50 |
import traceback
|
| 51 |
import uuid
|
| 52 |
from typing import Literal, Optional
|
| 53 |
|
| 54 |
+
import gradio as gr
|
| 55 |
from fastapi import BackgroundTasks, FastAPI, HTTPException
|
| 56 |
from fastapi.middleware.cors import CORSMiddleware
|
| 57 |
from pydantic import BaseModel, field_validator
|
| 58 |
|
| 59 |
+
from download_checkpoint import ensure_checkpoint
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
from simulation.runner import run_simulation
|
| 61 |
|
| 62 |
+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 63 |
SUMO_CONFIG_DIR = os.path.join(BASE_DIR, "sumo_config")
|
| 64 |
NET_PATH = os.path.join(SUMO_CONFIG_DIR, "intersection.net.xml")
|
| 65 |
+
# Prefer an env var so you can swap checkpoints without a code change.
|
|
|
|
| 66 |
CHECKPOINT_PATH = os.environ.get(
|
| 67 |
"BANTREL_CHECKPOINT", os.path.join(BASE_DIR, "model_files", "ppo_bangalore.pt")
|
| 68 |
)
|
| 69 |
|
| 70 |
+
MAX_N_RUNS = 3
|
| 71 |
+
MAX_CUSTOM_VEHICLES = 60_000 # ~3.7x the default day, generous headroom before state clipping dominates
|
| 72 |
+
MAX_PENDING_JOBS = 4 # queued + running; beyond this POST /simulate returns 429
|
| 73 |
+
JOB_TTL_SECONDS = 30 * 60 # finished jobs are discarded after this long
|
| 74 |
+
|
| 75 |
|
| 76 |
+
# --------------------------------------------------------------------------
|
| 77 |
+
# Startup: build the SUMO network and fetch the checkpoint if missing.
|
| 78 |
+
# Failures are printed but do not stop the server, so /health can report them.
|
| 79 |
+
# --------------------------------------------------------------------------
|
| 80 |
if not os.path.exists(NET_PATH):
|
| 81 |
try:
|
| 82 |
os.makedirs(SUMO_CONFIG_DIR, exist_ok=True)
|
|
|
|
|
|
|
|
|
|
| 83 |
print("Building SUMO network...")
|
| 84 |
+
subprocess.run(
|
| 85 |
+
[sys.executable, os.path.join(BASE_DIR, "simulation", "build_network.py")],
|
| 86 |
+
check=True,
|
| 87 |
+
)
|
| 88 |
+
except Exception: # noqa: BLE001
|
| 89 |
+
traceback.print_exc()
|
| 90 |
|
| 91 |
+
try:
|
| 92 |
+
ensure_checkpoint(CHECKPOINT_PATH)
|
| 93 |
+
except Exception: # noqa: BLE001
|
| 94 |
+
traceback.print_exc()
|
| 95 |
|
|
|
|
| 96 |
|
| 97 |
+
# --------------------------------------------------------------------------
|
| 98 |
+
# API
|
| 99 |
+
# --------------------------------------------------------------------------
|
| 100 |
+
api = FastAPI(title="BanTRel Simulation API")
|
| 101 |
+
|
| 102 |
+
api.add_middleware(
|
| 103 |
CORSMiddleware,
|
| 104 |
+
# Set BANTREL_CORS_ORIGINS=https://bantrel.becore.space in the Space
|
| 105 |
+
# variables to lock this down; "*" is fine for a public demo.
|
| 106 |
allow_origins=os.environ.get("BANTREL_CORS_ORIGINS", "*").split(","),
|
| 107 |
allow_methods=["*"],
|
| 108 |
allow_headers=["*"],
|
| 109 |
)
|
| 110 |
|
| 111 |
+
jobs: dict[str, dict] = {} # in-memory job store; lost on restart
|
| 112 |
+
_jobs_lock = threading.Lock()
|
| 113 |
+
# SUMO/TraCI runs share process-level state, so run one simulation at a time.
|
| 114 |
+
_SIM_SLOT = threading.Semaphore(1)
|
| 115 |
|
| 116 |
|
| 117 |
class SimulateRequest(BaseModel):
|
|
|
|
| 147 |
"auto": self.autorickshaw_pct / 100}
|
| 148 |
|
| 149 |
|
| 150 |
+
def _set_job(job_id: str, **fields) -> None:
|
| 151 |
+
with _jobs_lock:
|
| 152 |
+
jobs[job_id].update(fields)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _purge_old_jobs() -> None:
|
| 156 |
+
now = time.time()
|
| 157 |
+
with _jobs_lock:
|
| 158 |
+
stale = [
|
| 159 |
+
job_id for job_id, job in jobs.items()
|
| 160 |
+
if job["status"] in ("done", "error")
|
| 161 |
+
and now - job.get("created", now) > JOB_TTL_SECONDS
|
| 162 |
+
]
|
| 163 |
+
for job_id in stale:
|
| 164 |
+
del jobs[job_id]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 165 |
|
| 166 |
|
| 167 |
def _run_job(job_id: str, req: SimulateRequest) -> None:
|
| 168 |
+
with _SIM_SLOT:
|
| 169 |
+
_set_job(job_id, status="running")
|
| 170 |
+
try:
|
| 171 |
+
mix = req.resolve_mix()
|
| 172 |
+
if req.mode == "custom" and (req.total_vehicles or 0) > MAX_CUSTOM_VEHICLES:
|
| 173 |
+
raise ValueError(f"total_vehicles capped at {MAX_CUSTOM_VEHICLES} for this demo")
|
| 174 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
result = run_simulation(
|
| 176 |
net_path=NET_PATH,
|
| 177 |
sumo_config_dir=SUMO_CONFIG_DIR,
|
|
|
|
| 185 |
deterministic=req.deterministic,
|
| 186 |
seed=req.seed,
|
| 187 |
)
|
| 188 |
+
_set_job(job_id, status="done", result=result)
|
| 189 |
+
except Exception as exc: # noqa: BLE001 - surface any failure to the client
|
| 190 |
+
_set_job(job_id, status="error", error=str(exc), trace=traceback.format_exc())
|
| 191 |
|
| 192 |
|
| 193 |
+
@api.post("/simulate")
|
| 194 |
async def start_simulation(req: SimulateRequest, background_tasks: BackgroundTasks):
|
| 195 |
+
_purge_old_jobs()
|
| 196 |
+
with _jobs_lock:
|
| 197 |
+
pending = sum(1 for j in jobs.values() if j["status"] in ("queued", "running"))
|
| 198 |
+
if pending >= MAX_PENDING_JOBS:
|
| 199 |
+
raise HTTPException(
|
| 200 |
+
status_code=429, detail="Server is busy, please try again shortly"
|
| 201 |
+
)
|
| 202 |
+
job_id = str(uuid.uuid4())
|
| 203 |
+
jobs[job_id] = {"status": "queued", "created": time.time()}
|
| 204 |
background_tasks.add_task(_run_job, job_id, req)
|
| 205 |
return {"job_id": job_id}
|
| 206 |
|
| 207 |
|
| 208 |
+
@api.get("/simulate/{job_id}")
|
| 209 |
async def get_status(job_id: str):
|
| 210 |
+
with _jobs_lock:
|
| 211 |
+
job = jobs.get(job_id)
|
| 212 |
+
if job is None:
|
| 213 |
+
raise HTTPException(status_code=404, detail="job not found")
|
| 214 |
+
return {k: v for k, v in job.items() if k != "created"}
|
| 215 |
|
| 216 |
|
| 217 |
+
@api.get("/health")
|
| 218 |
async def health():
|
| 219 |
return {
|
| 220 |
"status": "ok",
|
|
|
|
| 222 |
"checkpoint_found": os.path.exists(CHECKPOINT_PATH),
|
| 223 |
}
|
| 224 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
|
| 226 |
+
# --------------------------------------------------------------------------
|
| 227 |
+
# Gradio shell (required for a Gradio SDK / ZeroGPU Space) + server start
|
| 228 |
+
# --------------------------------------------------------------------------
|
| 229 |
+
with gr.Blocks(title="BanTRel Backend") as demo:
|
| 230 |
+
gr.Markdown("BanTRel backend API is running. See `/health` and `/docs`.")
|
| 231 |
+
# Wires the keepalive function into Gradio so it is visible to ZeroGPU.
|
| 232 |
+
gr.Button("keepalive", visible=False).click(_zerogpu_keepalive, api_name=False)
|
| 233 |
|
| 234 |
+
app = gr.mount_gradio_app(api, demo, path="/", ssr_mode=False)
|
| 235 |
+
|
| 236 |
+
if __name__ == "__main__":
|
| 237 |
+
import uvicorn
|
| 238 |
+
|
| 239 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
download_checkpoint.py
CHANGED
|
@@ -1,28 +1,49 @@
|
|
| 1 |
"""
|
| 2 |
-
Downloads the
|
| 3 |
-
|
| 4 |
-
directly into the Space's git repo (keeps the repo small, and lets you
|
| 5 |
-
swap in a new checkpoint by just re-running this).
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
| 9 |
"""
|
| 10 |
|
| 11 |
import os
|
|
|
|
| 12 |
|
| 13 |
from huggingface_hub import hf_hub_download
|
| 14 |
|
| 15 |
REPO_ID = "BJyotibrat/BanTRel-v1.0.0"
|
| 16 |
-
#
|
| 17 |
-
FILENAME =
|
| 18 |
-
|
|
|
|
| 19 |
|
| 20 |
-
|
| 21 |
-
os.
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
repo_id=REPO_ID,
|
| 24 |
filename=FILENAME,
|
| 25 |
-
local_dir=OUT_DIR,
|
| 26 |
token=os.environ.get("HF_TOKEN"),
|
| 27 |
)
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
Downloads the PPO checkpoint from the HF Hub model repo into model_files/,
|
| 3 |
+
so the weights don't need to be committed into the Space's git repo.
|
|
|
|
|
|
|
| 4 |
|
| 5 |
+
Used two ways:
|
| 6 |
+
* imported by app.py, which calls ensure_checkpoint() at startup
|
| 7 |
+
* run by hand: python download_checkpoint.py
|
| 8 |
+
|
| 9 |
+
Requires the HF_TOKEN env var only if the model repo is private.
|
| 10 |
"""
|
| 11 |
|
| 12 |
import os
|
| 13 |
+
import shutil
|
| 14 |
|
| 15 |
from huggingface_hub import hf_hub_download
|
| 16 |
|
| 17 |
REPO_ID = "BJyotibrat/BanTRel-v1.0.0"
|
| 18 |
+
# Path of the file inside the model repo (note the subfolders and spaces).
|
| 19 |
+
FILENAME = os.environ.get(
|
| 20 |
+
"BANTREL_CHECKPOINT_FILE", "Model/Phase 2/PyTorch Model/ppo_bangalore.pt"
|
| 21 |
+
)
|
| 22 |
|
| 23 |
+
DEFAULT_DEST = os.path.join(
|
| 24 |
+
os.path.dirname(os.path.abspath(__file__)), "model_files", "ppo_bangalore.pt"
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def ensure_checkpoint(dest_path: str = DEFAULT_DEST) -> str:
|
| 29 |
+
"""Make sure the checkpoint exists at dest_path and return that path.
|
| 30 |
+
|
| 31 |
+
hf_hub_download keeps the repo's folder structure when local_dir is used,
|
| 32 |
+
so the file is fetched into the normal HF cache and then copied to a flat,
|
| 33 |
+
predictable location.
|
| 34 |
+
"""
|
| 35 |
+
if os.path.exists(dest_path):
|
| 36 |
+
return dest_path
|
| 37 |
+
|
| 38 |
+
cached_path = hf_hub_download(
|
| 39 |
repo_id=REPO_ID,
|
| 40 |
filename=FILENAME,
|
|
|
|
| 41 |
token=os.environ.get("HF_TOKEN"),
|
| 42 |
)
|
| 43 |
+
os.makedirs(os.path.dirname(dest_path), exist_ok=True)
|
| 44 |
+
shutil.copyfile(cached_path, dest_path)
|
| 45 |
+
return dest_path
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
if __name__ == "__main__":
|
| 49 |
+
print(f"Checkpoint ready at: {ensure_checkpoint()}")
|
runner.py
CHANGED
|
@@ -151,4 +151,4 @@ def run_simulation(
|
|
| 151 |
|
| 152 |
return result
|
| 153 |
finally:
|
| 154 |
-
shutil.rmtree(run_dir, ignore_errors=True)
|
|
|
|
| 151 |
|
| 152 |
return result
|
| 153 |
finally:
|
| 154 |
+
shutil.rmtree(run_dir, ignore_errors=True)
|