HFShishir commited on
Commit
46a2bd6
·
verified ·
1 Parent(s): 03ef987

Mount backend app under /api/v1 prefix to bypass Gradio ASGI

Browse files
Files changed (1) hide show
  1. gradio_app.py +12 -16
gradio_app.py CHANGED
@@ -35,7 +35,7 @@ async def lifespan(app: FastAPI):
35
  yield
36
  stop_scheduler()
37
 
38
- # Initialize unified backend FastAPI app
39
  backend_app = FastAPI(
40
  title=settings.APP_NAME,
41
  version=settings.VERSION,
@@ -51,6 +51,7 @@ backend_app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handle
51
  @backend_app.middleware("http")
52
  async def app_secret_security_middleware(request: Request, call_next):
53
  path = request.url.path
 
54
  if path in ["/", "/health", "/docs", "/openapi.json", "/redoc"]:
55
  return await call_next(request)
56
 
@@ -88,14 +89,14 @@ backend_app.add_middleware(
88
  allow_headers=["*"],
89
  )
90
 
91
- # Custom /health endpoint on backend app
92
  @backend_app.get("/health")
93
  @limiter.limit("60/minute")
94
  def health_check(request: Request):
95
  return {"status": "healthy", "service": settings.APP_NAME, "security": "rate_limited_enabled"}
96
 
97
- # Include API v1 Router on backend app
98
- backend_app.include_router(api_router, prefix="/api/v1")
99
 
100
  # Dummy function decorated with GPU to satisfy Hugging Face ZeroGPU requirement
101
  @spaces.GPU
@@ -112,30 +113,25 @@ with gr.Blocks(title="BytePulse AI Backend", theme=gr.themes.Soft()) as demo:
112
 
113
  | Endpoint | Description |
114
  |----------|-------------|
115
- | [`/health`](./health) | Health check |
116
- | [`/docs`](./docs) | Swagger API Docs |
117
- | [`/api/v1`](./api/v1) | API Base |
118
  """
119
  )
120
  btn = gr.Button("Warm Up ZeroGPU")
121
  out = gr.Textbox()
122
  btn.click(fn=dummy_gpu_func, inputs=out, outputs=out)
123
 
124
- # Mount our custom backend app inside Gradio's internal FastAPI app at root '/'
125
- # Wait! Since Gradio mounts its catch-all routes directly on the root level, we can prepend the custom mounted routes list.
126
- # We mount our backend_app on demo.app at '/' which merges them!
127
- # To do this correctly, we can mount backend_app at '/' and then prepend the newly added mount route in demo.app.router.routes!
128
  pre_insertion_route_count = len(demo.app.router.routes)
129
 
130
- # Mount backend sub-app on demo.app
131
- demo.app.mount("/", backend_app)
132
 
133
- # Prepend the newly added mount route to the beginning of demo.app's routing list
134
- # This guarantees that FastAPI matches our mounted '/health' and '/api/v1/...' BEFORE Gradio's catch-all wildcard.
135
  new_route_count = len(demo.app.router.routes) - pre_insertion_route_count
136
  if new_route_count > 0:
137
  demo.app.router.routes = demo.app.router.routes[-new_route_count:] + demo.app.router.routes[:-new_route_count]
138
- logger.info("Successfully prepended custom FastAPI sub-app mount route in Gradio router.")
139
 
140
  # Launch the Gradio app blocks directly (Gradio reads port 7860 from env and starts the server)
141
  demo.launch()
 
35
  yield
36
  stop_scheduler()
37
 
38
+ # Initialize custom FastAPI backend app (no prefix in sub-router)
39
  backend_app = FastAPI(
40
  title=settings.APP_NAME,
41
  version=settings.VERSION,
 
51
  @backend_app.middleware("http")
52
  async def app_secret_security_middleware(request: Request, call_next):
53
  path = request.url.path
54
+ # Since backend_app is mounted at '/api/v1', request.url.path here will be relative (e.g. '/health', '/digest/digests')
55
  if path in ["/", "/health", "/docs", "/openapi.json", "/redoc"]:
56
  return await call_next(request)
57
 
 
89
  allow_headers=["*"],
90
  )
91
 
92
+ # Health endpoint (relative to mount path, will map to /api/v1/health)
93
  @backend_app.get("/health")
94
  @limiter.limit("60/minute")
95
  def health_check(request: Request):
96
  return {"status": "healthy", "service": settings.APP_NAME, "security": "rate_limited_enabled"}
97
 
98
+ # Include API Router directly (routes like /digest/digests will map to /api/v1/digest/digests)
99
+ backend_app.include_router(api_router)
100
 
101
  # Dummy function decorated with GPU to satisfy Hugging Face ZeroGPU requirement
102
  @spaces.GPU
 
113
 
114
  | Endpoint | Description |
115
  |----------|-------------|
116
+ | [`/api/v1/health`](./api/v1/health) | Health check |
117
+ | [`/api/v1/docs`](./api/v1/docs) | Swagger API Docs |
 
118
  """
119
  )
120
  btn = gr.Button("Warm Up ZeroGPU")
121
  out = gr.Textbox()
122
  btn.click(fn=dummy_gpu_func, inputs=out, outputs=out)
123
 
124
+ # Mount our custom backend app inside Gradio's internal FastAPI app under '/api/v1' path
125
+ # Gradio's ASGI middleware bypasses all paths starting with '/api' to prevent returning HTML UI.
126
+ # Prepending the mount route ensures FastAPI processes it prior to Gradio wildcards.
 
127
  pre_insertion_route_count = len(demo.app.router.routes)
128
 
129
+ demo.app.mount("/api/v1", backend_app)
 
130
 
 
 
131
  new_route_count = len(demo.app.router.routes) - pre_insertion_route_count
132
  if new_route_count > 0:
133
  demo.app.router.routes = demo.app.router.routes[-new_route_count:] + demo.app.router.routes[:-new_route_count]
134
+ logger.info("Successfully prepended custom FastAPI /api/v1 sub-app mount route in Gradio router.")
135
 
136
  # Launch the Gradio app blocks directly (Gradio reads port 7860 from env and starts the server)
137
  demo.launch()