File size: 1,712 Bytes
c71be75
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
49
50
51
52
53
54
55
56
57
58
59
60
61
"""FakeGuard-TH Backend API — Hugging Face Space (Docker)

โหลดโมเดลทั้ง 3 ตัว (SVM, Random Forest, WangchanBERTa) จาก HF Model Hub
ตอน container start แล้วให้บริการผ่าน FastAPI เหมือน backend/main.py ทุกอย่าง
"""

import os
from contextlib import asynccontextmanager

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field

from inference import ModelRegistry

registry = ModelRegistry()
FRONTEND_ORIGIN = os.environ.get("FRONTEND_ORIGIN", "*")


@asynccontextmanager
async def lifespan(app: FastAPI):
    registry.warmup()
    yield


app = FastAPI(
    title="FakeGuard-TH API",
    description="ระบบตรวจสอบความน่าเชื่อถือของข่าวภาษาไทย (โครงงาน JSTP รุ่นที่ 29)",
    version="0.1.0",
    lifespan=lifespan,
)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"] if FRONTEND_ORIGIN == "*" else [FRONTEND_ORIGIN],
    allow_methods=["*"],
    allow_headers=["*"],
)


class PredictRequest(BaseModel):
    text: str = Field(min_length=10, max_length=2000)
    model: str | None = Field(default=None)


@app.get("/api/health")
def health() -> dict:
    return {"status": "ok", "best_model": registry.best}


@app.get("/api/models")
def models() -> dict:
    return registry.metrics


@app.post("/api/predict")
def predict(req: PredictRequest) -> dict:
    try:
        return registry.predict(req.text, req.model)
    except KeyError as e:
        raise HTTPException(status_code=400, detail=str(e)) from e