Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import AutoTokenizer,AutoModelForSequenceClassification,Trainer,TrainingArguments
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from datasets import load_dataset
|
| 5 |
+
labels = {
|
| 6 |
+
'Negative':0,
|
| 7 |
+
'Positive':1,
|
| 8 |
+
'Neutral':2,
|
| 9 |
+
'Irrelevant':3,
|
| 10 |
+
}
|
| 11 |
+
model_name = 'distilbert-base-uncased'
|
| 12 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 13 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_name,num_labels=4)
|
| 14 |
+
# Set up device
|
| 15 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 16 |
+
model.to(device)
|
| 17 |
+
# create function to predict sentence
|
| 18 |
+
def pre_sentiment(sentence):
|
| 19 |
+
model.eval()
|
| 20 |
+
inputs = tokenizer(sentence,return_tensors='pt',truncation=True,padding=True)
|
| 21 |
+
inputs = {k:v.to(device) for k,v in inputs.items()}
|
| 22 |
+
with torch.no_grad():
|
| 23 |
+
outputs = model(**inputs)
|
| 24 |
+
probs = F.softmax(outputs.logits,dim=-1)
|
| 25 |
+
pre = torch.argmax(probs,dim=-1).item()
|
| 26 |
+
score = torch.max(probs).item()
|
| 27 |
+
inv_label = {v:k for k,v in labels.items()}
|
| 28 |
+
result = inv_label.get(pre,'Unknown')
|
| 29 |
+
return result
|
| 30 |
+
# create UI/UX
|
| 31 |
+
import gradio as gr
|
| 32 |
+
|
| 33 |
+
demo = gr.Interface(fn=pre_sentiment,inputs='text',outputs='text',title='Predict Sentiment')
|
| 34 |
+
demo.launch()
|