File size: 1,403 Bytes
2f97561
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import os

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field

from src.predictor import ArticleTopicPredictor


MODEL_DIR = os.getenv("MODEL_DIR", "artifacts/article_topic_model")

app = FastAPI(title="Article Topic Classifier API", version="1.0.0")
_predictor: ArticleTopicPredictor | None = None


class PredictRequest(BaseModel):
    title: str = Field(default="", max_length=600)
    abstract: str = Field(default="", max_length=8000)
    top95_threshold: float = Field(default=0.95, ge=0.5, le=0.999)


@app.on_event("startup")
def startup_event() -> None:
    global _predictor
    _predictor = ArticleTopicPredictor(model_dir=MODEL_DIR)


@app.get("/health")
def health() -> dict:
    return {"status": "ok", "model_dir": MODEL_DIR}


@app.post("/predict")
def predict(request: PredictRequest) -> dict:
    if not request.title.strip() and not request.abstract.strip():
        raise HTTPException(status_code=400, detail="Provide at least title or abstract.")

    if _predictor is None:
        raise HTTPException(status_code=503, detail="Model is not loaded yet.")

    try:
        return _predictor.predict(
            title=request.title,
            abstract=request.abstract,
            top95_threshold=request.top95_threshold,
        )
    except Exception as exc:  # noqa: BLE001
        raise HTTPException(status_code=500, detail=str(exc)) from exc