Spaces:
Running on Zero
Running on Zero
Commit ·
decc879
1
Parent(s): 019f062
fix: added a dummy gradio ui component to resolve runtime errors at hf 0gu space
Browse filesFiles changed (3)
91 unmodified lines9293949596972 unmodified lines10010110210310410510610710810911011111211311411511611711827 unmodified lines14614714814915015191 unmodified linesreturn {"car": self.car_pct / 100, "bike": self.motorcycle_pct / 100,"auto": self.autorickshaw_pct / 100}def _run_job(job_id: str, req: SimulateRequest) -> None:jobs[job_id]["status"] = "running"2 unmodified linesif req.mode == "custom" and (req.total_vehicles or 0) > MAX_CUSTOM_VEHICLES:raise ValueError(f"total_vehicles capped at {MAX_CUSTOM_VEHICLES} for this demo")result = run_simulation(net_path=NET_PATH,sumo_config_dir=SUMO_CONFIG_DIR,checkpoint_path=CHECKPOINT_PATH,policy=req.policy,demand_mode=req.mode,total_vehicles=req.total_vehicles,period=req.period,mix=mix,n_runs=req.n_runs,deterministic=req.deterministic,seed=req.seed,)jobs[job_id] = {"status": "done", "result": result}except Exception as exc: # noqa: BLE001 — surface any failure to the clientjobs[job_id] = {"status": "error", "error": str(exc), "trace": traceback.format_exc()}27 unmodified linesdemo = gr.Blocks()with demo:gr.Markdown("BanTRel Backend API is running on ZeroGPU.")app = gr.mount_gradio_app(app, demo, path="/")91 unmodified lines92939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251262 unmodified lines12913013113213313413513613713813914014114214314414514614714814915015115215315427 unmodified lines18218318418518618718818919019191 unmodified linesreturn {"car": self.car_pct / 100, "bike": self.motorcycle_pct / 100,"auto": self.autorickshaw_pct / 100}# Adaptive GPU decoratortry:import spacesgpu_decorator = spaces.GPU(duration=120)except ImportError:def gpu_decorator(func):return func@gpu_decoratordef run_simulation_gpu_wrapper(req_json: str) -> str:import jsonreq_dict = json.loads(req_json)req = SimulateRequest(**req_dict)mix = req.resolve_mix()result = run_simulation(net_path=NET_PATH,sumo_config_dir=SUMO_CONFIG_DIR,checkpoint_path=CHECKPOINT_PATH,policy=req.policy,demand_mode=req.mode,total_vehicles=req.total_vehicles,period=req.period,mix=mix,n_runs=req.n_runs,deterministic=req.deterministic,seed=req.seed,)return json.dumps(result)def _run_job(job_id: str, req: SimulateRequest) -> None:jobs[job_id]["status"] = "running"2 unmodified linesif req.mode == "custom" and (req.total_vehicles or 0) > MAX_CUSTOM_VEHICLES:raise ValueError(f"total_vehicles capped at {MAX_CUSTOM_VEHICLES} for this demo")if os.environ.get("SPACE_ID"):from gradio_client import Clientimport jsonclient = Client("http://127.0.0.1:7860/")res_str = client.predict(req.model_dump_json(), api_name="/run_sim")result = json.loads(res_str)else:result = run_simulation(net_path=NET_PATH,sumo_config_dir=SUMO_CONFIG_DIR,checkpoint_path=CHECKPOINT_PATH,policy=req.policy,demand_mode=req.mode,total_vehicles=req.total_vehicles,period=req.period,mix=mix,n_runs=req.n_runs,deterministic=req.deterministic,seed=req.seed,)jobs[job_id] = {"status": "done", "result": result}except Exception as exc: # noqa: BLE001 — surface any failure to the clientjobs[job_id] = {"status": "error", "error": str(exc), "trace": traceback.format_exc()}27 unmodified linesdemo = gr.Blocks()with demo:gr.Markdown("BanTRel Backend API is running on ZeroGPU.")in_box = gr.Textbox(visible=False)out_box = gr.Textbox(visible=False)btn = gr.Button("Run", visible=False)btn.click(fn=run_simulation_gpu_wrapper, inputs=in_box, outputs=out_box, api_name="run_sim")app = gr.mount_gradio_app(app, demo, path="/")
5 unmodified lines6785 unmodified linessumolib==1.20.0huggingface_hub>=1.16.0,<3.0spaces5 unmodified lines67895 unmodified linessumolib==1.20.0huggingface_hub>=1.16.0,<3.0spacesgradio_client
13 unmodified lines1415161718192027 unmodified lines4849505152535413 unmodified linesimport torchimport torch.nn as nnfrom torch.distributions import Categoricalimport spacesDEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")27 unmodified linesif seed is not None:torch.manual_seed(seed)@spaces.GPUdef choose_action(self, state: np.ndarray) -> int:with torch.no_grad():tensor = torch.FloatTensor(state).unsqueeze(0).to(DEVICE)13 unmodified lines14151617181927 unmodified lines47484950515213 unmodified linesimport torchimport torch.nn as nnfrom torch.distributions import CategoricalDEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")27 unmodified linesif seed is not None:torch.manual_seed(seed)def choose_action(self, state: np.ndarray) -> int:with torch.no_grad():tensor = torch.FloatTensor(state).unsqueeze(0).to(DEVICE)
app.py+53-13
requirements.txt+1
simulation/model.py-2