sundea commited on
Commit
e43d2e0
·
1 Parent(s): 06477d9

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +187 -0
app.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ from importlib import import_module
4
+
5
+ import gradio as gr
6
+ from tqdm import tqdm
7
+ import models.TextCNN
8
+ import torch
9
+ import pickle as pkl
10
+ from utils import build_dataset
11
+
12
+ classes = ['finance', 'realty', 'stocks', 'education', 'science', 'society', 'politics', 'sports', 'game',
13
+ 'entertainment']
14
+
15
+ MAX_VOCAB_SIZE = 10000 # 词表长度限制
16
+ UNK, PAD = '<UNK>', '<PAD>' # 未知字,padding符号
17
+
18
+
19
+ def build_vocab(file_path, tokenizer, max_size, min_freq):
20
+ vocab_dic = {}
21
+ with open(file_path, 'r', encoding='UTF-8') as f:
22
+ for line in tqdm(f):
23
+ lin = line.strip()
24
+ if not lin:
25
+ continue
26
+ content = lin.split('\t')[0]
27
+ for word in tokenizer(content):
28
+ vocab_dic[word] = vocab_dic.get(word, 0) + 1
29
+ vocab_list = sorted([_ for _ in vocab_dic.items() if _[1] >= min_freq], key=lambda x: x[1], reverse=True)[
30
+ :max_size]
31
+ vocab_dic = {word_count[0]: idx for idx, word_count in enumerate(vocab_list)}
32
+ vocab_dic.update({UNK: len(vocab_dic), PAD: len(vocab_dic) + 1})
33
+ return vocab_dic
34
+
35
+
36
+ # parser = argparse.ArgumentParser(description='Chinese Text Classification')
37
+ # parser.add_argument('--word', default=False, type=bool, help='True for word, False for char')
38
+ # args = parser.parse_args()
39
+ # model_name = 'TextCNN'
40
+ # dataset = 'THUCNews' # 数据集
41
+ # embedding = 'embedding_SougouNews.npz'
42
+ # x = import_module('models.' + model_name)
43
+ #
44
+ # config = x.Config(dataset, embedding)
45
+ # device = 'cuda:0'
46
+ # model = models.TextCNN.Model(config)
47
+ #
48
+ # # vocab, train_data, dev_data, test_data = build_dataset(config, args.word)
49
+ # model.load_state_dict(torch.load('THUCNews/saved_dict/TextCNN.ckpt'))
50
+ # model.to(device)
51
+ # model.eval()
52
+ #
53
+ # tokenizer = lambda x: [y for y in x] # char-level
54
+ # if os.path.exists(config.vocab_path):
55
+ # vocab = pkl.load(open(config.vocab_path, 'rb'))
56
+ # else:
57
+ # vocab = build_vocab(config.train_path, tokenizer=tokenizer, max_size=MAX_VOCAB_SIZE, min_freq=1)
58
+ # pkl.dump(vocab, open(config.vocab_path, 'wb'))
59
+ # print(f"Vocab size: {len(vocab)}")
60
+ #
61
+ # # content='时评:“国学小天才”录取缘何少佳话'
62
+ # content = input('输入语句:')
63
+ #
64
+ # words_line = []
65
+ # token = tokenizer(content)
66
+ # seq_len = len(token)
67
+ # pad_size = 32
68
+ # contents = []
69
+ #
70
+ # if pad_size:
71
+ # if len(token) < pad_size:
72
+ # token.extend([PAD] * (pad_size - len(token)))
73
+ # else:
74
+ # token = token[:pad_size]
75
+ # seq_len = pad_size
76
+ # # word to id
77
+ # for word in token:
78
+ # words_line.append(vocab.get(word, vocab.get(UNK)))
79
+ #
80
+ # contents.append((words_line, seq_len))
81
+ # print(words_line)
82
+ # # input = torch.LongTensor(words_line).unsqueeze(1).to(device) # convert words_line to LongTensor and add batch dimension
83
+ # x = torch.LongTensor([_[0] for _ in contents]).to(device)
84
+ #
85
+ # # pad前的长度(超过pad_size的设为pad_size)
86
+ # seq_len = torch.LongTensor([_[1] for _ in contents]).to(device)
87
+ # input = (x, seq_len)
88
+ # # print(input)
89
+ # with torch.no_grad():
90
+ # output = model(input)
91
+ # predic = torch.max(output.data, 1)[1].cpu().numpy()
92
+ # print(predic)
93
+ # print('类别为:{}'.format(classes[predic[0]]))
94
+
95
+
96
+
97
+
98
+ def greet(text):
99
+ parser = argparse.ArgumentParser(description='Chinese Text Classification')
100
+ parser.add_argument('--word', default=False, type=bool, help='True for word, False for char')
101
+ args = parser.parse_args()
102
+ model_name = 'TextCNN'
103
+ dataset = 'THUCNews' # 数据集
104
+ embedding = 'embedding_SougouNews.npz'
105
+ x = import_module('models.' + model_name)
106
+
107
+ config = x.Config(dataset, embedding)
108
+ device = 'cuda:0'
109
+ model = models.TextCNN.Model(config)
110
+
111
+ # vocab, train_data, dev_data, test_data = build_dataset(config, args.word)
112
+ model.load_state_dict(torch.load('THUCNews/saved_dict/TextCNN.ckpt'))
113
+ model.to(device)
114
+ model.eval()
115
+
116
+ tokenizer = lambda x: [y for y in x] # char-level
117
+ if os.path.exists(config.vocab_path):
118
+ vocab = pkl.load(open(config.vocab_path, 'rb'))
119
+ else:
120
+ vocab = build_vocab(config.train_path, tokenizer=tokenizer, max_size=MAX_VOCAB_SIZE, min_freq=1)
121
+ pkl.dump(vocab, open(config.vocab_path, 'wb'))
122
+ # print(f"Vocab size: {len(vocab)}")
123
+
124
+ # content='时评:“国学小天才”录取缘何少佳话'
125
+ content = text
126
+
127
+ words_line = []
128
+ token = tokenizer(content)
129
+ seq_len = len(token)
130
+ pad_size = 32
131
+ contents = []
132
+
133
+ if pad_size:
134
+ if len(token) < pad_size:
135
+ token.extend([PAD] * (pad_size - len(token)))
136
+ else:
137
+ token = token[:pad_size]
138
+ seq_len = pad_size
139
+ # word to id
140
+ for word in token:
141
+ words_line.append(vocab.get(word, vocab.get(UNK)))
142
+
143
+ contents.append((words_line, seq_len))
144
+ # print(words_line)
145
+ # input = torch.LongTensor(words_line).unsqueeze(1).to(device) # convert words_line to LongTensor and add batch dimension
146
+ x = torch.LongTensor([_[0] for _ in contents]).to(device)
147
+
148
+ # pad前的长度(超过pad_size的设为pad_size)
149
+ seq_len = torch.LongTensor([_[1] for _ in contents]).to(device)
150
+ input = (x, seq_len)
151
+ # print(input)
152
+ with torch.no_grad():
153
+ output = model(input)
154
+ predic = torch.max(output.data, 1)[1].cpu().numpy()
155
+ # print(predic)
156
+ # print('类别为:{}'.format(classes[predic[0]]))
157
+ return classes[predic[0]]
158
+ #
159
+ demo = gr.Interface(fn=greet, inputs="text", outputs="text")
160
+
161
+ demo.launch(server_port=9090)
162
+ # with torch.no_grad():
163
+ # output=model(input)
164
+ # print(output)
165
+
166
+ #
167
+ # start_time = time.time()
168
+ # test_iter = build_iterator(test_data, config)
169
+ # with torch.no_grad():
170
+ # predict_all = np.array([], dtype=int)
171
+ # labels_all = np.array([], dtype=int)
172
+ # for texts, labels in test_iter:
173
+ # # texts=texts.to(device)
174
+ # print(texts)
175
+ # outputs = model(texts)
176
+ # loss = F.cross_entropy(outputs, labels)
177
+ # labels = labels.data.cpu().numpy()
178
+ # predic = torch.max(outputs.data, 1)[1].cpu().numpy()
179
+ # labels_all = np.append(labels_all, labels)
180
+ # predict_all = np.append(predict_all, predic)
181
+ # break
182
+ # print(labels_all)
183
+ # print(predict_all)
184
+ #
185
+ #
186
+
187
+