Spaces:
Sleeping
Sleeping
Mount sub-apps explicitly on demo.app to bypass UI wildcards
Browse files- gradio_app.py +56 -55
gradio_app.py
CHANGED
|
@@ -25,55 +25,30 @@ logger = logging.getLogger(__name__)
|
|
| 25 |
# Initialize Rate Limiter
|
| 26 |
limiter = Limiter(key_func=get_remote_address, default_limits=["60 per minute"])
|
| 27 |
|
| 28 |
-
#
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
# Minimal Gradio landing page
|
| 34 |
-
with gr.Blocks(title="BytePulse AI Backend", theme=gr.themes.Soft()) as demo:
|
| 35 |
-
gr.Markdown(
|
| 36 |
-
"""
|
| 37 |
-
# ⚡ BytePulse AI — Daily Tech Digest API
|
| 38 |
-
|
| 39 |
-
> Backend is **live and healthy!** 🚀
|
| 40 |
-
|
| 41 |
-
| Endpoint | Description |
|
| 42 |
-
|----------|-------------|
|
| 43 |
-
| [`/health`](./health) | Health check |
|
| 44 |
-
| [`/docs`](./docs) | Swagger API Docs |
|
| 45 |
-
| [`/api/v1`](./api/v1) | API Base |
|
| 46 |
-
"""
|
| 47 |
-
)
|
| 48 |
-
btn = gr.Button("Warm Up ZeroGPU")
|
| 49 |
-
out = gr.Textbox()
|
| 50 |
-
btn.click(fn=dummy_gpu_func, inputs=out, outputs=out)
|
| 51 |
-
|
| 52 |
-
# Access Gradio's internal FastAPI app
|
| 53 |
-
app = demo.app
|
| 54 |
-
|
| 55 |
-
# Configure FastAPI attributes on Gradio's app
|
| 56 |
-
app.title = settings.APP_NAME
|
| 57 |
-
app.version = settings.VERSION
|
| 58 |
-
app.description = "Enterprise API for BytePulse AI Daily Tech Digest powered by 8 Scrapers, Gemini 2.5 Flash, ChromaDB, and FCM."
|
| 59 |
-
|
| 60 |
-
# Initialize database schema and scheduler during startup event
|
| 61 |
-
@app.on_event("startup")
|
| 62 |
-
async def startup_event():
|
| 63 |
logger.info("Initializing database schema...")
|
| 64 |
Base.metadata.create_all(bind=engine)
|
| 65 |
start_scheduler()
|
| 66 |
-
|
| 67 |
-
@app.on_event("shutdown")
|
| 68 |
-
async def shutdown_event():
|
| 69 |
stop_scheduler()
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
# Attach Rate Limiter
|
| 72 |
-
|
| 73 |
-
|
| 74 |
|
| 75 |
# App Secret Authentication Middleware
|
| 76 |
-
@
|
| 77 |
async def app_secret_security_middleware(request: Request, call_next):
|
| 78 |
path = request.url.path
|
| 79 |
if path in ["/", "/health", "/docs", "/openapi.json", "/redoc"]:
|
|
@@ -92,7 +67,7 @@ async def app_secret_security_middleware(request: Request, call_next):
|
|
| 92 |
return await call_next(request)
|
| 93 |
|
| 94 |
# Global Error Handler
|
| 95 |
-
@
|
| 96 |
async def global_exception_handler(request: Request, exc: Exception):
|
| 97 |
logger.error(f"Global Error caught on {request.url.path}: {exc}", exc_info=True)
|
| 98 |
return JSONResponse(
|
|
@@ -105,7 +80,7 @@ async def global_exception_handler(request: Request, exc: Exception):
|
|
| 105 |
)
|
| 106 |
|
| 107 |
# Enable CORS Security Middleware
|
| 108 |
-
|
| 109 |
CORSMiddleware,
|
| 110 |
allow_origins=["*"],
|
| 111 |
allow_credentials=True,
|
|
@@ -113,23 +88,49 @@ app.add_middleware(
|
|
| 113 |
allow_headers=["*"],
|
| 114 |
)
|
| 115 |
|
| 116 |
-
#
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
# Include custom API routes directly on Gradio FastAPI app
|
| 120 |
-
@app.get("/health")
|
| 121 |
@limiter.limit("60/minute")
|
| 122 |
def health_check(request: Request):
|
| 123 |
return {"status": "healthy", "service": settings.APP_NAME, "security": "rate_limited_enabled"}
|
| 124 |
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
-
#
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
|
|
|
| 132 |
|
| 133 |
# Launch the Gradio app blocks directly (Gradio reads port 7860 from env and starts the server)
|
| 134 |
-
# This blocks execution and keeps the container process alive on port 7860
|
| 135 |
demo.launch()
|
|
|
|
| 25 |
# Initialize Rate Limiter
|
| 26 |
limiter = Limiter(key_func=get_remote_address, default_limits=["60 per minute"])
|
| 27 |
|
| 28 |
+
# Lifespan events context manager
|
| 29 |
+
from contextlib import asynccontextmanager
|
| 30 |
+
@asynccontextmanager
|
| 31 |
+
async def lifespan(app: FastAPI):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
logger.info("Initializing database schema...")
|
| 33 |
Base.metadata.create_all(bind=engine)
|
| 34 |
start_scheduler()
|
| 35 |
+
yield
|
|
|
|
|
|
|
| 36 |
stop_scheduler()
|
| 37 |
|
| 38 |
+
# Initialize custom FastAPI backend sub-app
|
| 39 |
+
backend_app = FastAPI(
|
| 40 |
+
title=settings.APP_NAME,
|
| 41 |
+
version=settings.VERSION,
|
| 42 |
+
description="Enterprise API for BytePulse AI Daily Tech Digest powered by 8 Scrapers, Gemini 2.5 Flash, ChromaDB, and FCM.",
|
| 43 |
+
lifespan=lifespan
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
# Attach Rate Limiter
|
| 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
|
| 54 |
if path in ["/", "/health", "/docs", "/openapi.json", "/redoc"]:
|
|
|
|
| 67 |
return await call_next(request)
|
| 68 |
|
| 69 |
# Global Error Handler
|
| 70 |
+
@backend_app.exception_handler(Exception)
|
| 71 |
async def global_exception_handler(request: Request, exc: Exception):
|
| 72 |
logger.error(f"Global Error caught on {request.url.path}: {exc}", exc_info=True)
|
| 73 |
return JSONResponse(
|
|
|
|
| 80 |
)
|
| 81 |
|
| 82 |
# Enable CORS Security Middleware
|
| 83 |
+
backend_app.add_middleware(
|
| 84 |
CORSMiddleware,
|
| 85 |
allow_origins=["*"],
|
| 86 |
allow_credentials=True,
|
|
|
|
| 88 |
allow_headers=["*"],
|
| 89 |
)
|
| 90 |
|
| 91 |
+
# Custom /health endpoint
|
| 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 sub-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
|
| 102 |
+
def dummy_gpu_func(name):
|
| 103 |
+
return f"ZeroGPU active for {name}"
|
| 104 |
+
|
| 105 |
+
# Minimal Gradio landing page
|
| 106 |
+
with gr.Blocks(title="BytePulse AI Backend", theme=gr.themes.Soft()) as demo:
|
| 107 |
+
gr.Markdown(
|
| 108 |
+
"""
|
| 109 |
+
# ⚡ BytePulse AI — Daily Tech Digest API
|
| 110 |
+
|
| 111 |
+
> Backend is **live and healthy!** 🚀
|
| 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 backend FastAPI sub-app inside Gradio's internal FastAPI app
|
| 125 |
+
# FastAPI mounts are prioritized first in routing, completely bypassing Gradio UI wildcards!
|
| 126 |
+
demo.app.mount("/api/v1", api_router)
|
| 127 |
|
| 128 |
+
# Mount health endpoint sub-app explicitly to bypass Gradio wildcards
|
| 129 |
+
health_app = FastAPI()
|
| 130 |
+
@health_app.get("")
|
| 131 |
+
def root_health():
|
| 132 |
+
return {"status": "healthy", "service": settings.APP_NAME, "security": "rate_limited_enabled"}
|
| 133 |
+
demo.app.mount("/health", health_app)
|
| 134 |
|
| 135 |
# Launch the Gradio app blocks directly (Gradio reads port 7860 from env and starts the server)
|
|
|
|
| 136 |
demo.launch()
|