-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_server.py
More file actions
61 lines (45 loc) · 1.43 KB
/
http_server.py
File metadata and controls
61 lines (45 loc) · 1.43 KB
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
"""
Cato HTTP API Server (FastAPI)
POST /detect - 检测单条文本
POST /batch - 批量检测
GET /health - 健康检查
"""
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from main import CatoModel, load_lexicon
lexicon = load_lexicon()
model = CatoModel()
if not model.load():
raise RuntimeError("模型文件不存在,请先运行 main.py 训练模型")
model.lexicon = lexicon
print("模型加载完成")
app = FastAPI(title="Cato", version="0.1.0")
class DetectRequest(BaseModel):
text: str
class BatchRequest(BaseModel):
texts: list[str]
@app.get("/health")
async def health():
return {"status": "ok"}
@app.post("/detect")
async def detect(req: DetectRequest):
if not req.text:
raise HTTPException(status_code=400, detail="text is required")
return model.score_text(req.text)
@app.post("/batch")
async def batch(req: BatchRequest):
if not req.texts:
raise HTTPException(status_code=400, detail="texts is required")
preds, probs = model.predict(req.texts)
results = []
for i, text in enumerate(req.texts):
p = float(probs[i])
results.append({
"text": text[:200],
"score": round(p, 4),
"verdict": "违规" if preds[i] == 1 else "正常",
})
return {"results": results, "total": len(results)}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8421)