Alovestocode commited on
Commit
7d6ddbd
·
verified ·
1 Parent(s): 10bb95a

Fix: Use gradio_app.load() event to add routes after initialization

Browse files
Files changed (1) hide show
  1. app.py +57 -48
app.py CHANGED
@@ -511,54 +511,63 @@ with gr.Blocks(
511
  outputs=[prompt_input, output],
512
  )
513
 
514
- # Add FastAPI routes directly to Gradio's router
515
- # This ensures they're registered and accessible alongside Gradio routes
516
- try:
517
- from fastapi.responses import JSONResponse
518
-
519
- async def generate_handler(request):
520
- """Handle POST /v1/generate requests."""
521
- try:
522
- data = await request.json()
523
- payload = GeneratePayload(**data)
524
- text = _generate_with_gpu(
525
- prompt=payload.prompt,
526
- max_new_tokens=payload.max_new_tokens or MAX_NEW_TOKENS,
527
- temperature=payload.temperature or DEFAULT_TEMPERATURE,
528
- top_p=payload.top_p or DEFAULT_TOP_P,
529
- )
530
- return JSONResponse(content={"text": text})
531
- except Exception as exc:
532
- from fastapi import HTTPException
533
- raise HTTPException(status_code=500, detail=str(exc))
534
-
535
- async def healthcheck_handler(request):
536
- """Handle GET /api/health requests."""
537
- return JSONResponse(content={
538
- "status": "ok",
539
- "model": MODEL_ID,
540
- "strategy": ACTIVE_STRATEGY or "pending",
541
- })
542
-
543
- async def gradio_ui_handler(request):
544
- """Handle GET /api/gradio requests."""
545
- return HTMLResponse(interactive_ui())
546
-
547
- # Add routes to Gradio's router using Starlette's router
548
- # Use Starlette Route objects for compatibility
549
- from starlette.routing import Route
550
-
551
- # Add routes to Gradio's router
552
- gradio_app.app.router.add_route("/v1/generate", generate_handler, methods=["POST"])
553
- gradio_app.app.router.add_route("/api/health", healthcheck_handler, methods=["GET"])
554
- gradio_app.app.router.add_route("/api/gradio", gradio_ui_handler, methods=["GET"])
555
- # Also add /gradio for backward compatibility
556
- gradio_app.app.router.add_route("/gradio", gradio_ui_handler, methods=["GET"])
557
- print("FastAPI routes added successfully to Gradio router")
558
- except Exception as e:
559
- print(f"Warning: Could not add FastAPI routes: {e}")
560
- import traceback
561
- traceback.print_exc()
 
 
 
 
 
 
 
 
 
562
 
563
  # Set app to Gradio Blocks for Spaces - ZeroGPU requires Gradio SDK
564
  app = gradio_app
 
511
  outputs=[prompt_input, output],
512
  )
513
 
514
+ # Add FastAPI routes using Gradio's load event
515
+ # This ensures routes are added after Gradio is fully initialized
516
+ def add_api_routes():
517
+ """Add API routes after Gradio app is loaded."""
518
+ try:
519
+ from fastapi.responses import JSONResponse
520
+ from starlette.routing import Route
521
+
522
+ async def generate_handler(request):
523
+ """Handle POST /v1/generate requests."""
524
+ try:
525
+ data = await request.json()
526
+ payload = GeneratePayload(**data)
527
+ text = _generate_with_gpu(
528
+ prompt=payload.prompt,
529
+ max_new_tokens=payload.max_new_tokens or MAX_NEW_TOKENS,
530
+ temperature=payload.temperature or DEFAULT_TEMPERATURE,
531
+ top_p=payload.top_p or DEFAULT_TOP_P,
532
+ )
533
+ return JSONResponse(content={"text": text})
534
+ except Exception as exc:
535
+ from fastapi import HTTPException
536
+ raise HTTPException(status_code=500, detail=str(exc))
537
+
538
+ async def healthcheck_handler(request):
539
+ """Handle GET /api/health requests."""
540
+ return JSONResponse(content={
541
+ "status": "ok",
542
+ "model": MODEL_ID,
543
+ "strategy": ACTIVE_STRATEGY or "pending",
544
+ })
545
+
546
+ async def gradio_ui_handler(request):
547
+ """Handle GET /api/gradio requests."""
548
+ return HTMLResponse(interactive_ui())
549
+
550
+ # Add routes using Route objects
551
+ gradio_app.app.router.routes.append(
552
+ Route("/v1/generate", generate_handler, methods=["POST"])
553
+ )
554
+ gradio_app.app.router.routes.append(
555
+ Route("/api/health", healthcheck_handler, methods=["GET"])
556
+ )
557
+ gradio_app.app.router.routes.append(
558
+ Route("/api/gradio", gradio_ui_handler, methods=["GET"])
559
+ )
560
+ gradio_app.app.router.routes.append(
561
+ Route("/gradio", gradio_ui_handler, methods=["GET"])
562
+ )
563
+ print("FastAPI routes added successfully via load event")
564
+ except Exception as e:
565
+ print(f"Warning: Could not add FastAPI routes: {e}")
566
+ import traceback
567
+ traceback.print_exc()
568
+
569
+ # Use load event to add routes after app initialization
570
+ gradio_app.load(add_api_routes)
571
 
572
  # Set app to Gradio Blocks for Spaces - ZeroGPU requires Gradio SDK
573
  app = gradio_app