Spaces:
Sleeping
Sleeping
kietnt0603
commited on
Commit
•
bc189c6
1
Parent(s):
b666afb
Update app.py
Browse files
app.py
CHANGED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
3 |
+
import torch
|
4 |
+
import numpy as np
|
5 |
+
|
6 |
+
# Load the model and tokenizer
|
7 |
+
model = AutoModelForSequenceClassification.from_pretrained('kietnt0603/bertweet-base-hate-speech-offensive')
|
8 |
+
tokenizer = AutoTokenizer.from_pretrained('kietnt0603/bertweet-base-hate-speech-offensive')
|
9 |
+
|
10 |
+
# Define the labels
|
11 |
+
labels = ["Hate", "Offensive", "Neither"]
|
12 |
+
|
13 |
+
# Function for prediction
|
14 |
+
def predict(inputs: str) -> Dict[str, Any]:
|
15 |
+
# Tokenize input text
|
16 |
+
inputs_dict = tokenizer(inputs, return_tensors="pt")
|
17 |
+
|
18 |
+
# Forward pass
|
19 |
+
with torch.no_grad():
|
20 |
+
outputs = model(**inputs_dict)
|
21 |
+
|
22 |
+
# Softmax to get probabilities
|
23 |
+
probabilities = torch.nn.functional.softmax(outputs.logits, dim=1)
|
24 |
+
|
25 |
+
# Get probabilities for each label
|
26 |
+
label_probabilities = {label: round(prob.item(), 4) for label, prob in zip(labels, probabilities[0].tolist())}
|
27 |
+
|
28 |
+
# Return the result
|
29 |
+
return label_probabilities
|
30 |
+
|
31 |
+
# Create title and description for the task
|
32 |
+
title = "Text Classification Demo"
|
33 |
+
description = "Classify text into categories: Hate, Offensive, Neither"
|
34 |
+
article = "Model loaded from https://huggingface.co/kietnt0603/bertweet-base-hate-speech-offensive"
|
35 |
+
|
36 |
+
# Create the Gradio interface
|
37 |
+
iface = gr.Interface(fn=predict,
|
38 |
+
inputs="textbox",
|
39 |
+
outputs="dictionary",
|
40 |
+
title=title,
|
41 |
+
description=description,
|
42 |
+
article=article)
|
43 |
+
|
44 |
+
# Launch the interface
|
45 |
+
iface.launch()
|