BJyotibrat commited on
Commit
decc879
·
1 Parent(s): 019f062

fix: added a dummy gradio ui component to resolve runtime errors at hf 0gu space

Browse files
Files changed (3) hide show
  1. app.py +53 -13
  2. requirements.txt +1 -0
  3. simulation/model.py +0 -2
app.py CHANGED
@@ -92,6 +92,35 @@ class SimulateRequest(BaseModel):
92
  return {"car": self.car_pct / 100, "bike": self.motorcycle_pct / 100,
93
  "auto": self.autorickshaw_pct / 100}
94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
96
  def _run_job(job_id: str, req: SimulateRequest) -> None:
97
  jobs[job_id]["status"] = "running"
@@ -100,19 +129,26 @@ def _run_job(job_id: str, req: SimulateRequest) -> None:
100
  if req.mode == "custom" and (req.total_vehicles or 0) > MAX_CUSTOM_VEHICLES:
101
  raise ValueError(f"total_vehicles capped at {MAX_CUSTOM_VEHICLES} for this demo")
102
 
103
- result = run_simulation(
104
- net_path=NET_PATH,
105
- sumo_config_dir=SUMO_CONFIG_DIR,
106
- checkpoint_path=CHECKPOINT_PATH,
107
- policy=req.policy,
108
- demand_mode=req.mode,
109
- total_vehicles=req.total_vehicles,
110
- period=req.period,
111
- mix=mix,
112
- n_runs=req.n_runs,
113
- deterministic=req.deterministic,
114
- seed=req.seed,
115
- )
 
 
 
 
 
 
 
116
  jobs[job_id] = {"status": "done", "result": result}
117
  except Exception as exc: # noqa: BLE001 — surface any failure to the client
118
  jobs[job_id] = {"status": "error", "error": str(exc), "trace": traceback.format_exc()}
@@ -146,6 +182,10 @@ import gradio as gr
146
  demo = gr.Blocks()
147
  with demo:
148
  gr.Markdown("BanTRel Backend API is running on ZeroGPU.")
 
 
 
 
149
 
150
  app = gr.mount_gradio_app(app, demo, path="/")
151
 
 
92
  return {"car": self.car_pct / 100, "bike": self.motorcycle_pct / 100,
93
  "auto": self.autorickshaw_pct / 100}
94
 
95
+ # Adaptive GPU decorator
96
+ try:
97
+ import spaces
98
+ gpu_decorator = spaces.GPU(duration=120)
99
+ except ImportError:
100
+ def gpu_decorator(func):
101
+ return func
102
+
103
+ @gpu_decorator
104
+ def run_simulation_gpu_wrapper(req_json: str) -> str:
105
+ import json
106
+ req_dict = json.loads(req_json)
107
+ req = SimulateRequest(**req_dict)
108
+ mix = req.resolve_mix()
109
+ result = run_simulation(
110
+ net_path=NET_PATH,
111
+ sumo_config_dir=SUMO_CONFIG_DIR,
112
+ checkpoint_path=CHECKPOINT_PATH,
113
+ policy=req.policy,
114
+ demand_mode=req.mode,
115
+ total_vehicles=req.total_vehicles,
116
+ period=req.period,
117
+ mix=mix,
118
+ n_runs=req.n_runs,
119
+ deterministic=req.deterministic,
120
+ seed=req.seed,
121
+ )
122
+ return json.dumps(result)
123
+
124
 
125
  def _run_job(job_id: str, req: SimulateRequest) -> None:
126
  jobs[job_id]["status"] = "running"
 
129
  if req.mode == "custom" and (req.total_vehicles or 0) > MAX_CUSTOM_VEHICLES:
130
  raise ValueError(f"total_vehicles capped at {MAX_CUSTOM_VEHICLES} for this demo")
131
 
132
+ if os.environ.get("SPACE_ID"):
133
+ from gradio_client import Client
134
+ import json
135
+ client = Client("http://127.0.0.1:7860/")
136
+ res_str = client.predict(req.model_dump_json(), api_name="/run_sim")
137
+ result = json.loads(res_str)
138
+ else:
139
+ result = run_simulation(
140
+ net_path=NET_PATH,
141
+ sumo_config_dir=SUMO_CONFIG_DIR,
142
+ checkpoint_path=CHECKPOINT_PATH,
143
+ policy=req.policy,
144
+ demand_mode=req.mode,
145
+ total_vehicles=req.total_vehicles,
146
+ period=req.period,
147
+ mix=mix,
148
+ n_runs=req.n_runs,
149
+ deterministic=req.deterministic,
150
+ seed=req.seed,
151
+ )
152
  jobs[job_id] = {"status": "done", "result": result}
153
  except Exception as exc: # noqa: BLE001 — surface any failure to the client
154
  jobs[job_id] = {"status": "error", "error": str(exc), "trace": traceback.format_exc()}
 
182
  demo = gr.Blocks()
183
  with demo:
184
  gr.Markdown("BanTRel Backend API is running on ZeroGPU.")
185
+ in_box = gr.Textbox(visible=False)
186
+ out_box = gr.Textbox(visible=False)
187
+ btn = gr.Button("Run", visible=False)
188
+ btn.click(fn=run_simulation_gpu_wrapper, inputs=in_box, outputs=out_box, api_name="run_sim")
189
 
190
  app = gr.mount_gradio_app(app, demo, path="/")
191
 
requirements.txt CHANGED
@@ -6,3 +6,4 @@ traci==1.20.0
6
  sumolib==1.20.0
7
  huggingface_hub>=1.16.0,<3.0
8
  spaces
 
 
6
  sumolib==1.20.0
7
  huggingface_hub>=1.16.0,<3.0
8
  spaces
9
+ gradio_client
simulation/model.py CHANGED
@@ -14,7 +14,6 @@ import numpy as np
14
  import torch
15
  import torch.nn as nn
16
  from torch.distributions import Categorical
17
- import spaces
18
 
19
  DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
20
 
@@ -48,7 +47,6 @@ class PPOPolicy:
48
  if seed is not None:
49
  torch.manual_seed(seed)
50
 
51
- @spaces.GPU
52
  def choose_action(self, state: np.ndarray) -> int:
53
  with torch.no_grad():
54
  tensor = torch.FloatTensor(state).unsqueeze(0).to(DEVICE)
 
14
  import torch
15
  import torch.nn as nn
16
  from torch.distributions import Categorical
 
17
 
18
  DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
19
 
 
47
  if seed is not None:
48
  torch.manual_seed(seed)
49
 
 
50
  def choose_action(self, state: np.ndarray) -> int:
51
  with torch.no_grad():
52
  tensor = torch.FloatTensor(state).unsqueeze(0).to(DEVICE)