Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,3 +1,39 @@
|
|
1 |
import gradio as gr
|
|
|
|
|
2 |
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
import torch
|
3 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
4 |
|
5 |
+
# Load pre-trained model and tokenizer
|
6 |
+
model_name = "KoalaAI/Text-Moderation"
|
7 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
8 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
9 |
+
|
10 |
+
# Get labels from the model's config
|
11 |
+
labels = list(model.config.id2label.values())
|
12 |
+
|
13 |
+
def classify_text(text):
|
14 |
+
# Tokenize input
|
15 |
+
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512)
|
16 |
+
|
17 |
+
# Get prediction
|
18 |
+
with torch.no_grad():
|
19 |
+
outputs = model(**inputs)
|
20 |
+
predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
|
21 |
+
|
22 |
+
# Format results
|
23 |
+
results = {labels[i]: float(predictions[0][i]) for i in range(len(labels))}
|
24 |
+
|
25 |
+
return results
|
26 |
+
|
27 |
+
# Create Gradio interface
|
28 |
+
demo = gr.Interface(
|
29 |
+
fn=classify_text,
|
30 |
+
inputs=gr.Textbox(placeholder="Enter text to classify...", lines=5),
|
31 |
+
outputs=gr.Label(num_top_classes=len(labels)),
|
32 |
+
title="KoalaAI - Text-Moderation Demo",
|
33 |
+
description="This model determines whether or not there is potentially harmful content in a given text",
|
34 |
+
theme=gr.themes.Soft()
|
35 |
+
)
|
36 |
+
|
37 |
+
# Launch app
|
38 |
+
if __name__ == "__main__":
|
39 |
+
demo.launch()
|