HFShishir commited on
Commit
3133727
·
verified ·
1 Parent(s): 1f0cde3

Use direct ASGI middleware dispatching for routing bypass

Browse files
Files changed (1) hide show
  1. gradio_app.py +25 -14
gradio_app.py CHANGED
@@ -47,7 +47,7 @@ backend_app = FastAPI(
47
  backend_app.state.limiter = limiter
48
  backend_app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
49
 
50
- # App Secret Authentication Middleware
51
  @backend_app.middleware("http")
52
  async def app_secret_security_middleware(request: Request, call_next):
53
  path = request.url.path
@@ -88,13 +88,13 @@ backend_app.add_middleware(
88
  allow_headers=["*"],
89
  )
90
 
91
- # Health endpoint (will map to /gradio_api/v1/health)
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 Router directly (will map to /gradio_api/v1/digest/digests, etc.)
98
  backend_app.include_router(api_router)
99
 
100
  # Dummy function decorated with GPU to satisfy Hugging Face ZeroGPU requirement
@@ -112,24 +112,35 @@ with gr.Blocks(title="BytePulse AI Backend", theme=gr.themes.Soft()) as demo:
112
 
113
  | Endpoint | Description |
114
  |----------|-------------|
115
- | [`/gradio_api/v1/health`](./gradio_api/v1/health) | Health check |
116
- | [`/gradio_api/v1/docs`](./gradio_api/v1/docs) | Swagger API Docs |
117
  """
118
  )
119
  btn = gr.Button("Warm Up ZeroGPU")
120
  out = gr.Textbox()
121
  btn.click(fn=dummy_gpu_func, inputs=out, outputs=out)
122
 
123
- # Mount our custom backend app inside Gradio's internal FastAPI app under '/gradio_api/v1' path
124
- # Gradio's ASGI middleware bypasses all paths starting with '/gradio_api' to prevent returning Svelte HTML.
125
- pre_insertion_route_count = len(demo.app.router.routes)
126
 
127
- demo.app.mount("/gradio_api/v1", backend_app)
128
-
129
- new_route_count = len(demo.app.router.routes) - pre_insertion_route_count
130
- if new_route_count > 0:
131
- demo.app.router.routes = demo.app.router.routes[-new_route_count:] + demo.app.router.routes[:-new_route_count]
132
- logger.info("Successfully prepended custom FastAPI /gradio_api/v1 sub-app mount route in Gradio router.")
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
  # Launch the Gradio app blocks directly (Gradio reads port 7860 from env and starts the server)
135
  demo.launch()
 
47
  backend_app.state.limiter = limiter
48
  backend_app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
49
 
50
+ # App Secret Authentication Middleware on backend_app
51
  @backend_app.middleware("http")
52
  async def app_secret_security_middleware(request: Request, call_next):
53
  path = request.url.path
 
88
  allow_headers=["*"],
89
  )
90
 
91
+ # Health endpoint (will map to /api/v1/health via dispatch)
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 Router directly (will map to /api/v1/digest/digests, etc.)
98
  backend_app.include_router(api_router)
99
 
100
  # Dummy function decorated with GPU to satisfy Hugging Face ZeroGPU requirement
 
112
 
113
  | Endpoint | Description |
114
  |----------|-------------|
115
+ | [`/api/v1/health`](./api/v1/health) | Health check |
116
+ | [`/api/v1/docs`](./api/v1/docs) | Swagger API Docs |
117
  """
118
  )
119
  btn = gr.Button("Warm Up ZeroGPU")
120
  out = gr.Textbox()
121
  btn.click(fn=dummy_gpu_func, inputs=out, outputs=out)
122
 
123
+ # Access Gradio's internal FastAPI app
124
+ app = demo.app
 
125
 
126
+ # Custom ASGI Middleware to intercept all incoming requests
127
+ # If the path starts with /api/v1 or /health, we bypass Gradio entirely and dispatch to backend_app.
128
+ # This works independently of FastAPI route matching order and UI wildcards!
129
+ @app.middleware("http")
130
+ async def asgi_routing_bypass_middleware(request: Request, call_next):
131
+ path = request.url.path
132
+ if path.startswith("/api/v1") or path == "/health":
133
+ # Modify request path scope for backend_app matching if needed
134
+ # Since backend_app expects /health and /digest/digests, we strip /api/v1 from the path if it starts with it
135
+ if path.startswith("/api/v1"):
136
+ # Strip /api/v1 prefix for internal backend_app routing
137
+ new_path = path[7:] or "/"
138
+ request.scope["path"] = new_path
139
+
140
+ # Dispatch directly to backend_app using ASGI protocol
141
+ return await backend_app(request.scope, request.receive, request.send)
142
+
143
+ return await call_next(request)
144
 
145
  # Launch the Gradio app blocks directly (Gradio reads port 7860 from env and starts the server)
146
  demo.launch()