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()