Spaces:
Sleeping
Sleeping
| 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 | |
| # ========================= | |
| def analyze_get(text: str): | |
| return analyze_text(text) | |
| # ========================= | |
| # POST ENDPOINT | |
| # ========================= | |
| def analyze_post(body: TextIn): | |
| return analyze_text(body.text) | |
| # ========================= | |
| # ROOT | |
| # ========================= | |
| 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) |