jingwora commited on
Commit
7989e87
1 Parent(s): 6f85527

Add application file

Browse files
Files changed (2) hide show
  1. app.py +66 -0
  2. requirements.txt +4 -0
app.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import gradio as gr
3
+ import numpy as np
4
+ import torch
5
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification
6
+ from transformers import pipeline
7
+
8
+ emotion_labels = ['喜び', '悲しみ', '期待', '驚き', '怒り', '信頼', '悲しみ', '嫌悪']
9
+ sentiment_labels = ['ポジティブ', 'ニュートラル', 'ネガティブ']
10
+
11
+ def np_softmax(x):
12
+ x_exp = torch.exp(torch.tensor(x) - torch.max(torch.tensor(x)))
13
+ f_x = x_exp / x_exp.sum()
14
+ return f_x
15
+
16
+ def emotion_classifier(text):
17
+ model.eval()
18
+ tokens = tokenizer(text, truncation=True, return_tensors="pt")
19
+ tokens.to(model.device)
20
+ preds = model(**tokens)
21
+ prob = np_softmax(preds.logits.cpu().detach().numpy()[0])
22
+ out_dict = {n: p.item() for n, p in zip(emotion_labels, prob)}
23
+ return out_dict
24
+
25
+ tokenizer = AutoTokenizer.from_pretrained("cl-tohoku/bert-base-japanese-whole-word-masking")
26
+ model = AutoModelForSequenceClassification.from_pretrained("jingwora/language-emotion-classification-ja", num_labels=8)
27
+
28
+ def sentiment_classifier(text):
29
+ clf = pipeline(model="lxyuan/distilbert-base-multilingual-cased-sentiments-student", return_all_scores=True)
30
+ sentiment = clf(text)
31
+ sentiment = {item['label']: item['score'] for item in sentiment[0]}
32
+ sentiment = {sentiment_labels[i]: sentiment[label] for i, label in enumerate(sentiment)} # 日本語ラベル
33
+ return sentiment
34
+
35
+ examples = [
36
+ ["このお店は本当に素晴らしいです!サービスも料理も満足できるものばかりでした。"],
37
+ ["料理の味が期待外れでした。改善が必要ですね。"],
38
+ ["サービスは普通ですが、特に不満もありません。"],
39
+ ["価格と品質のバランスが取れていると思います。"],
40
+ ]
41
+
42
+
43
+ demo = gr.Blocks(
44
+ theme="freddyaboulton/dracula_revamped",
45
+ )
46
+
47
+ with demo:
48
+ gr.Markdown(
49
+ """
50
+ # Emotion and Sentiment Classification
51
+ Enter Japanese text and get the emotion probabilities and sentiment probablilities.
52
+ """
53
+ )
54
+ text = gr.Textbox(lines=2)
55
+ with gr.Row():
56
+ gr.Examples(examples=examples, inputs=text)
57
+
58
+ b1 = gr.Button("Emotion Classification")
59
+ label1 = gr.Label(num_top_classes=8)
60
+ b1.click(emotion_classifier, inputs=text, outputs=label1)
61
+
62
+ b2 = gr.Button("Sentiment Analysis")
63
+ label2 = gr.Label(num_top_classes=3)
64
+ b2.click(sentiment_classifier, inputs=text, outputs=label2)
65
+
66
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+
2
+ gradio==3.36.1
3
+ transformers==4.30.2
4
+ torch==2.0.1