Alovestocode commited on
Commit
8bc1f92
·
verified ·
1 Parent(s): 27e964d

Fix: Use middleware to intercept API routes before Gradio processes them

Browse files
Files changed (1) hide show
  1. app.py +34 -20
app.py CHANGED
@@ -524,7 +524,6 @@ with gr.Blocks(
524
  """Mount FastAPI routes using middleware to ensure they're processed first."""
525
  try:
526
  from fastapi.responses import JSONResponse
527
- from starlette.middleware.base import BaseHTTPMiddleware
528
  from starlette.requests import Request
529
  from starlette.responses import Response
530
 
@@ -557,28 +556,43 @@ with gr.Blocks(
557
  """Handle GET /console requests."""
558
  return HTMLResponse(interactive_ui())
559
 
560
- # Create middleware to intercept routes before Gradio
561
- class FastAPIRouteMiddleware(BaseHTTPMiddleware):
562
- async def dispatch(self, request: Request, call_next):
563
- path = request.url.path
564
- method = request.method
565
-
566
- # Handle our custom routes
567
- if path == "/health" and method == "GET":
568
- return await health_handler(request)
569
- elif path == "/v1/generate" and method == "POST":
570
- return await generate_handler(request)
571
- elif path == "/console" and method == "GET":
572
- return await console_handler(request)
573
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
574
  # Let other requests pass through to Gradio
575
- return await call_next(request)
576
 
577
- # Add middleware to Gradio's app (must be added before app is built)
578
- # Use add_middleware to properly register it
579
  try:
580
- gradio_app.app.add_middleware(FastAPIRouteMiddleware)
581
- print("FastAPI routes mounted successfully via middleware")
 
 
582
  except Exception as middleware_error:
583
  # Fallback: try to add routes directly to router
584
  print(f"Middleware approach failed: {middleware_error}, trying direct route addition...")
 
524
  """Mount FastAPI routes using middleware to ensure they're processed first."""
525
  try:
526
  from fastapi.responses import JSONResponse
 
527
  from starlette.requests import Request
528
  from starlette.responses import Response
529
 
 
556
  """Handle GET /console requests."""
557
  return HTMLResponse(interactive_ui())
558
 
559
+ # Create pure ASGI middleware to intercept routes before Gradio
560
+ # This avoids Content-Length issues with BaseHTTPMiddleware
561
+ class FastAPIRouteMiddleware:
562
+ def __init__(self, app):
563
+ self.app = app
564
+
565
+ async def __call__(self, scope, receive, send):
566
+ if scope["type"] == "http":
567
+ path = scope["path"]
568
+ method = scope["method"]
569
+
570
+ # Handle our custom routes
571
+ if path == "/health" and method == "GET":
572
+ request = Request(scope, receive)
573
+ response = await health_handler(request)
574
+ await response(scope, receive, send)
575
+ return
576
+ elif path == "/v1/generate" and method == "POST":
577
+ request = Request(scope, receive)
578
+ response = await generate_handler(request)
579
+ await response(scope, receive, send)
580
+ return
581
+ elif path == "/console" and method == "GET":
582
+ request = Request(scope, receive)
583
+ response = await console_handler(request)
584
+ await response(scope, receive, send)
585
+ return
586
+
587
  # Let other requests pass through to Gradio
588
+ await self.app(scope, receive, send)
589
 
590
+ # Wrap Gradio's app with our pure ASGI middleware
 
591
  try:
592
+ # Store original app and wrap it with our middleware
593
+ original_app = gradio_app.app
594
+ gradio_app.app = FastAPIRouteMiddleware(original_app)
595
+ print("FastAPI routes mounted successfully via pure ASGI middleware")
596
  except Exception as middleware_error:
597
  # Fallback: try to add routes directly to router
598
  print(f"Middleware approach failed: {middleware_error}, trying direct route addition...")