Spaces:
Runtime error
Runtime error
Add Gradio app
Browse files- app.py +48 -0
- requirements.txt +2 -1
app.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from transformers import pipeline
|
| 3 |
+
|
| 4 |
+
# Load model
|
| 5 |
+
classifier = pipeline("text-classification",
|
| 6 |
+
model="unitary/toxic-bert",
|
| 7 |
+
top_k=None)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def moderate(text):
|
| 11 |
+
if not text or len(text.strip()) == 0:
|
| 12 |
+
return "Error: Text cannot be empty"
|
| 13 |
+
|
| 14 |
+
if len(text) > 5000:
|
| 15 |
+
return "Error: Text too long (max 5000 characters)"
|
| 16 |
+
|
| 17 |
+
result = classifier(text)[0]
|
| 18 |
+
top_prediction = max(result, key=lambda x: x['score'])
|
| 19 |
+
|
| 20 |
+
output = f"**Prediction:** {top_prediction['label']}\n"
|
| 21 |
+
output += f"**Confidence:** {top_prediction['score']:.2%}\n\n"
|
| 22 |
+
output += "**All Scores:**\n"
|
| 23 |
+
for pred in sorted(result, key=lambda x: x['score'], reverse=True):
|
| 24 |
+
output += f"- {pred['label']}: {pred['score']:.2%}\n"
|
| 25 |
+
|
| 26 |
+
return output
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# Create interface
|
| 30 |
+
demo = gr.Interface(
|
| 31 |
+
fn=moderate,
|
| 32 |
+
inputs=gr.Textbox(
|
| 33 |
+
lines=5,
|
| 34 |
+
placeholder="Enter text to moderate...",
|
| 35 |
+
label="Input Text"
|
| 36 |
+
),
|
| 37 |
+
outputs=gr.Markdown(label="Moderation Results"),
|
| 38 |
+
title="🛡️ Content Moderation API",
|
| 39 |
+
description="Detects toxic and harmful content using a fine-tuned BERT model.",
|
| 40 |
+
examples=[
|
| 41 |
+
["This is a wonderful day!"],
|
| 42 |
+
["I hate everything about this"],
|
| 43 |
+
["You are amazing and I appreciate your help"]
|
| 44 |
+
]
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
if __name__ == "__main__":
|
| 48 |
+
demo.launch()
|
requirements.txt
CHANGED
|
@@ -2,4 +2,5 @@ fastapi==0.104.1
|
|
| 2 |
uvicorn==0.24.0
|
| 3 |
transformers==4.35.0
|
| 4 |
torch==2.1.0
|
| 5 |
-
pydantic==2.5.0
|
|
|
|
|
|
| 2 |
uvicorn==0.24.0
|
| 3 |
transformers==4.35.0
|
| 4 |
torch==2.1.0
|
| 5 |
+
pydantic==2.5.0
|
| 6 |
+
gradio
|