Repository navigation
Expand file tree
/
Copy pathserver.py
More file actions
64 lines (52 loc) · 1.93 KB
/
Copy pathserver.py
File metadata and controls
64 lines (52 loc) · 1.93 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
62
63
64
import logging
from pathlib import Path
import uvicorn
from fastapi import FastAPI
from fastapi.responses import JSONResponse, HTMLResponse
from service import ContentModerationService, ModerationRequest, ModerationResponse
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI(title="Content Moderation API", version="0.0.1")
moderation_service = ContentModerationService()
@app.get("/", response_class=HTMLResponse)
def read_root():
"""Serve the content moderation UI"""
ui_file = Path("ui.html")
if ui_file.exists():
return ui_file.read_text(encoding="utf-8")
else:
return """
<html>
<body>
<h1>Content Moderation API</h1>
<p>UI file not found. Please ensure ui.html exists.</p>
</body>
</html>
"""
@app.post("/moderate", response_model=ModerationResponse)
def moderate_content(request: ModerationRequest):
"""
Main endpoint for content moderation
Returns:
- should_moderate: boolean indicating if content should be moderated
- reason: string explaining why the decision was made
- flagged_words: list of words that triggered the decision
- processing_time_ms: time taken to process the request
"""
try:
result = moderation_service.moderate_content(request.text)
return JSONResponse(content=ModerationResponse(**result).model_dump(), status_code=result.get("status_code", 200))
except Exception as e:
logger.error(f"Error during moderation: {e}")
error_body = ModerationResponse(
meta={
"response_time": 0.0,
"flagged_words": [],
},
should_moderate=False,
reason=None,
status_code=500,
).model_dump()
return JSONResponse(content=error_body, status_code=500)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)