-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathweb_demo.py
More file actions
822 lines (617 loc) ยท 33.1 KB
/
web_demo.py
File metadata and controls
822 lines (617 loc) ยท 33.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
#!/usr/bin/env python
# coding: utf-8
# from model.tiny_transformer import *
from utils import *
from dataloader import *
#import pickle5 as pickle
import pickle
import pandas as pd
from prerequisite import *
from preprocess import *
from torch.utils.data import Dataset
from prerequisite import *
from transformers import BertConfig
import math
import os
import warnings
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union
import torch
import torch.utils.checkpoint
from packaging import version
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from transformers import BertTokenizer, BertPreTrainedModel, BertModel#,
from transformers.models.bert.modeling_bert import BertPreTrainingHeads
import gradio as gr
import argparse
parser = argparse.ArgumentParser(description='Script of Brid call')
parser.add_argument('--gpu', '-gpu', type=str, default='0', help='gpu')
parser.add_argument('--hidden_layer', '-hl', type=int, default=12)
parser.add_argument('--hidden_size', '-hs', type=int, default=768)
parser.add_argument('--intermediate_size', '-is', type=int, default=3072)
parser.add_argument('--model_pth_name', '-mp', type=str, default="./saved_models/n4_h252_i_1024_head_12_kobert_exp-gradio/best_model.pth" )
parser.add_argument('--num_decoder_layer', '-ndl', type=int, default=1)
parser.add_argument('--decoder_head', '-dh', type=int, default=12)
args = parser.parse_args()
class config:
# ---- factor ---- #
debug = False
full_cv = False
mode = 'train'
gpu = args.gpu
dropout = 0.1
heads = args.decoder_head # 4
encoder_layers = args.num_decoder_layer
decoder_layers = args.num_decoder_layer
d_model = 768
d_ff = 1024 # 256
batch_size = 1
embedding = 'bert' # ['bert','roberta']
emb_name = 'monologg/kobert'
mawps_vocab = True
max_length = 50 # 30
vocab_size = 30000 # 30000
init_range = 0.08 # 'Initialization range for seq2seq model'
freeze_emb = True
# -- encoder -- #
num_hidden_layers = args.hidden_layer
hidden_size = args.hidden_size #768#252
intermediate_size = args.intermediate_size #3072#786
model_path = args.model_pth_name
# ---- Else ---- #
num_workers = 8
seed = 92
os.environ["CUDA_VISIBLE_DEVICES"] = config.gpu
def build_model(config, voc1, voc2, device, teacher=False):
"""
Args:
config (dict): command line arguments
voc1 (object of class Voc1): vocabulary of source
voc2 (object of class Voc2): vocabulary of target
device (torch.device): GPU device
Returns:
model (object of class TransformerModel): model
"""
model = TransformerModel(config, voc1, voc2, device, teacher=teacher)
model = model.to(device)
# print(f"model parameters: {sum(p.numel() for p in model.parameters() if p.requires_grad)}")
print(f"model parameters: {sum(p.numel() for p in model.parameters())}")
return model
class TinyBertForPreTraining(BertPreTrainedModel):
def __init__(self, config, fit_size=768):
super(TinyBertForPreTraining, self).__init__(config)
self.bert = BertModel(config, add_pooling_layer=True)
self.cls = BertPreTrainingHeads(config)#, self.bert.embeddings.word_embeddings.weight)
self.fit_dense = nn.Linear(config.hidden_size, fit_size)
#self.apply(self.init_bert_weights)
def forward(self, input_ids, token_type_ids=None,
attention_mask=None, masked_lm_labels=None,
next_sentence_label=None, labels=None):
outputs = self.bert(input_ids, token_type_ids, attention_mask, output_attentions=True)
sequence_output, att_output, pooled_output = outputs['last_hidden_state'], outputs['attentions'], outputs['pooler_output']
# ์ถ๊ฐ
prediction_logits, _ = self.cls(sequence_output, pooled_output)
#
tmp = []
for s_id, sequence_layer in enumerate(sequence_output):
tmp.append(self.fit_dense(sequence_layer))
sequence_output = tmp
return prediction_logits, att_output, sequence_output
# model
class BertEncoder(nn.Module):
def __init__(self, bert_model='bert-base-uncased', device='cuda', cfg=None, teacher=False, freeze_bert=False):
super(BertEncoder, self).__init__()
# self.bert_layer = TinyBertForPreTraining(BertConfig(num_hidden_layers=12,
# hidden_size=768,intermediate_size=3072)).from_pretrained(bert_model)
if teacher:
self.bert_layer = TinyBertForPreTraining(BertConfig(num_hidden_layers=12,
hidden_size=768, intermediate_size=3072)).from_pretrained(bert_model)
else: # student
self.bert_layer = TinyBertForPreTraining(BertConfig(num_hidden_layers=cfg.num_hidden_layers,
hidden_size=cfg.hidden_size,intermediate_size=cfg.intermediate_size,
num_attention_heads=cfg.heads))#.from_pretrained(bert_model)
#BertConfig(num_hidden_layers=4, hidden_size=252, intermediate_size=786)
#BertConfig(num_hidden_layers=12, hidden_size=768, intermediate_size=3072)
self.bert_tokenizer = BertTokenizer.from_pretrained(bert_model)
self.device = device
self.cfg = cfg
if freeze_bert:
for p in self.bert_layer.parameters():
p.requires_grad = False
def bertify_input(self, sentences):
'''
Preprocess the input sentences using bert tokenizer and converts them to a torch tensor containing token ids
Args:
sentences (list): source sentences
Returns:
token_ids (tensor): tokenized sentences | size: [BS x S]
attn_masks (tensor): masks padded indices | size: [BS x S]
input_lengths (list): lengths of sentences | size: [BS]
'''
# Tokenize the input sentences for feeding into BERT
all_tokens = [['[CLS]'] + self.bert_tokenizer.tokenize(sentence) + ['[SEP]'] for sentence in sentences]
# Pad all the sentences to a maximum length
input_lengths = [len(tokens) for tokens in all_tokens]
max_length = max(input_lengths)
max_length = self.cfg.max_length
padded_tokens = [tokens + ['[PAD]' for _ in range(max_length - len(tokens))] for tokens in all_tokens]
# Convert tokens to token ids
token_ids = torch.tensor([self.bert_tokenizer.convert_tokens_to_ids(tokens) for tokens in padded_tokens]).to(
self.device)
# Obtain attention masks
pad_token = self.bert_tokenizer.convert_tokens_to_ids('[PAD]')
attn_masks = (token_ids != pad_token).long()
return token_ids, attn_masks, input_lengths
def forward(self, sentences):
'''
Feed the batch of sentences to a BERT encoder to obtain contextualized representations of each token
Args:
sentences (list): source sentences
Returns:
cont_reps (tensor): BERT Embeddings | size: [BS x S x d_model]
token_ids (tensor): tokenized sentences | size: [BS x S]
'''
# Preprocess sentences
token_ids, attn_masks, input_lengths = self.bertify_input(sentences)
cont_reps, attn, seq = self.bert_layer(token_ids, attention_mask=attn_masks) # logit, attn, embedding
return cont_reps, attn, seq, token_ids
class RobertaEncoder(nn.Module):
def __init__(self, roberta_model='roberta-base', device='cuda:0 ', freeze_roberta=False):
super(RobertaEncoder, self).__init__()
# self.roberta_layer = RobertaModel.from_pretrained(roberta_model, return_dict=False)
# self.roberta_tokenizer = RobertaTokenizer.from_pretrained(roberta_model)
self.roberta_layer = AutoModel.from_pretrained(roberta_model)
self.roberta_tokenizer = AutoTokenizer.from_pretrained(roberta_model)
self.device = device
if freeze_roberta:
for p in self.roberta_layer.parameters():
p.requires_grad = False
def robertify_input(self, sentences):
'''
Preprocess the input sentences using roberta tokenizer and converts them to a torch tensor containing token ids
Args:
sentences (list): source sentences
Returns:
token_ids (tensor): tokenized sentences | size: [BS x S]
attn_masks (tensor): masks padded indices | size: [BS x S]
input_lengths (list): lengths of sentences | size: [BS]
'''
# Tokenize the input sentences for feeding into RoBERTa
all_tokens = [['<s>'] + self.roberta_tokenizer.tokenize(sentence) + ['</s>'] for sentence in sentences]
# Pad all the sentences to a maximum length
input_lengths = [len(tokens) for tokens in all_tokens]
max_length = max(input_lengths)
padded_tokens = [tokens + ['<pad>' for _ in range(max_length - len(tokens))] for tokens in all_tokens]
# Convert tokens to token ids
token_ids = torch.tensor([self.roberta_tokenizer.convert_tokens_to_ids(tokens) for tokens in padded_tokens]).to(
self.device)
# Obtain attention masks
pad_token = self.roberta_tokenizer.convert_tokens_to_ids('<pad>')
attn_masks = (token_ids != pad_token).long()
return token_ids, attn_masks, input_lengths
def forward(self, sentences):
'''
Feed the batch of sentences to a RoBERTa encoder to obtain contextualized representations of each token
Args:
sentences (list): source sentences
Returns:
cont_reps (tensor): RoBERTa Embeddings | size: [BS x S x d_model]
token_ids (tensor): tokenized sentences | size: [BS x S]
'''
# Preprocess sentences
token_ids, attn_masks, input_lengths = self.robertify_input(sentences)
# Feed through RoBERTa
cont_reps, _ = self.roberta_layer(token_ids, attention_mask=attn_masks).values()
return cont_reps, token_ids
class PositionalEncoding(nn.Module):
def __init__(self, d_model, dropout=0.1, max_len=5000):
super(PositionalEncoding, self).__init__()
self.dropout = nn.Dropout(p=dropout)
self.scale = nn.Parameter(torch.ones(1)) # nn.Parameter causes the tensor to appear in the model.parameters()
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) # max_len x 1
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (
-math.log(10000.0) / d_model)) # torch.arange(0, d_model, 2) gives 2i
pe[:, 0::2] = torch.sin(position * div_term) # all alternate columns 0 onwards
pe[:, 1::2] = torch.cos(position * div_term) # all alternate columns 1 onwards
pe = pe.unsqueeze(0).transpose(0, 1)
self.register_buffer('pe', pe)
def forward(self, x):
'''
Args:
x (tensor): embeddings | size : [max_len x batch_size x d_model]
Returns:
z (tensor) : embeddings with positional encoding | size : [max_len x batch_size x d_model]
'''
# print(x.shape)
# print(self.scale.shape)
# print(self.pe[:x.size(0), :].shape)
x = x[:, :, :768] + self.scale * self.pe[:x.size(0), :]
z = self.dropout(x)
return z
class TransformerModel(nn.Module):
def __init__(self, config, voc1, voc2, device,teacher, EOS_tag='</s>', SOS_tag='<s>'):
super(TransformerModel, self).__init__()
self.config = config
self.device = device
self.voc1 = voc1
self.voc2 = voc2
self.EOS_tag = EOS_tag
self.SOS_tag = SOS_tag
self.EOS_token = voc2.get_id(EOS_tag)
self.SOS_token = voc2.get_id(SOS_tag)
if self.config.embedding == 'bert':
config.d_model = 768
self.embedding1 = BertEncoder(self.config.emb_name, self.device, self.config, teacher,self.config.freeze_emb)
elif self.config.embedding == 'roberta':
config.d_model = 768
self.embedding1 = RobertaEncoder(self.config.emb_name, self.device, self.config.freeze_emb)
else:
self.embedding1 = nn.Embedding(self.voc1.nwords, self.config.d_model)
nn.init.uniform_(self.embedding1.weight, -1 * self.config.init_range, self.config.init_range)
self.pos_embedding1 = PositionalEncoding(self.config.d_model, self.config.dropout)
self.embedding2 = nn.Embedding(self.voc2.nwords, self.config.d_model)
nn.init.uniform_(self.embedding2.weight, -1 * self.config.init_range, self.config.init_range)
self.pos_embedding2 = PositionalEncoding(self.config.d_model, self.config.dropout)
self.transformer = nn.Transformer(d_model=self.config.d_model, nhead=self.config.heads,
num_encoder_layers=self.config.encoder_layers,
num_decoder_layers=self.config.decoder_layers,
dim_feedforward=self.config.d_ff, dropout=self.config.dropout)
self.fc_out = nn.Linear(self.config.d_model, self.voc2.nwords)
self.src_mask = None
self.trg_mask = None
self.memory_mask = None
def generate_square_subsequent_mask(self, sz):
'''
Args:
sz (integer): max_len of sequence in target without EOS i.e. (T-1)
Returns:
mask (tensor) : square mask | size : [T-1 x T-1]
'''
mask = torch.triu(torch.ones(sz, sz), 1)
mask = mask.masked_fill(mask == 1, float('-inf'))
return mask
def make_len_mask(self, inp):
'''
Args:
inp (tensor): input indices | size : [S x BS]
Returns:
mask (tensor) : pad mask | size : [BS x S]
'''
mask = (inp == -1).transpose(0, 1)
return mask
def forward(self, ques, src, trg):
'''
Args:
ques (list): raw source input | size : [BS]
src (tensor): source indices | size : [S x BS]
trg (tensor): target indices | size : [T x BS]
Returns:
output (tensor) : Network output | size : [T-1 x BS x voc2.nwords]
'''
if self.trg_mask is None or self.trg_mask.size(0) != len(trg):
self.trg_mask = self.generate_square_subsequent_mask(len(trg)).to(trg.device)
if self.config.embedding == 'bert' or self.config.embedding == 'roberta':
src, attn, seq_emb, src_tokens = self.embedding1(ques)
# print('train src shape:',src.shape)
src = src.transpose(0, 1)
# src: Tensor [S x BS x d_model]
src_pad_mask = self.make_len_mask(src_tokens.transpose(0, 1))
src = self.pos_embedding1(src)
else:
src_pad_mask = self.make_len_mask(src)
src = self.embedding1(src)
src = self.pos_embedding1(src)
trg_pad_mask = self.make_len_mask(trg)
trg = self.embedding2(trg)
trg = self.pos_embedding2(trg)
output = self.transformer(src, trg, src_mask=self.src_mask, tgt_mask=self.trg_mask,
memory_mask=self.memory_mask,
src_key_padding_mask=src_pad_mask, tgt_key_padding_mask=trg_pad_mask,
memory_key_padding_mask=src_pad_mask)
output = self.fc_out(output)
return output, src, attn, seq_emb
def greedy_decode(self, ques=None, input_seq1=None, input_seq2=None, input_len2=None, criterion=None,
validation=False):
'''
Args:
ques (list): raw source input | size : [BS]
input_seq1 (tensor): source indices | size : [S x BS]
input_seq2 (tensor): target indices | size : [T x BS]
input_len2 (list): lengths of targets | size: [BS]
validation (bool): whether validate
Returns:
if validation:
validation loss (float): Validation loss
decoded_words (list): predicted equations | size : [BS x target_len]
else:
decoded_words (list): predicted equations | size : [BS x target_len]
'''
with torch.no_grad():
loss = 0.0
if self.config.embedding == 'bert' or self.config.embedding == 'roberta':
src, _ , _, _= self.embedding1(ques)
src = src.transpose(0, 1)
# src: Tensor [S x BS x emb1_size]
memory = self.transformer.encoder(self.pos_embedding1(src))
# print('memory:',memory.shape)
else:
memory = self.embedding1(input_seq1)
memory = self.transformer.encoder(self.pos_embedding1(memory))
# memory: S x BS x d_model
input_list = [[self.SOS_token for i in range(input_seq1.size(1))]]
decoded_words = [[] for i in range(input_seq1.size(1))]
if validation:
target_len = max(input_len2)
else:
target_len = self.config.max_length
for step in range(target_len):
decoder_input = torch.LongTensor(input_list).to(self.device) # seq_len x bs
decoder_output = self.fc_out(
self.transformer.decoder(self.pos_embedding2(self.embedding2(decoder_input)),
memory)) # seq_len x bs x voc2.nwords
if validation:
loss += criterion(decoder_output[-1, :, :], input_seq2[step])
out_tokens = decoder_output.argmax(2)[-1, :] # bs
for i in range(input_seq1.size(1)):
if out_tokens[i].item() == self.EOS_token:
continue
decoded_words[i].append(self.voc2.get_word(out_tokens[i].item()))
input_list.append(out_tokens.detach().tolist())
if validation:
return loss / target_len, decoded_words
else:
return decoded_words
def sim_forward(self, ques=None, input_seq1=None):
with torch.no_grad():
loss = 0.0
if self.config.embedding == 'bert' or self.config.embedding == 'roberta':
src, _ = self.embedding1(ques)
src = src.transpose(0, 1)
# src: Tensor [S x BS x emb1_size]
memory = self.transformer.encoder(self.pos_embedding1(src))
else:
memory = self.transformer.encoder(self.pos_embedding1(self.embedding1(input_seq1)))
# memory: S x BS x d_model
input_list = [[self.SOS_token for i in range(input_seq1.size(1))]]
decoded_words = [[] for i in range(input_seq1.size(1))]
target_len = self.config.max_length
for step in range(target_len):
decoder_input = torch.LongTensor(input_list).to(self.device) # seq_len x bs
decoder_output = self.fc_out(
self.transformer.decoder(self.pos_embedding2(self.embedding2(decoder_input)),
memory)) # seq_len x bs x voc2.nwords
out_tokens = decoder_output.argmax(2)[-1, :] # bs
for i in range(input_seq1.size(1)):
if out_tokens[i].item() == self.EOS_token:
continue
decoded_words[i].append(self.voc2.get_word(out_tokens[i].item()))
input_list.append(out_tokens.detach().tolist())
return decoded_words
# In[ ]:
###############๋ฐ์ดํฐ ์์๋ฐ๊พธ๊ธฐ์ํด#####################################################
# ์ด๋ฆ๋ค ์ ๋ถ name0~ ์ด๋ฐ์์ผ๋ก ๋ฐ๊พธ๊ธฐ
name_ = ['๋ฏผ์', '์ ๋', '์ ๊ตญ', '์ ์ ', 'ํํ', '๋จ์ค', '์ค๊ธฐ', 'ํธ์', '์ง๋ฏผ', '์์ง', '์์ง',
'๋ํฌ', '์๋ณ', '์ง๋ฒ', '๋ฏผํ', '๊ด์', '์ฌ์', '์งํจ', '์ฏ์', '์ฏ์', 'ํ์ค', '์ง์', '์ง์', '๊ฑด์ฐ', '์ก์ฐฌ',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'N', 'M', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V',
'W', 'X', 'Y', 'Z',
'\(๊ฐ\)', '\(๋\)', '\(๋ค\)', '\(๋ผ\)', '\(๋ง\)', '\(๋ฐ\)', '\(์ฌ\)', '\(์\)', '\(์\)', '\(์ฐจ\)', '\(์นด\)', '\(ํ\)',
'\(ํ\)', '\(ํ\)'
'์์์ผ', 'ํ์์ผ', '์์์ผ', '๋ชฉ์์ผ', '๊ธ์์ผ', 'ํ ์์ผ', '์ผ์์ผ',
'๋๊ตฌ๊ณต', '๋ฐฐ๊ตฌ๊ณต', 'ํ
๋์ค๊ณต', 'ํ๊ตฌ๊ณต', '์ผ๊ตฌ๊ณต', '์ถ๊ตฌ๊ณต',
'๋
ธ๋์', 'ํ๋์', '๋นจ๊ฐ์', '์ฃผํฉ์', '๋จ์', '๋ณด๋ผ์', 'ํฐ์', '๊ฒ์์', '์ด๋ก์',
# ๋ค๋ฆฌ ์ ์ธ๋ ค๊ณ ์ผ๋ถ๋ฌ ๋ค๋บ์
# '๊ฐ์์ง', '๊ฐ๊ตฌ๋ฆฌ', '๊ฑฐ์', '๊ณ ๋ผ๋', '๊ณ ๋', '๊ณ ์์ด', '๊ณฐ', '๊ธฐ๋ฆฐ', '๋๋', '๋ฌํฝ์ด', '๋ฌผ๊ณ ๊ธฐ',
# '๋ณ์๋ฆฌ', '๋น๋๊ธฐ', '์ฌ์', '์ฌ์ฐ', '์ค๋ฆฌ', '์์ญ์ด', '์ฝ๋ผ๋ฆฌ', 'ํ ๋ผ', 'ํญ๊ท', '๊ธ๋ถ์ด', '๋ญ'
'๋ณผํ', '๋์๊ด', '๋ฐ๋ฌผ๊ด',
'์ฌํ', '๊ณผ์', '์ฌ๊ณผ', '๋ฐฐ', '๊ฐ', '๊ทค', 'ํฌ๋', '์๋ฐ', 'ํ ๋งํ ', '๋ฌด', '๋น๊ทผ', '์ค์ด', '๋ฐฐ์ถ', '๊น๋ฐฅ', '๋นต',
'์ด์ฝ๋ง์ฌํ','์ฌ๊ณผ๋ง์ฌํ','๋ฉ๋ก ๋ง์ฌํ','ํฌ๋๋ง์ฌํ',
'๋ผ๋ฉด', '์๋ฃ์', '์ฃผ์ค', '์ฐ์ ', '๋ฌ๊ฑ',
'๋จํ์', '์ฌํ์',
'๊ตญ์ด', '์์ด', '์ํ', '์ฌํ', '๊ณผํ', '์์
', '๋ฏธ์ ', '์ฒด์ก',
'์คํ ๋ฐ์ด', 'ํธ๋ญ', '์๋์ฐจ', '์์ ๊ฑฐ', '๋นํ๊ธฐ', '๋ฒ์ค', '๋ฐฐ', '๊ธฐ์ฐจ']
name_dict = {x: n for n, x in enumerate(name_)}
####################################################################
# ํ๊ธ์ ์ซ์๋ก ๋ฐ๊พธ๋ preprocessing
a = ['์ฒซ[ ]?๋ฒ์งธ', '๋[ ]?๋ฒ์งธ', '์ธ[ ]?๋ฒ์งธ', '๋ค[ ]?๋ฒ์งธ', '๋ค์ฏ[ ]?๋ฒ์งธ', '์ฌ์ฏ[ ]?๋ฒ์งธ', '์ผ๊ณฑ[ ]?๋ฒ์งธ', '์ฌ๋[ ]?๋ฒ์งธ',
'์ํ[ ]?๋ฒ์งธ', '์ด[ ]?๋ฒ์งธ', '์ค๋ฌด[ ]?๋ฒ์งธ', '์๋ฅธ[ ]?๋ฒ์งธ', '๋งํ[ ]?๋ฒ์งธ', '์ฐ[ ]?๋ฒ์งธ', '์์[ ]?๋ฒ์งธ', '์ผํ[ ]?๋ฒ์งธ',
'์ฌ๋ [ ]?๋ฒ์งธ', '์ํ[ ]?๋ฒ์งธ',
'์ฒซ[ ]?์งธ', '๋[ ]?์งธ', '์
[ ]?์งธ', '๋ท[ ]?์งธ', '๋ค์ฏ[ ]?์งธ', '์ฌ์ฏ[ ]?์งธ', '์ผ๊ณฑ[ ]?์งธ',
'์ฌ๋[ ]?์งธ', '์ํ[ ]?์งธ',
'์ผ์[ ]?์๋ฆฌ', '์ญ์[ ]?์๋ฆฌ', '๋ฐฑ์[ ]?์๋ฆฌ', '์ฒ์[ ]?์๋ฆฌ',
'๋[ ]?์',
'ํ[ ]?๊ฐ', '๋[ ]?๊ฐ', '์ธ[ ]?๊ฐ', '๋ค[ ]?๊ฐ', '๋ค์ฏ[ ]?๊ฐ', '์ฌ์ฏ[ ]?๊ฐ', '์ผ๊ณฑ[ ]?๊ฐ', '์ฌ๋[ ]?๊ฐ', '์ํ[ ]?๊ฐ',
'์ด[ ]?๊ฐ', '์ค๋ฌด[ ]?๊ฐ', '์๋ฅธ[ ]?๊ฐ', '๋งํ[ ]?๊ฐ', '์ฐ[ ]?๊ฐ', '์์[ ]?๊ฐ', '์ผํ[ ]?๊ฐ', '์ฌ๋ [ ]?๊ฐ', '์ํ[ ]?๊ฐ',
'ํ[ ]?ํต', 'ํ[ ]?๋ณ',
'ํ[ ]?๋ช
', '๋[ ]?๋ช
', '์ธ[ ]?๋ช
', '๋ค[ ]?๋ช
', '๋ค์ฏ[ ]?๋ช
', '์ฌ์ฏ[ ]?๋ช
', '์ผ๊ณฑ[ ]?๋ช
', '์ฌ๋[ ]?๋ช
', '์ํ[ ]?๋ช
',
'์ด[ ]?๋ช
', '์ค๋ฌด[ ]?๋ช
', '์๋ฅธ[ ]?๋ช
', '๋งํ[ ]?๋ช
', '์ฐ[ ]?๋ช
', '์์[ ]?๋ช
', '์ผํ[ ]?๋ช
', '์ฌ๋ [ ]?๋ช
', '์ํ[ ]?๋ช
',
'ํ[ ]?๊ฐ์ง', '๋[ ]?๊ฐ์ง', '์ธ[ ]?๊ฐ์ง', '๋ค[ ]?๊ฐ์ง', '๋ค์ฏ[ ]?๊ฐ์ง', '์ฌ์ฏ[ ]?๊ฐ์ง', '์ผ๊ณฑ[ ]?๊ฐ์ง', '์ฌ๋[ ]?๊ฐ์ง',
'์ํ[ ]?๊ฐ์ง', '์ด[ ]?๊ฐ์ง', '์ค๋ฌด[ ]?๊ฐ์ง', '์๋ฅธ[ ]?๊ฐ์ง', '๋งํ[ ]?๊ฐ์ง', '์ฐ[ ]?๊ฐ์ง', '์์[ ]?๊ฐ์ง', '์ผํ[ ]?๊ฐ์ง',
'์ฌ๋ [ ]?๊ฐ์ง', '์ํ[ ]?๊ฐ์ง',
'ํ[ ]?์๋ฃจ', '๋[ ]?์๋ฃจ', '์ธ[ ]?์๋ฃจ', '๋ค[ ]?์๋ฃจ', '๋ค์ฏ[ ]?์๋ฃจ', '์ฌ์ฏ[ ]?์๋ฃจ', '์ผ๊ณฑ[ ]?์๋ฃจ', '์ฌ๋[ ]?์๋ฃจ',
'์ํ[ ]?์๋ฃจ', '์ด[ ]?์๋ฃจ', '์ค๋ฌด[ ]?์๋ฃจ', '์๋ฅธ[ ]?์๋ฃจ', '๋งํ[ ]?์๋ฃจ', '์ฐ[ ]?์๋ฃจ', '์์[ ]?์๋ฃจ', '์ผํ[ ]?์๋ฃจ',
'์ฌ๋ [ ]?์๋ฃจ', '์ํ[ ]?์๋ฃจ',
'ํ๋', '๋', '์
', '๋ท', '๋ค์ฏ', '์ฌ์ฏ', '์ผ๊ณฑ', '์ฌ๋', '์ํ', '์ด',
'ํ[ ]?์๋ฆฌ', '๋[ ]?์๋ฆฌ', '์ธ[ ]?์๋ฆฌ', '๋ค[ ]?์๋ฆฌ', '๋ค์ฏ[ ]?์๋ฆฌ', '์ฌ์ฏ[ ]?์๋ฆฌ', '์ผ๊ณฑ[ ]?์๋ฆฌ', '์ฌ๋[ ]?์๋ฆฌ',
'์ํ[ ]?์๋ฆฌ', '์ด[ ]?์๋ฆฌ', '์ค๋ฌด[ ]?์๋ฆฌ', '์๋ฅธ[ ]?์๋ฆฌ', '๋งํ[ ]?์๋ฆฌ', '์ฐ[ ]?์๋ฆฌ', '์์[ ]?์๋ฆฌ', '์ผํ[ ]?์๋ฆฌ',
'์ฌ๋ [ ]?์๋ฆฌ', '์ํ[ ]?์๋ฆฌ',
'ํ[ ]?๋ง๋ฆฌ', '๋[ ]?๋ง๋ฆฌ', '์ธ[ ]?๋ง๋ฆฌ', '๋ค[ ]?๋ง๋ฆฌ', '๋ค์ฏ[ ]?๋ง๋ฆฌ', '์ฌ์ฏ[ ]?๋ง๋ฆฌ', '์ผ๊ณฑ[ ]?๋ง๋ฆฌ', '์ฌ๋[ ]?๋ง๋ฆฌ',
'์ํ[ ]?๋ง๋ฆฌ', '์ด[ ]?๋ง๋ฆฌ', '์ค๋ฌด[ ]?๋ง๋ฆฌ', '์๋ฅธ[ ]?๋ง๋ฆฌ', '๋งํ[ ]?๋ง๋ฆฌ', '์ฐ[ ]?๋ง๋ฆฌ', '์์[ ]?๋ง๋ฆฌ', '์ผํ[ ]?๋ง๋ฆฌ',
'์ฌ๋ [ ]?๋ง๋ฆฌ', '์ํ[ ]?๋ง๋ฆฌ',
'ํ[ ]?๊ฐ', '๋[ ]?๊ฐ', '์ธ[ ]?๊ฐ', '๋ค[ ]?๊ฐ', '๋ค์ฏ[ ]?๊ฐ', '์ฌ์ฏ[ ]?๊ฐ', '์ผ๊ณฑ[ ]?๊ฐ', '์ฌ๋[ ]?๊ฐ', '์ํ[ ]?๊ฐ',
'์ด[ ]?๊ฐ', '์ค๋ฌด[ ]?๊ฐ', '์๋ฅธ[ ]?๊ฐ', '๋งํ[ ]?๊ฐ', '์ฐ[ ]?๊ฐ', '์์[ ]?๊ฐ', '์ผํ[ ]?๊ฐ', '์ฌ๋ [ ]?๊ฐ', '์ํ[ ]?๊ฐ',
'ํ[ ]?๋ช
', '๋[ ]?๋ช
', '์ธ[ ]?๋ช
', '๋ค[ ]?๋ช
', '๋ค์ฏ[ ]?๋ช
', '์ฌ์ฏ[ ]?๋ช
', '์ผ๊ณฑ[ ]?๋ช
', '์ฌ๋[ ]?๋ช
', '์ํ[ ]?๋ช
',
'์ด[ ]?๋ช
', '์ค๋ฌด[ ]?๋ช
', '์๋ฅธ[ ]?๋ช
', '๋งํ[ ]?๋ช
', '์ฐ[ ]?๋ช
', '์์[ ]?๋ช
', '์ผํ[ ]?๋ช
', '์ฌ๋ [ ]?๋ช
', '์ํ[ ]?๋ช
'
]
b = ['1๋ฒ์งธ', '2๋ฒ์งธ', '3๋ฒ์งธ', '4๋ฒ์งธ', '5๋ฒ์งธ', '6๋ฒ์งธ', '7๋ฒ์งธ', '8๋ฒ์งธ', '9๋ฒ์งธ',
'10๋ฒ์งธ', '20๋ฒ์งธ', '30๋ฒ์งธ', '40๋ฒ์งธ', '50๋ฒ์งธ', '60๋ฒ์งธ', '70๋ฒ์งธ', '80๋ฒ์งธ', '90๋ฒ์งธ',
'1์งธ', '2์งธ', '3์งธ', '4์งธ', '5์งธ', '6์งธ', '7์งธ', '8์งธ', '9์งธ',
'1์๋ฆฌ', '10์๋ฆฌ', '100์๋ฆฌ', '100์๋ฆฌ',
'2์',
'1๊ฐ', '2๊ฐ', '3๊ฐ', '4๊ฐ', '5๊ฐ', '6๊ฐ', '7๊ฐ', '8๊ฐ', '9๊ฐ', '10๊ฐ',
'20๊ฐ', '30๊ฐ', '40๊ฐ', '50๊ฐ', '60๊ฐ', '70๊ฐ', '80๊ฐ', '90๊ฐ',
'1ํต', '1๋ณ',
'1๋ช
', '2๋ช
', '3๋ช
', '4๋ช
', '5๋ช
', '6๋ช
', '7๋ช
', '8๋ช
', '9๋ช
', '10๋ช
', '20๋ช
', '30๋ช
', '40๋ช
', '50๋ช
', '60๋ช
',
'70๋ช
', '80๋ช
', '90๋ช
',
'1๊ฐ์ง', '2๊ฐ์ง', '3๊ฐ์ง', '4๊ฐ์ง', '5๊ฐ์ง', '6๊ฐ์ง', '7๊ฐ์ง', '8๊ฐ์ง', '9๊ฐ์ง', '10๊ฐ์ง', '20๊ฐ์ง', '30๊ฐ์ง',
'40๊ฐ์ง', '50๊ฐ์ง', '60๊ฐ์ง', '70๊ฐ์ง', '80๊ฐ์ง', '90๊ฐ์ง',
'1์๋ฃจ', '2์๋ฃจ', '3์๋ฃจ', '4์๋ฃจ', '5์๋ฃจ', '6์๋ฃจ', '7์๋ฃจ', '8์๋ฃจ', '9์๋ฃจ', '10์๋ฃจ', '20์๋ฃจ', '30์๋ฃจ',
'40์๋ฃจ', '50์๋ฃจ', '60์๋ฃจ', '70์๋ฃจ', '80์๋ฃจ', '90์๋ฃจ',
'1', '2', '3', '4', '5', '6', '7', '8', '9', '10',
'1์๋ฆฌ', '2์๋ฆฌ', '3์๋ฆฌ', '4์๋ฆฌ', '5์๋ฆฌ', '6์๋ฆฌ', '7์๋ฆฌ', '8์๋ฆฌ', '9์๋ฆฌ', '10์๋ฆฌ', '20์๋ฆฌ', '30์๋ฆฌ', '40์๋ฆฌ',
'50์๋ฆฌ', '60์๋ฆฌ', '70์๋ฆฌ', '80์๋ฆฌ', '90์๋ฆฌ',
'1๋ง๋ฆฌ', '2๋ง๋ฆฌ', '3๋ง๋ฆฌ', '4๋ง๋ฆฌ', '5๋ง๋ฆฌ', '6๋ง๋ฆฌ', '7๋ง๋ฆฌ', '8๋ง๋ฆฌ', '9๋ง๋ฆฌ', '10๋ง๋ฆฌ', '20๋ง๋ฆฌ', '30๋ง๋ฆฌ', '40๋ง๋ฆฌ',
'50๋ง๋ฆฌ', '60๋ง๋ฆฌ', '70๋ง๋ฆฌ', '80๋ง๋ฆฌ', '90๋ง๋ฆฌ',
'1๊ฐ', '2๊ฐ', '3๊ฐ', '4๊ฐ', '5๊ฐ', '6๊ฐ', '7๊ฐ', '8๊ฐ', '9๊ฐ', '10๊ฐ', '20๊ฐ', '30๊ฐ', '40๊ฐ', '50๊ฐ', '60๊ฐ', '70๊ฐ',
'80๊ฐ', '90๊ฐ',
'1๋ช
', '2๋ช
', '3๋ช
', '4๋ช
', '5๋ช
', '6๋ช
', '7๋ช
', '8๋ช
', '9๋ช
', '10๋ช
', '20๋ช
', '30๋ช
', '40๋ช
', '50๋ช
', '60๋ช
', '70๋ช
',
'80๋ช
', '90๋ช
'
]
dict_ = {}
for i, j in zip(a, b):
dict_[i] = j
for i, k in zip(['์ด', '์ค๋ฌผ', '์๋ฅธ', '๋งํ', '์ฐ', '์์', '์ผํ', '์ฌ๋ ', '์ํ'], [10, 20, 30, 40, 50, 60, 70, 80, 90]):
for j, l in zip(['ํ', '๋', '์ธ', '๋ค', '๋ค์ฏ', '์ฌ์ฏ', '์ผ๊ณฑ', '์ฌ๋', '์ํ'], [1, 2, 3, 4, 5, 6, 7, 8, 9]):
for n in ['๋ฒ์งธ', '์๋ฆฌ', '๋ง๋ฆฌ', '๊ฐ', '๋ช
']:
# print(i+'[]?'+j+'[]?' +n, '-->',f'{k+l}'+n)
dict_[i + '[ ]?' + j + '[ ]?' + n] = f'{k + l}' + n
####################################################################
def func1(a):
"""์ ๋ถ๋ค numberAGC์ผ๋ก ๋ฐ๊พธ๊ณ ๋ค์ num1~~"""
a = re.sub('[0-9]+/[0-9]+|[0-9]*\.[0-9]+|[0-9]+', 'numberAGC', a)
list_ = re.findall('numberAGC', a)
print("list", list_)
for n in range(len(list_)):
a = re.sub('numberAGC', f'number{n}', a, 1) # 1๋ฒ์ฉ๋ง ๋ฐ๊ฟ
return a
def func2(x):
"""question์์ -+๋ ๋นผ๊ณ ๊ฐ์ ธ์์ผํจ.. ์๊ทธ๋ฌ๋ฉด numbers๊ฐ + or -๊ฐ ๋๋ฒ๋ฆผ"""
p = re.compile('[0-9]+/[0-9]+|[0-9]*\.[0-9]+|[0-9]+')
m = p.findall(x)
string = ''
for i in m:
string += i + ' '
return string
##### ๋จ์ด ๋ต๋ ๋ง์ถ๊ธฐ ์ํ ์์
#####
def func_name(x, name_):
"""๊ทผ๋ฐ ์ด๋ ๊ฒ์ง๋ฉด, ๊ฐ์ ์ด๋ฆ์ด๋๋ผ๋ ๋ค๋ฅธ name์ผ๋ก ์ ์ฅ๋๋ค"""
for n in name_:
x = re.sub(n, '์ด๋ฆ๋ํ', x)
list_ = re.findall('์ด๋ฆ๋ํ', x)
for n in range(len(list_)):
x = re.sub('์ด๋ฆ๋ํ', f'name{n}', x, 1)
return x
def func_name2(x, name_):
"""๋ฌธ์๋ฅผ names ์ ๋ต์ผ๋ก ์ ์ฅ"""
string = ''
for i in name_:
m = re.search(i, x)
if m is not None:
string += m.group() + ' '
return string
def word2number(x, dict_):
for d in dict_:
x = re.sub(d, dict_[d], x)
return x
def eq2num(x, y):
"""
x : numbers column
y : equation column
๋์ number๊ฐ ์์ ๋ถ์ผ๋ฉด ๋ฐ๊พธ์ง ์๋๋ฐฉ์
"""
temp_ = {x: 'number' + str(n) for n, x in enumerate(x.split())}
for d in temp_:
# y = re.sub('[^number]'+d, temp_[d], y)
y = re.sub(f'[ ]{d}[ ]', f' {temp_[d]} ', y)
return y
def eq2name(x, y):
"""
x : name column
y : equation column
๋์ number๊ฐ ์์ ๋ถ์ผ๋ฉด ๋ฐ๊พธ์ง ์๋๋ฐฉ์
"""
temp_ = {x: 'name' + str(n) for n, x in enumerate(x.split())}
for d in temp_:
y = re.sub(d, temp_[d], y)
# y = re.sub(f'[ ]{d}[ ]', f' {temp_[d]} ', y)
return y
def pp_question(q):
q = word2number(q, dict_)
names = func_name2(q, name_)
nums = func2(q)
q = func1(q)
q = func_name(q, name_)
return {"question": q, "names": names, "nums": nums}
def pp(tp):
tp['Question'] = tp['Question'].apply(lambda x: word2number(x, dict_)) # ๋จผ์ ํ๊ธ->์ซ์๋ก ๋ค๋ฐ๊พธ๊ณ ์์
tp['Numbers'] = tp['Question'].apply(lambda x: func2(x)) # ์ซ์ ์ ๋ต ๋ณํ
tp['Names'] = tp['Question'].apply(lambda x: func_name2(x, name_)) # ๋ฌธ์ ์ ๋ต ๋ณํ
# ์์ ์ ๋๋ก ์ง์ผ์ผํจ.
tp['Question'] = tp['Question'].apply(lambda x: func1(x)) # numbern์ผ๋ก ๋ณํ
tp['Question'] = tp['Question'].apply(lambda x: func_name(x, name_)) # namen์ผ๋ก ๋ณํ
tp['Equation'] = tp['Equation'].apply(lambda x: f' {x} ') # ์์ชฝ๋์ ์คํ์ด์ค ์ถ๊ฐํด์ num์ผ๋ก ์๋ฐ๋๋์ ๋ค ์ฒ๋ฆฌ
tp['Equation'] = tp[['Numbers', 'Equation']].apply(lambda x: eq2num(x[0], x[1]), 1)
tp['Equation'] = tp[['Names', 'Equation']].apply(lambda x: eq2name(x[0], x[1]), 1)
# ์๋์ ์คํ์ด์ค ์์ ๊ธฐ
tp['Equation'] = tp['Equation'].apply(lambda x: x.strip())
tp['Equation'] = tp['Equation'].apply(lambda x: x.strip())
return tp
def start(path):
try:
test = pd.read_csv(path, dtype={'Answer':'str'})
tp = test.copy()
print('tye num', tp['Numbers'].dtypes)
print('tye name', tp['Names'].dtypes)
except:
test = pd.read_csv(path.replace('_pp',''))
#test = test.rename(columns={'question': 'Question', 'equation': 'Equation', 'answer': 'Answer'})
test = pp(test) # ์ ์ ๋ dataframe
test.to_csv(path, index=False)
tp = test.copy()
#tp = tp.drop(['Question', 'Equation'], 1)
#tp = tp.rename(columns={'Question2': 'Question', 'Equation2': 'Equation', 'answer': 'Answer'})
tp['Numbers'] = tp['Numbers'].astype('str')
tp['Names'] = tp['Names'].astype('str')
return test, tp
voc1_path = "./saved_models/vocab1.p"
voc2_path = "./saved_models/vocab2.p"
saved_path = config.model_path
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
with open(voc1_path, 'rb') as f:
voc1 = pickle.load(f, encoding='bytes')
with open(voc2_path, 'rb') as f:
voc2 = pickle.load(f, encoding='bytes')
model = build_model(config=config, voc1=voc1, voc2=voc2, device=device)
model.load_state_dict(torch.load(saved_path)['state_dict'])
model = model.to(device)
model.eval()
def process_batch(sent1s, voc1, device):
input_len1 = [len(s) for s in sent1s]
# print('input_len1 :',input_len1)
max_length_1 = max(input_len1)
sent1s_padded = [pad_seq(s, max_length_1, voc1) for s in sent1s]
# Convert to [Max_len X Batch]
sent1_var = torch.LongTensor(sent1s_padded).transpose(0, 1)
sent1_var = sent1_var.to(device)
return sent1_var, input_len1
def main_worker(raw_sent):
pp_output = pp_question(raw_sent)
ques = [pp_output["question"]]
names = pp_output["names"].split()
nums = pp_output["nums"].split()
sent1s = sents_to_idx(voc1, ques, config.max_length, flag=0)
sent1_var, _ = process_batch(sent1s, voc1, device)
decoder_output = model.greedy_decode(ques, sent1_var)
str_output = "".join(decoder_output[0])
for i in range(len(names)):
name = f"name{i}"
name_val = names[i]
str_output = str_output.replace(name, name_val)
for i in range(len(nums)):
number = f"number{i}"
number_val = nums[i]
str_output = str_output.replace(number, number_val)
return str_output, eval(str_output)
demo = gr.Interface(fn=main_worker, inputs=["text"], outputs=["text", "text"])
demo.launch(share=True)