kevin-yang commited on
Commit
f1e343a
·
1 Parent(s): b1944b2

initial commit

Browse files
Files changed (1) hide show
  1. app.py +97 -0
app.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoConfig
2
+ import gradio as gr
3
+ from torch.nn import functional as F
4
+ import seaborn
5
+
6
+ import matplotlib
7
+ import platform
8
+
9
+ if platform.system() == "Darwin":
10
+ print("MacOS")
11
+ matplotlib.use('Agg')
12
+ import matplotlib.pyplot as plt
13
+ import io
14
+ from PIL import Image
15
+
16
+ import matplotlib.font_manager as fm
17
+
18
+
19
+
20
+
21
+ import util
22
+
23
+ font_path = r'NanumGothicCoding.ttf'
24
+ fontprop = fm.FontProperties(fname=font_path, size=18)
25
+
26
+ plt.rcParams["font.family"] = 'NanumGothic'
27
+
28
+
29
+ def visualize_attention(sent, attention_matrix, n_words=10):
30
+ def draw(data, x, y, ax):
31
+ seaborn.heatmap(data,
32
+ xticklabels=x, square=True, yticklabels=y, vmin=0.0, vmax=1.0,
33
+ cbar=False, ax=ax)
34
+
35
+ # make plt figure with 1x6 subplots
36
+ fig = plt.figure(figsize=(16, 8))
37
+ # fig.subplots_adjust(hspace=0.7, wspace=0.2)
38
+ for i, layer in enumerate(range(1, 12, 2)):
39
+ ax = fig.add_subplot(2, 3, i+1)
40
+ ax.set_title("Layer {}".format(layer))
41
+ draw(attention_matrix[layer], sent if layer > 6 else [], sent if layer in [1,7] else [], ax=ax)
42
+
43
+ fig.tight_layout()
44
+ plt.close()
45
+
46
+ return fig
47
+
48
+
49
+
50
+ def predict(model_name, text):
51
+
52
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
53
+ model = AutoModelForSequenceClassification.from_pretrained(model_name)
54
+ config = AutoConfig.from_pretrained(model_name)
55
+ print(config.id2label)
56
+
57
+ tokenized_text = tokenizer([text], return_tensors='pt')
58
+
59
+ input_tokens = tokenizer.convert_ids_to_tokens(tokenized_text.input_ids[0])
60
+ print(input_tokens)
61
+ input_tokens = util.bytetokens_to_unicdode(input_tokens) if config.model_type in ['roberta', 'gpt', 'gpt2'] else input_tokens
62
+
63
+ model.eval()
64
+ output, attention = model(**tokenized_text, output_attentions=True, return_dict=False)
65
+ output = F.softmax(output, dim=-1)
66
+ result = {}
67
+
68
+ for idx, label in enumerate(output[0].detach().numpy()):
69
+ result[config.id2label[idx]] = float(label)
70
+
71
+ fig = visualize_attention(input_tokens, attention[0][0].detach().numpy())
72
+ return result, fig#.logits.detach()#.numpy()#, output.attentions.detach().numpy()
73
+
74
+
75
+ if __name__ == '__main__':
76
+
77
+ model_name = 'jason9693/SoongsilBERT-beep-base'
78
+ text = '읿딴걸 홍볿글 읿랉곭 쌑젩낄고 앉앟있냩'
79
+ # output = predict(model_name, text)
80
+
81
+ # print(output)
82
+
83
+ model_name_list = [
84
+ 'jason9693/SoongsilBERT-beep-base'
85
+ ]
86
+
87
+ #Create a gradio app with a button that calls predict()
88
+ app = gr.Interface(
89
+ fn=predict,
90
+ server_port=26899,
91
+ server_name='0.0.0.0',
92
+ inputs=[gr.inputs.Dropdown(model_name_list, label="Model Name"), 'text'], outputs=['label', 'plot'],
93
+ examples = [[model_name, text]],
94
+ title="한국어 혐오성 발화 분류기 (Korean Hate Speech Classifier)",
95
+ description="Korean Hate Speech Classifier with Several Pretrained LM\nCurrent Supported Model:\n1. SoongsilBERT"
96
+ )
97
+ app.launch(inline=False)