File size: 1,382 Bytes
05086cb
7d31ef5
 
05086cb
7d31ef5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcb5ec6
 
 
aa651cc
 
7d31ef5
 
 
 
 
 
aa651cc
7d31ef5
 
 
 
 
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
import gradio as gr
import torch
from transformers import AutoTokenizer, AutoModelForSequenceClassification

# Load pre-trained model and tokenizer
model_name = "KoalaAI/Text-Moderation"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)

# Get labels from the model's config
labels = list(model.config.id2label.values())

def classify_text(text):
    # Tokenize input
    inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512)
    
    # Get prediction
    with torch.no_grad():
        outputs = model(**inputs)
        predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
        
    # Format results
    results = {labels[i]: float(predictions[0][i]) for i in range(len(labels))}
    
    return results

# Create Gradio interface
custom_theme = gr.themes.Soft(
    primary_hue=gr.themes.colors.green,
    secondary_hue=gr.themes.colors.emerald,
)

demo = gr.Interface(
    fn=classify_text,
    inputs=gr.Textbox(placeholder="Enter text to classify...", lines=5),
    outputs=gr.Label(num_top_classes=len(labels)),
    title="KoalaAI - Text-Moderation Demo",
    description="This model determines whether or not there is potentially harmful content in a given text",
    theme=custom_theme
)

# Launch app
if __name__ == "__main__":
    demo.launch()