Sari20 commited on
Commit
5c525be
·
verified ·
1 Parent(s): b5e44f9

สร้าง app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -0
app.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import torch
4
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
5
+
6
+ id2label = {0: 'anger', 1: 'anticipation', 2: 'disgust', 3: 'fear', 4: 'joy', 5: 'love', 6: 'optimism', 7: 'pessimism', 8: 'sadness', 9: 'surprise', 10: 'trust'}
7
+ tokenizer = AutoTokenizer.from_pretrained("winain7788/bert-finetuned-sem_eval-english")
8
+ model = AutoModelForSequenceClassification.from_pretrained("winain7788/bert-finetuned-sem_eval-english")
9
+
10
+ async def get_sentiment(text):
11
+ encoding = tokenizer(text, return_tensors="pt")
12
+ encoding = {k: v.to(model.device) for k,v in encoding.items()}
13
+
14
+ outputs = model(**encoding)
15
+ logits = outputs.logits
16
+ logits.shape
17
+ # apply sigmoid + threshold
18
+ sigmoid = torch.nn.Sigmoid()
19
+ probs = sigmoid(logits.squeeze().cpu())
20
+ predictions = np.zeros(probs.shape)
21
+ predictions[np.where(probs >= 0.5)] = 1
22
+
23
+ # turn predicted id's into actual label names
24
+ predicted_labels = [id2label[idx] for idx, label in enumerate(predictions) if label == 1.0]
25
+ return predicted_labels
26
+
27
+ demo = gr.Interface(fn=get_sentiment, inputs="text", outputs="json")
28
+
29
+ demo.launch()