Sirapatrwan commited on
Commit
bfe5bd7
·
verified ·
1 Parent(s): 46b225e

Add emotion detection

Browse files
Files changed (1) hide show
  1. emotion_detection.py +74 -0
emotion_detection.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
2
+ from transformers_interpret import SequenceClassificationExplainer
3
+ import torch
4
+ import pandas as pd
5
+
6
+
7
+ class EmotionDetection:
8
+ """
9
+ Emotion Detection on text data.
10
+
11
+ Attributes:
12
+ tokenizer: An instance of Hugging Face Tokenizer
13
+ model: An instance of Hugging Face Model
14
+ explainer: An instance of SequenceClassificationExplainer from Transformers interpret
15
+ """
16
+
17
+ def __init__(self):
18
+ hub_location = 'cardiffnlp/twitter-roberta-base-emotion'
19
+ self.tokenizer = AutoTokenizer.from_pretrained(hub_location)
20
+ self.model = AutoModelForSequenceClassification.from_pretrained(hub_location)
21
+ self.explainer = SequenceClassificationExplainer(self.model, self.tokenizer)
22
+
23
+ def justify(self, text):
24
+ """
25
+ Get html annotation for displaying emotion justification over text.
26
+
27
+ Parameters:
28
+ text (str): The user input string to emotion justification
29
+
30
+ Returns:
31
+ html (hmtl): html object for plotting emotion prediction justification
32
+ """
33
+
34
+ word_attributions = self.explainer(text)
35
+ html = self.explainer.visualize("example.html")
36
+
37
+ return html
38
+
39
+ def classify(self, text):
40
+ """
41
+ Recognize Emotion in text.
42
+
43
+ Parameters:
44
+ text (str): The user input string to perform emotion classification on
45
+
46
+ Returns:
47
+ predictions (str): The predicted probabilities for emotion classes
48
+ """
49
+
50
+ tokens = self.tokenizer.encode_plus(text, add_special_tokens=False, return_tensors='pt')
51
+ outputs = self.model(**tokens)
52
+ probs = torch.nn.functional.softmax(outputs[0], dim=-1)
53
+ probs = probs.mean(dim=0).detach().numpy()
54
+ labels = list(self.model.config.id2label.values())
55
+ preds = pd.Series(probs, index=labels, name='Predicted Probability')
56
+
57
+ return preds
58
+
59
+ def run(self, text):
60
+ """
61
+ Classify and Justify Emotion in text.
62
+
63
+ Parameters:
64
+ text (str): The user input string to perform emotion classification on
65
+
66
+ Returns:
67
+ predictions (str): The predicted probabilities for emotion classes
68
+ html (hmtl): html object for plotting emotion prediction justification
69
+ """
70
+
71
+ preds = self.classify(text)
72
+ html = self.justify(text)
73
+
74
+ return preds, html