winain7788 commited on
Commit
5412a97
·
1 Parent(s): 67bdbbf
Files changed (1) hide show
  1. app.py +20 -7
app.py CHANGED
@@ -1,15 +1,28 @@
1
  import gradio as gr
 
2
  import torch
3
- from transformers import pipeline
4
 
5
- device = 0 if torch.cuda.is_available() else -1
6
-
7
- sentiment_pipeline = pipeline("text-classification",
8
- model="winain7788/bert-finetuned-sem_eval-english",
9
- device=device)
10
 
11
  async def get_sentiment(text):
12
- return sentiment_pipeline([text])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  demo = gr.Interface(fn=get_sentiment, inputs="text", outputs="json")
15
 
 
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