Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
from transformers import pipeline
|
| 4 |
+
import uvicorn
|
| 5 |
+
|
| 6 |
+
app = FastAPI()
|
| 7 |
+
|
| 8 |
+
# ===== LOAD MODEL (LIGHTWEIGHT MULTILINGUAL TOXICITY) =====
|
| 9 |
+
classifier = pipeline(
|
| 10 |
+
"text-classification",
|
| 11 |
+
model="unitary/multilingual-toxic-xlm-roberta",
|
| 12 |
+
top_k=None
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
# ===== RESPONSE MODEL =====
|
| 16 |
+
class TextIn(BaseModel):
|
| 17 |
+
text: str
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def analyze_text(text: str):
|
| 21 |
+
result = classifier(text)[0]
|
| 22 |
+
|
| 23 |
+
# model output: list of dicts
|
| 24 |
+
# we normalize it
|
| 25 |
+
output = []
|
| 26 |
+
for r in result:
|
| 27 |
+
output.append({
|
| 28 |
+
"label": r["label"],
|
| 29 |
+
"score": float(r["score"])
|
| 30 |
+
})
|
| 31 |
+
|
| 32 |
+
# find toxic score (if label exists)
|
| 33 |
+
toxic_score = 0.0
|
| 34 |
+
for r in output:
|
| 35 |
+
if "toxic" in r["label"].lower():
|
| 36 |
+
toxic_score = r["score"]
|
| 37 |
+
|
| 38 |
+
return {
|
| 39 |
+
"input": text,
|
| 40 |
+
"toxic_score": toxic_score,
|
| 41 |
+
"details": output,
|
| 42 |
+
"is_flagged": toxic_score > 0.5
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# ===== GET ENDPOINT (WHAT YOU WANT) =====
|
| 47 |
+
@app.get("/analyze")
|
| 48 |
+
def analyze_get(text: str):
|
| 49 |
+
return analyze_text(text)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# ===== OPTIONAL POST ENDPOINT =====
|
| 53 |
+
@app.post("/analyze")
|
| 54 |
+
def analyze_post(body: TextIn):
|
| 55 |
+
return analyze_text(body.text)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# ===== ROOT =====
|
| 59 |
+
@app.get("/")
|
| 60 |
+
def root():
|
| 61 |
+
return {
|
| 62 |
+
"status": "ok",
|
| 63 |
+
"usage": "/analyze?text=your_message_here"
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# ===== RUN (for local testing only) =====
|
| 68 |
+
if __name__ == "__main__":
|
| 69 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|