Breadknife commited on
Commit
528de41
·
1 Parent(s): 3fdb3d0

Emergency fix: Background model loading to prevent HF Space startup timeout

Browse files
Files changed (1) hide show
  1. hf_api.py +24 -5
hf_api.py CHANGED
@@ -23,10 +23,17 @@ except ImportError:
23
  app = FastAPI(title="NewsApex AI Backend")
24
  service = NewsService()
25
 
26
- # Pre-load the model at startup to avoid delay on first request
27
- print("Pre-loading bias model...", file=sys.stderr)
28
- service.load_local_bias_model()
29
- print("Bias model ready.", file=sys.stderr)
 
 
 
 
 
 
 
30
 
31
  class AnalysisRequest(BaseModel):
32
  url: Optional[str] = None
@@ -35,7 +42,19 @@ class AnalysisRequest(BaseModel):
35
 
36
  @app.get("/")
37
  def read_root():
38
- return {"status": "online", "model": "BERT-BABE Bias Detector"}
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
  @app.get("/fetch_news")
41
  def fetch_news(query: Optional[str] = None, category: Optional[str] = None):
 
23
  app = FastAPI(title="NewsApex AI Backend")
24
  service = NewsService()
25
 
26
+ @app.on_event("startup")
27
+ async def startup_event():
28
+ """Load the model in the background so the server starts immediately and passes the health check."""
29
+ import threading
30
+ def load_model():
31
+ print("Startup Task: Pre-loading bias model...", file=sys.stderr)
32
+ service.load_local_bias_model()
33
+ print("Startup Task: Bias model ready.", file=sys.stderr)
34
+
35
+ # Run loading in a background thread to prevent blocking the FastAPI startup loop
36
+ threading.Thread(target=load_model, daemon=True).start()
37
 
38
  class AnalysisRequest(BaseModel):
39
  url: Optional[str] = None
 
42
 
43
  @app.get("/")
44
  def read_root():
45
+ """Simple health check endpoint for Hugging Face and Vercel monitoring."""
46
+ model_status = "Loaded" if service.bias_model else "Loading (Background)"
47
+ return {
48
+ "status": "online",
49
+ "service": "NewsApex AI Backend",
50
+ "model_status": model_status,
51
+ "api_version": "1.1.0"
52
+ }
53
+
54
+ @app.get("/health")
55
+ def health_check():
56
+ """Dedicated health check for deployment monitors."""
57
+ return {"status": "ok", "model_ready": service.bias_model is not None}
58
 
59
  @app.get("/fetch_news")
60
  def fetch_news(query: Optional[str] = None, category: Optional[str] = None):