File size: 2,179 Bytes
5731e4a
 
 
 
af171ba
5731e4a
 
af171ba
5731e4a
 
 
 
 
74706d1
5731e4a
 
 
 
 
b3c518d
 
 
 
 
 
 
 
 
 
 
af171ba
b3c518d
 
 
 
5731e4a
 
af171ba
 
 
74706d1
 
af171ba
 
74706d1
 
 
 
 
 
5731e4a
 
 
74706d1
5731e4a
af171ba
5731e4a
 
 
 
 
 
 
 
 
74706d1
af171ba
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
63
64
65
66
67
68
import gradio as gr
import requests
import os

# Hugging Face API Token (Set in Hugging Face Spaces)
HF_API_TOKEN = os.getenv("HF_API_TOKEN")

# Hugging Face Model API Endpoints
MODEL_ENDPOINTS = {
    "Hindi": "https://api-inference.huggingface.co/models/LingoIITGN/mBERT_toxic_hindi",
    "Telugu": "https://api-inference.huggingface.co/models/LingoIITGN/mBERT_toxic_telugu"
}

# Function to get toxicity prediction
def get_toxicity_prediction(text, language):
    if language not in MODEL_ENDPOINTS:
        return "Error: Model not found for the selected language"

    url = MODEL_ENDPOINTS[language]
    headers = {
        "Authorization": f"Bearer {HF_API_TOKEN}",
        "Content-Type": "application/json"
    }

    payload = {
        "inputs": text,
        "parameters": {
            "return_all_scores": True
        },
        "options": {
            "wait_for_model": True  # Helps avoid cold start failures
        }
    }

    response = requests.post(url, headers=headers, json=payload)

    if response.status_code == 200:
        predictions = response.json()[0]  # Extract first result
        
        # Convert scores to percentage and map to labels
        toxicity_score = None
        for pred in predictions:
            if pred["label"] == "toxic":
                toxicity_score = pred["score"] * 100  # Convert to %
                break

        if toxicity_score is not None:
            return f"Toxicity Score: {toxicity_score:.2f}%\nClassification: Toxic"
        else:
            return "Classification: Non-Toxic"
    else:
        return f"Error: {response.text}"

# Gradio Interface
with gr.Blocks() as app:
    gr.Markdown("# 🛡️ ToxiGuard - Hindi & Telugu Toxicity Detection")
    
    text_input = gr.Textbox(label="Enter your text")
    language_dropdown = gr.Dropdown(choices=["Hindi", "Telugu"], label="Select Language", value="Hindi")
    
    submit_button = gr.Button("Check Toxicity")
    output_text = gr.Textbox(label="Result")

    submit_button.click(fn=get_toxicity_prediction, inputs=[text_input, language_dropdown], outputs=output_text)

# Launch the Gradio app
app.launch(server_name="0.0.0.0", server_port=7860)