Spaces:
Sleeping
Sleeping
File size: 1,901 Bytes
478bb6f fe5e888 478bb6f 20cc711 b80778e 478bb6f fcb4a95 fe5e888 478bb6f fcb4a95 b80778e 478bb6f 55702b8 fcb4a95 55702b8 fcb4a95 478bb6f 55702b8 478bb6f fcb4a95 478bb6f 55702b8 478bb6f 55702b8 478bb6f fa0f53f 478bb6f b80778e 478bb6f | 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 | import gradio as gr
import requests
import os
import time
HF_TOKEN = os.environ.get("HF_TOKEN")
API_URL = "https://router.huggingface.co/hf-inference/models/Hate-speech-CNERG/dehatebert-mono-english"
def query(text):
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
for i in range(3):
response = requests.post(API_URL, headers=headers, json={
"inputs": text,
"options": {"wait_for_model": True}
})
if response.status_code == 200:
return response.json()
time.sleep(3)
return {"error": f"Status: {response.status_code}, Response: {response.text}"}
def predict(comment):
if not comment.strip():
return "⚠️ Please enter some text.", ""
try:
result = query(comment)
if isinstance(result, dict) and "error" in result:
return f"API Error: {result['error']}", ""
if isinstance(result, list):
result = result[0][0]
label = result["label"]
score = result["score"]
if label == "HATE":
prediction = "🚨 Hate Speech Detected"
probability = round(score * 100, 2)
else:
prediction = "✅ No Hate Speech"
probability = round((1 - score) * 100, 2)
return prediction, f"{probability}%"
return f"Unexpected: {result}", ""
except Exception as e:
return f"Exception: {str(e)}", ""
demo = gr.Interface(
fn=predict,
inputs=gr.Textbox(lines=4, placeholder="Enter a comment...", label="Comment"),
outputs=[
gr.Textbox(label="Prediction"),
gr.Textbox(label="Confidence")
],
title="🛡️ Hate Speech Detector",
description="Enter any text to check if it contains hate speech."
)
if __name__ == "__main__":
demo.launch() |