HFShishir commited on
Commit
4db4e13
·
verified ·
1 Parent(s): d353bd9

Run Gradio on port 7861 and FastAPI on port 7860

Browse files
Files changed (1) hide show
  1. gradio_app.py +63 -55
gradio_app.py CHANGED
@@ -25,55 +25,33 @@ logger = logging.getLogger(__name__)
25
  # Initialize Rate Limiter
26
  limiter = Limiter(key_func=get_remote_address, default_limits=["60 per minute"])
27
 
28
- # Dummy function decorated with GPU to satisfy Hugging Face ZeroGPU requirement
29
- @spaces.GPU
30
- def dummy_gpu_func(name):
31
- return f"ZeroGPU active for {name}"
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
- app.state.limiter = limiter
73
- app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
74
 
75
  # App Secret Authentication Middleware
76
- @app.middleware("http")
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 +70,7 @@ async def app_secret_security_middleware(request: Request, call_next):
92
  return await call_next(request)
93
 
94
  # Global Error Handler
95
- @app.exception_handler(Exception)
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 +83,7 @@ async def global_exception_handler(request: Request, exc: Exception):
105
  )
106
 
107
  # Enable CORS Security Middleware
108
- app.add_middleware(
109
  CORSMiddleware,
110
  allow_origins=["*"],
111
  allow_credentials=True,
@@ -113,15 +91,45 @@ app.add_middleware(
113
  allow_headers=["*"],
114
  )
115
 
116
- # Health Endpoint directly on Gradio FastAPI app
117
- @app.get("/health")
118
  @limiter.limit("60/minute")
119
  def health_check(request: Request):
120
  return {"status": "healthy", "service": settings.APP_NAME, "security": "rate_limited_enabled"}
121
 
122
- # Include API v1 Router directly on Gradio FastAPI app
123
- app.include_router(api_router, prefix="/api/v1")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
 
125
- # Launch Gradio Block directly on port 7860 to allow ZeroGPU hooks to initialize
126
- # This will block the process and keep the server running continuously.
127
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
25
  # Initialize Rate Limiter
26
  limiter = Limiter(key_func=get_remote_address, default_limits=["60 per minute"])
27
 
28
+ # Lifespan events
29
+ @fastapi_app_lifespan := None
30
+ def set_lifespan():
31
+ from contextlib import asynccontextmanager
32
+ @asynccontextmanager
33
+ async def lifespan(app: FastAPI):
34
+ logger.info("Initializing database schema...")
35
+ Base.metadata.create_all(bind=engine)
36
+ start_scheduler()
37
+ yield
38
+ stop_scheduler()
39
+ return lifespan
40
+
41
+ # Initialize FastAPI application
42
+ fastapi_app = FastAPI(
43
+ title=settings.APP_NAME,
44
+ version=settings.VERSION,
45
+ description="Enterprise API for BytePulse AI Daily Tech Digest powered by 8 Scrapers, Gemini 2.5 Flash, ChromaDB, and FCM.",
46
+ lifespan=set_lifespan()
47
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
+ # Attach Rate Limiter to app state
50
+ fastapi_app.state.limiter = limiter
51
+ fastapi_app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
52
 
53
  # App Secret Authentication Middleware
54
+ @fastapi_app.middleware("http")
55
  async def app_secret_security_middleware(request: Request, call_next):
56
  path = request.url.path
57
  if path in ["/", "/health", "/docs", "/openapi.json", "/redoc"]:
 
70
  return await call_next(request)
71
 
72
  # Global Error Handler
73
+ @fastapi_app.exception_handler(Exception)
74
  async def global_exception_handler(request: Request, exc: Exception):
75
  logger.error(f"Global Error caught on {request.url.path}: {exc}", exc_info=True)
76
  return JSONResponse(
 
83
  )
84
 
85
  # Enable CORS Security Middleware
86
+ fastapi_app.add_middleware(
87
  CORSMiddleware,
88
  allow_origins=["*"],
89
  allow_credentials=True,
 
91
  allow_headers=["*"],
92
  )
93
 
94
+ # Root & Health Endpoints
95
+ @fastapi_app.get("/health")
96
  @limiter.limit("60/minute")
97
  def health_check(request: Request):
98
  return {"status": "healthy", "service": settings.APP_NAME, "security": "rate_limited_enabled"}
99
 
100
+ # Include API v1 Router
101
+ fastapi_app.include_router(api_router, prefix="/api/v1")
102
+
103
+ # Dummy function decorated with GPU to satisfy Hugging Face ZeroGPU requirement
104
+ @spaces.GPU
105
+ def dummy_gpu_func(name):
106
+ return f"ZeroGPU active for {name}"
107
+
108
+ # Minimal Gradio landing page
109
+ with gr.Blocks(title="BytePulse AI Backend", theme=gr.themes.Soft()) as demo:
110
+ gr.Markdown(
111
+ """
112
+ # ⚡ BytePulse AI — Daily Tech Digest API
113
+
114
+ > Backend is **live and healthy!** 🚀
115
+
116
+ | Endpoint | Description |
117
+ |----------|-------------|
118
+ | [`/health`](./health) | Health check |
119
+ | [`/docs`](./docs) | Swagger API Docs |
120
+ | [`/api/v1`](./api/v1) | API Base |
121
+ """
122
+ )
123
+ btn = gr.Button("Warm Up ZeroGPU")
124
+ out = gr.Textbox()
125
+ btn.click(fn=dummy_gpu_func, inputs=out, outputs=out)
126
+
127
+ # Mount Gradio inside FastAPI under /gradio path
128
+ app = gr.mount_gradio_app(fastapi_app, demo, path="/gradio")
129
+
130
+ # Launch demo in non-blocking mode on port 7861 so ZeroGPU hooks into Gradio successfully
131
+ demo.launch(server_name="0.0.0.0", server_port=7861, prevent_thread_lock=True)
132
 
133
+ # Run the unified FastAPI app on the main HF port 7860 to handle root API endpoints
134
+ import uvicorn
135
+ uvicorn.run(app, host="0.0.0.0", port=7860)