joddabod commited on
Commit
3eedd34
·
verified ·
1 Parent(s): d1161ea

deploy bbuilder host

Browse files
Files changed (1) hide show
  1. app.py +35 -6
app.py CHANGED
@@ -309,7 +309,37 @@ with gr.Blocks(title="bbuilder host") as demo:
309
  "This dashboard is read-only."
310
  )
311
 
312
- app = gr.mount_gradio_app(app, demo, path="/")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
 
314
 
315
  if __name__ == "__main__":
@@ -317,8 +347,7 @@ if __name__ == "__main__":
317
  BOTS_DIR.mkdir(parents=True, exist_ok=True)
318
  threading.Thread(target=bootstrap, daemon=True).start()
319
  threading.Thread(target=self_ping, daemon=True).start()
320
- # Gradio Spaces expose the app on GRADIO_SERVER_PORT (7860) and route the public domain
321
- # there. Do NOT fall back to $PORT: HF sets it to something else in the container (7861,
322
- # already bound), so trusting it makes the app fail to start with EADDRINUSE.
323
- port = int(os.environ.get("GRADIO_SERVER_PORT") or 7860)
324
- uvicorn.run(app, host="0.0.0.0", port=port)
 
309
  "This dashboard is read-only."
310
  )
311
 
312
+ def serve_via_gradio() -> None:
313
+ """Let Gradio own the server, then graft our API routes onto its FastAPI app.
314
+
315
+ ZeroGPU only notices @spaces.GPU functions when the app starts through
316
+ demo.launch(); calling uvicorn.run() on our own app bypasses that hook and the Space is
317
+ killed with "No @spaces.GPU function detected during startup". So Gradio launches, and
318
+ we insert our routes at the *front* of its router afterwards — position matters because
319
+ Gradio registers a catch-all for SPA routing that would otherwise shadow /health.
320
+ """
321
+ demo.queue()
322
+ demo.launch(
323
+ server_name="0.0.0.0",
324
+ server_port=int(os.environ.get("GRADIO_SERVER_PORT") or 7860),
325
+ prevent_thread_lock=True,
326
+ show_api=False,
327
+ )
328
+ target = demo.app
329
+ for route in reversed(app.router.routes):
330
+ if getattr(route, "path", None) in ("/openapi.json",):
331
+ continue
332
+ target.router.routes.insert(0, route)
333
+ print(f"[boot] grafted {len(app.router.routes)} API routes onto the Gradio app", flush=True)
334
+
335
+ while True:
336
+ time.sleep(3600)
337
+
338
+
339
+ def serve_standalone() -> None:
340
+ """Local development: no ZeroGPU to appease, so run our own app directly."""
341
+ port = int(os.environ.get("GRADIO_SERVER_PORT") or os.environ.get("BB_PORT") or 7860)
342
+ uvicorn.run(gr.mount_gradio_app(app, demo, path="/"), host="0.0.0.0", port=port)
343
 
344
 
345
  if __name__ == "__main__":
 
347
  BOTS_DIR.mkdir(parents=True, exist_ok=True)
348
  threading.Thread(target=bootstrap, daemon=True).start()
349
  threading.Thread(target=self_ping, daemon=True).start()
350
+ if HAS_SPACES:
351
+ serve_via_gradio()
352
+ else:
353
+ serve_standalone()