Spaces:
Sleeping
Sleeping
File size: 1,675 Bytes
232a0ea b82e46a 232a0ea b82e46a 232a0ea b82e46a 232a0ea b82e46a 232a0ea b82e46a 232a0ea b82e46a 232a0ea b82e46a 232a0ea b82e46a 232a0ea b82e46a 232a0ea | 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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | from fastapi import FastAPI
from pydantic import BaseModel
from openai import OpenAI
import uvicorn
app = FastAPI()
# =========================
# OPENAI CLIENT
# =========================
client = OpenAI() # uses OPENAI_API_KEY from environment / HF Secrets
# =========================
# REQUEST BODY
# =========================
class TextIn(BaseModel):
text: str
# =========================
# CORE MODERATION FUNCTION
# =========================
def analyze_text(text: str):
try:
response = client.moderations.create(
model="omni-moderation-latest",
input=text
)
result = response.results[0]
return {
"input": text,
"flagged": result.flagged,
"categories": result.categories.model_dump(),
"category_scores": result.category_scores.model_dump()
}
except Exception as e:
return {
"input": text,
"error": str(e),
"flagged": False
}
# =========================
# GET ENDPOINT
# =========================
@app.get("/analyze")
def analyze_get(text: str):
return analyze_text(text)
# =========================
# POST ENDPOINT
# =========================
@app.post("/analyze")
def analyze_post(body: TextIn):
return analyze_text(body.text)
# =========================
# ROOT
# =========================
@app.get("/")
def root():
return {
"status": "ok",
"usage": "/analyze?text=your_text_here"
}
# =========================
# RUN (for local testing only)
# =========================
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860) |