forked from wbengine/wblib
-
Notifications
You must be signed in to change notification settings - Fork 1
/
base.py
1508 lines (1226 loc) · 44.2 KB
/
base.py
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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import math
import os
import sys
import time
import io
import numpy as np
import shutil
import json
import platform
import re
import copy
from contextlib import contextmanager
from collections import OrderedDict
from copy import deepcopy
# get the platform
def is_window():
return platform.system() == 'Windows'
def is_linux():
return platform.system() == 'Linux'
def rate2str(a, b):
# return string a / b
return '{:.2f}% ({} / {})'.format(100.0 * a / b, a, b)
# from itertools import zip_longest
def exists(path):
return os.path.exists(path)
# create the dir
def mkdir(path, is_recreate=False, force=False):
if not os.path.exists(path):
os.makedirs(path)
else:
if is_recreate:
if force:
b = 'y'
else:
b = input('Path exit: {} \n'
'Do you want delete it? [y|n]: '.format(path))
if b == 'y' or b == 'yes':
print('Delete and recreate path', path)
rmdir(path)
os.makedirs(path)
return path
# get the file name
def path_file_name(path, rm_suffix=False):
s = os.path.split(path)[-1]
if rm_suffix:
s = os.path.splitext(s)[0]
return s
def mklogdir(path, logname='trf.log', is_recreate=False, force=False):
mkdir(path, is_recreate, force)
sys.stdout = std_log(os.path.join(path, logname))
return path
# prepare the log dir
def prepare_log_dir(logdir, logname):
# create the logdir
mkdir(logdir, is_recreate=True)
# output to log
sys.stdout = std_log(os.path.join(logdir, logname))
# print
print('[{}] log to {}'.format(__name__, os.path.join(logdir, logname)))
# remove files
def remove(path):
if os.path.exists(path):
os.remove(path)
# remove a dir
def rmdir(path):
if os.path.exists(path):
shutil.rmtree(path)
# make sure a folder
def folder(path):
if path[-1] != os.sep:
return path + os.sep
return path
# get the name of current script
def script_name():
argv0_list = sys.argv[0].split(os.sep)
name = argv0_list[len(argv0_list) - 1]
name = name[0:-3]
return name
def file_avoid_overwrite(path):
"""if the path is exit, then revise the file to avoid overwritting"""
if os.path.exists(path):
t = time.localtime()
data_code = '{:04d}{:02d}{:02d}[{:02d}{:02d}]'.format(t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min)
idx = path.rfind('.')
if idx == -1:
path += '_' + data_code
else:
path = path[0:idx] + '_' + data_code + path[idx:]
return path
def log_head(contents=''):
"""return a string, including the date and time"""
s = '================================================================\n'
s += '[time] ' + time.asctime(time.localtime()) + '\n'
s += '[name] ' + script_name() + '\n'
s += '[author] Bin Wang\n'
s += '[email] [email protected]\n'
s += contents
s += '===============================================================\n'
return s
def log_tail(contents=''):
"""return a string, which can be write to the tail of a log files"""
s = '================================================================\n'
s += '[time] ' + time.asctime(time.localtime()) + '\n'
s += '[program finish succeed!]\n'
s += contents
s += '===============================================================\n'
return s
@contextmanager
def processing(s):
print('[wblib.processing] ' + s)
beg_time = time.time()
yield
print('[wblib.processing] finished! time={:.2}m'.format((time.time()-beg_time)/60))
def pprint_dict(d, is_print=True):
prep_d = {}
for k, v in d.items():
new_v = v
if isinstance(new_v, np.int32) or isinstance(new_v, np.int64):
new_v = int(new_v)
if isinstance(new_v, np.ndarray):
new_v = list(new_v)
if isinstance(new_v, list):
if len(new_v) > 10:
new_v = '[' + ', '.join([str(i) for i in new_v[0: 8]] + ['...', str(new_v[-1])]) + ']'
else:
new_v = json.dumps(new_v)
if isinstance(new_v, tuple):
new_v = json.dumps(new_v)
if isinstance(new_v, dict):
new_v = pprint_dict(new_v, is_print=False)
prep_d[k] = new_v
if is_print:
print(json.dumps(prep_d, sort_keys=True, indent=4))
return prep_d
def json_formulate(d):
if isinstance(d, dict):
iter_list = d.items()
elif isinstance(d, list):
iter_list = list(enumerate(d))
elif isinstance(d, tuple):
iter_list = list(enumerate(d))
else:
raise TypeError('unsuport the type {}'.format(type(d)))
res_list = []
for k, v in iter_list:
if isinstance(v, np.int32) or isinstance(v, np.int64):
v = int(v)
elif isinstance(v, np.float32) or isinstance(v, np.float64):
v = float(v)
elif isinstance(v, np.ndarray):
v = v.tolist()
elif isinstance(v, dict) or isinstance(v, list) or isinstance(v, tuple):
v = json_formulate(v)
else:
try:
json.dumps(v)
except TypeError:
v = str(v)
res_list.append((k, v))
if isinstance(d, dict):
return dict(res_list)
elif isinstance(d, list):
return [v for k, v in res_list]
elif isinstance(d, tuple):
return tuple([v for k, v in res_list])
else:
raise TypeError('unsuport the type {}'.format(type(d)))
def interpolate(a, b, weight):
"""output:
if a==None: return b
else: return a*weight + b*(1-weight)
"""
if a is None:
return b
else:
return weight * a + (1 - weight) * b
class clock:
def __init__(self):
self.time_beginning = time.time()
self.time_recoder = dict()
self.time_recoder_beg_stack = list()
self.print_recorde_info = False
def beg(self):
self.time_beginning = time.time()
def end(self, unit='m'):
"""
return the record time
:param unit: one of 's'(second) 'm' (minute) 'h' (hours)
:return:
"""
if unit == 's':
k = 1
elif unit == 'm':
k = 60
elif unit == 'h':
k = 3600
else:
raise KeyError('[end] unknown time unit = ' + unit)
res = (time.time() - self.time_beginning)/k
self.beg()
return res
@contextmanager
def recode(self, name):
try:
self.time_recoder.setdefault(name, 0)
self.time_recoder_beg_stack.append(time.time())
if self.print_recorde_info:
print('[clock] recode [{}] beg'.format(name))
yield
finally:
beg_time = self.time_recoder_beg_stack.pop(-1)
self.time_recoder[name] += (time.time() - beg_time)/60
if self.print_recorde_info:
print('[clock] recode [{}] end, time={}'.format(name, self.time_recoder[name]))
def items(self):
return sorted(self.time_recoder.items(), key=lambda x: x[0])
def merge(self, clock_variables):
# add the time_recoder in the given clock into the current clock
self.time_recoder.update(clock_variables.time_recoder)
class std_log:
"""output text to log file and console"""
def __init__(self, log_file=None, mod='at'):
"""
init
:param log_file: the log file, if None, then write to the <script_name>.log
:param mod: 'wt' or 'at' (default)
"""
self.__console__ = sys.__stdout__
if log_file is None:
log_file = script_name() + '.log'
self.__log__ = open(log_file, mod)
def __del__(self):
self.__log__.close()
def write(self, output_stream):
self.__console__.write(output_stream)
self.__log__.write(output_stream)
self.__log__.flush()
def flush(self):
self.__console__.flush()
self.__log__.flush()
# count the sentence number and the word number of a txt files
def file_count(fname):
if isinstance(fname, str):
f = open(fname)
nLine = 0
nWord = 0
for line in f:
nLine += 1
nWord += len(line.split())
f.close()
else:
"""input is a list of list"""
nLine = len(fname)
nWord = sum([len(x) for x in fname])
return [nLine, nWord]
def file_len_count(fname):
"""
count the file length
"""
len_dict = {}
with open(fname, 'rt') as f:
for line in f:
n = len(line.split())
len_dict.setdefault(n, 0)
len_dict[n] += 1
max_len = max(len_dict.keys())
len_count = np.zeros(max_len + 1)
for n, count in len_dict.items():
len_count[n] = count
return len_count.tolist()
# get more info for txt files
class TxtInfo(object):
def __init__(self, fname):
"""
Count the information of input txt files
Args:
fname: str/ or a list of list
"""
self.nLine = 0
self.nWord = 0
self.vocab = {}
self.min_len = 100
self.max_len = 0
self.fname = fname
if isinstance(fname, str):
with open(fname) as f:
for line in f:
a = line.split()
self.nLine += 1
self.nWord += len(a)
self.min_len = min(self.min_len, len(a))
self.max_len = max(self.max_len, len(a))
for w in a:
self.vocab.setdefault(w, 0)
self.vocab[w] += 1
else:
for a in fname:
self.nLine += 1
self.nWord += len(a)
self.min_len = min(self.min_len, len(a))
self.max_len = max(self.max_len, len(a))
for w in a:
self.vocab.setdefault(w, 0)
self.vocab[w] += 1
self.nVocab = len(self.vocab)
def __str__(self):
return 'line={:,} word={:,} vocab={:,} minlen={} maxlen={}'.format(
self.nLine, self.nWord, self.nVocab, self.min_len, self.max_len)
def write(self, fp):
if isinstance(self.fname, str):
fp.write(self.fname + '\n')
fp.write('line={:,}\nword={:,}\nvocab={:,}\nminlen={}\nmaxlen={}\n'.format(
self.nLine, self.nWord, self.nVocab, self.min_len, self.max_len))
print(str(self))
# rmove the frist column of each line
def file_rmlabel(fread, fout):
with open(fread) as f1, open(fout, 'wt') as f2:
for line in f1:
f2.write(' '.join(line.split()[1:]) + '\n')
# get the word list in files
def getLext(fname):
v = dict()
f = open(fname)
for line in f:
words = line.split()
for w in words:
w = w.upper() # note: to upper
n = v.setdefault(w, 0)
v[w] = n + 1
f.close()
# resorted
n = 0
for k in sorted(v.keys()):
v[k] = n
n += 1
return v
# corpus word to number
# the id of a word w = v[w] + id_offset (if w in v) or v[unk]+ id_offset (if w not in v)
def corpus_w2n(fin, fout, v, unk='<UNK>', id_offset=0):
f = open(fin)
fo = open(fout, 'wt')
for line in f:
words = line.split()
nums = []
for w in words:
w = w.upper()
if w in v:
nums.append(v[w])
elif unk in v:
nums.append(v[unk])
else:
print('[wb.corpus_w2n]: cannot find the key = ' + w);
exit()
fo.write(''.join(['{} '.format(n + id_offset) for n in nums]))
f.close()
fo.close()
# corpus
# ppl to loglikelihood
# two usage: PPL2LL(ppl, nline, nword), PPL2LL(ppl, file)
def PPL2LL(ppl, obj1, obj2=0):
nLine = obj1
nWord = obj2
if isinstance(obj1, str):
[nLine, nWord] = file_count(obj1)
return -math.log(ppl) * (nLine + nWord) / nLine
# LL to PPL
# two usage: LL2PPL(LL, nline, nword), LL2PPL(LL, file)
def LL2PPL(LL, obj1, obj2=0):
nLine = obj1
nWord = obj2
if isinstance(obj1, str):
[nLine, nWord] = file_count(obj1)
return np.exp(-LL * nLine / (nLine + nWord))
# LL incrence bits to PPL decence precent
def LLInc2PPL(LLInc, obj1, obj2):
nLine = obj1
nWord = obj2
if isinstance(obj1, str):
[nLine, nWord] = file_count(obj1)
return 1 - np.exp(-LLInc * nLine / (nLine + nWord))
# read nbest file into dict
def nbest_read_to_dict(nbest_file, type=str):
d = OrderedDict()
with open(nbest_file) as f:
for line in f:
a = line.split()
label = '-'.join(a[0].split('-')[0:-1])
val = type(' '.join(a[1:]))
d.setdefault(label, [])
d[label].append(val)
return d
# compare two word sequence (array), and return the error number
def TxtScore(hypos, refer, special_word=None):
"""
compute the err number
For example:
refer = A B C
hypos = X B V C
after alignment
refer = ~A B ^ C
hypos = ~X B ^V C
err number = 2
where ~ denotes replacement error, ^ denote insertion error, * denotes deletion error.
if set the special_word (not None), then the special word in reference can match any words in hypothesis.
For example:
refer = 'A <?> C'
hypos = 'A B C D C'
after aligment:
refer = A <?> C
hypos = A B C D C
where <?> matches 'B C D'. error number = 0
Usage:
```
refer = 'A <?> C'
hypos = 'A B C D C'
res = wer.wer(refer, hypos, '<?>')
print('err={}'.format(res['err']))
print('ins={ins} del={del} rep={rep}'.format(**res))
print('refer = {}'.format(' '.join(res['refer'])))
print('hypos = {}'.format(' '.join(res['hypos'])))
```
:param refer: a string or a list of words
:param hypos: a string or a list of hypos
:param special_word: this word in reference can match any words
:return:
a result dict, including:
res['word']: word number
res['err']: error number
res['del']: deletion number
res['ins']: insertion number
res['rep']: replacement number
res['hypos']: a list of words, hypothesis after alignment
res['refer']: a list of words, reference after alignment
"""
res = {'word': 0, 'err': 0, 'none': 0, 'del': 0, 'ins': 0, 'rep': 0, 'hypos': [], 'refer': []}
refer_words = refer if isinstance(refer, list) else refer.split()
hypos_words = hypos if isinstance(hypos, list) else hypos.split()
hypos_words.insert(0, '<s>')
hypos_words.append('</s>')
refer_words.insert(0, '<s>')
refer_words.append('</s>')
hypos_len = len(hypos_words)
refer_len = len(refer_words)
if hypos_len == 0 or refer_len == 0:
return res
go_nexts = [[0, 1], [1, 1], [1, 0]]
score_table = [([['none', 10000, [-1, -1], '', '']] * refer_len) for hypos_cur in range(hypos_len)]
score_table[0][0] = ['none', 0, [-1, -1], '<s>', '<s>'] # [error-type, note distance, best previous]
for hypos_cur in range(hypos_len - 1):
for refer_cur in range(refer_len):
for go_nxt in go_nexts:
hypos_next = hypos_cur + go_nxt[0]
refer_next = refer_cur + go_nxt[1]
if hypos_next >= hypos_len or refer_next >= refer_len:
continue
next_score = score_table[hypos_cur][refer_cur][1]
next_state = 'none'
next_hypos = ''
next_refer = ''
if go_nxt == [0, 1]:
if special_word is not None and refer_words[refer_next] == special_word:
next_state = 'none'
next_score += 0
next_hypos = ' ' * len(refer_words[refer_next])
next_refer = refer_words[refer_next]
else:
next_state = 'del'
next_score += 1
next_hypos = '*' + ' ' * len(refer_words[refer_next])
next_refer = '*' + refer_words[refer_next]
elif go_nxt == [1, 0]:
next_state = 'ins'
next_score += 1
next_hypos = '^' + hypos_words[hypos_next]
next_refer = '^' + ' ' * len(hypos_words[hypos_next])
else:
if special_word is not None and refer_words[refer_next] == special_word:
for ii in range(hypos_cur+1, hypos_len-1):
next_score += 0 # can match any words, without penalty
next_state = 'none'
next_refer = special_word
next_hypos = ' '.join(hypos_words[hypos_cur+1:ii+1])
if next_score < score_table[ii][refer_next][1]:
score_table[ii][refer_next] = [next_state, next_score, [hypos_cur, refer_cur], next_hypos, next_refer]
# avoid add too many times
next_score = 10000
else:
next_hypos = hypos_words[hypos_next]
next_refer = refer_words[refer_next]
if hypos_words[hypos_next] != refer_words[refer_next]:
next_state = 'rep'
next_score += 1
next_hypos = '~' + next_hypos
next_refer = '~' + next_refer
if next_score < score_table[hypos_next][refer_next][1]:
score_table[hypos_next][refer_next] = [next_state, next_score, [hypos_cur, refer_cur], next_hypos, next_refer]
res['err'] = score_table[hypos_len - 1][refer_len - 1][1]
res['word'] = refer_len - 2
hypos_cur = hypos_len - 1
refer_cur = refer_len - 1
refer_fmt_words = []
hypos_fmt_words = []
while hypos_cur >= 0 and refer_cur >= 0:
res[score_table[hypos_cur][refer_cur][0]] += 1 # add the del/rep/ins error number
hypos_fmt_words.append(score_table[hypos_cur][refer_cur][3])
refer_fmt_words.append(score_table[hypos_cur][refer_cur][4])
[hypos_cur, refer_cur] = score_table[hypos_cur][refer_cur][2]
refer_fmt_words.reverse()
hypos_fmt_words.reverse()
# format the hypos and refer
assert len(refer_fmt_words) == len(hypos_fmt_words)
for hypos_cur in range(len(refer_fmt_words)):
w = max(len(refer_fmt_words[hypos_cur]), len(hypos_fmt_words[hypos_cur]))
fmt = '{:>%d}' % w
refer_fmt_words[hypos_cur] = fmt.format(refer_fmt_words[hypos_cur])
hypos_fmt_words[hypos_cur] = fmt.format(hypos_fmt_words[hypos_cur])
res['refer'] = refer_fmt_words[1:-1]
res['hypos'] = hypos_fmt_words[1:-1]
return res
# calculate the WER given best file
def CmpWER(best, temp, log_str_or_io=None, sentence_process_fun=None, special_word=None):
nLine = 0
nTotalWord = 0
nTotalErr = 0
f1 = open(best) if isinstance(best, str) else best
f2 = open(temp) if isinstance(temp, str) else temp
fout = open(log_str_or_io, 'wt') if isinstance(log_str_or_io, str) else log_str_or_io
# using the label to match sentences
# first load the correct sentences
temp_dict = dict()
for line in f2:
a = line.split()
temp_dict[a[0]] = a[1:]
# process each sentence in the 1best file
for line in f1:
a = line.split()
try:
temp_sent = temp_dict[a[0]]
except KeyError:
raise("[{}.CmpWER] cannot find the label={} in template".format(__name__, a[0]))
target = a[1:]
if sentence_process_fun is not None:
target = sentence_process_fun(target)
temp_sent = sentence_process_fun(temp_sent)
res = TxtScore(target, temp_sent, special_word=special_word)
nTotalErr += res['err']
nTotalWord += res['word']
if fout is not None:
fout.write('[{}] {}\n'.format(nLine, a[0]))
fout.write('[nDist={0}] [{0}/{1}] [{2}/{3}]\n'.format(res['err'], res['word'], nTotalErr, nTotalWord))
fout.write('refer: ' + ''.join([i + ' ' for i in res['refer']]) + '\n')
fout.write('hypos: ' + ''.join([i + ' ' for i in res['hypos']]) + '\n')
fout.flush()
nLine += 1
if isinstance(best, str):
f1.close()
if isinstance(temp, str):
f2.close()
if isinstance(log_str_or_io, str):
fout.close()
return [nTotalErr, nTotalWord, 1.0 * nTotalErr / nTotalWord * 100]
def CmpCER(best, temp, log_str_or_io=None):
def word_to_chars(wseq):
char_seq = []
for w in wseq:
# split Chinese word to char, and preserve the English words
cs = re.split(r'([\u4e00-\u9fa5])', w)
cs = list(filter(None, cs))
char_seq += cs
return char_seq
return CmpWER(best, temp, log_str_or_io, sentence_process_fun=word_to_chars)
def TxtScoreForPool(input_tuple):
# input_tuple = (label, target, temp_sent, special_word)
return input_tuple[0], TxtScore(*input_tuple[1:])
def CmpOracleWER(nbest, refer, log_str_or_io=None, sentence_process_fun=None, processes=4, special_word=None):
import tqdm
from multiprocessing import Pool
f1 = open(nbest) if isinstance(nbest, str) else nbest
f2 = open(refer) if isinstance(refer, str) else refer
fout = open(log_str_or_io, 'wt') if isinstance(log_str_or_io, str) else log_str_or_io
# using the label to match sentences
# first load the correct sentences
temp_dict = OrderedDict()
for line in f2:
a = line.split()
temp_dict[a[0]] = a[1:]
def iter_get_data():
for line in f1:
a = line.split()
head = a[0]
idx = head.rindex('-')
label = head[0:idx]
num = int(head[idx + 1:])
target = a[1:]
temp_sent = temp_dict[label]
if sentence_process_fun is not None:
target = sentence_process_fun(target)
temp_sent = sentence_process_fun(temp_sent)
yield label, target, temp_sent, special_word
total_lines = len(f1.readlines())
f1.seek(0)
# perform wer
nbest_dct = OrderedDict()
pool = Pool(processes=processes)
for label, res in tqdm.tqdm(pool.imap(func=TxtScoreForPool, iterable=iter_get_data()),
desc='computing oracle WER',
total=total_lines):
dist = nbest_dct.setdefault(label, [])
dist.append(res)
# compute the oracle wer
lowest_err = []
for label, err_dict_list in nbest_dct.items():
fout.write(label + ' ')
for res in err_dict_list:
fout.write('{}/{}/{}/{}/{} '.format(res['ins'], res['del'], res['rep'], res['err'], res['word']))
fout.write('\n')
err_list = [(res['err'], res['word']) for res in err_dict_list]
lowest_err.append(sorted(err_list, key=lambda x: x[0])[0])
a = np.array(lowest_err).sum(axis=0)
nTotalErr = a[0]
nTotalWord = a[1]
if isinstance(nbest, str):
f1.close()
if isinstance(refer, str):
f2.close()
if isinstance(log_str_or_io, str):
fout.close()
return nTotalErr, nTotalWord, 1.0 * nTotalErr / nTotalWord * 100
# given the score get the 1-best result
def GetBest(nbest, score, best):
"""
:param nbest: nbest file
:param score: score file, if None, then select the first sentence
:param best: output the best file
"""
nbest_dict = nbest_read_to_dict(nbest)
if score is None:
score_dict = None
elif isinstance(score, str) and os.path.isfile(score):
score_dict = nbest_read_to_dict(score, type=float)
else:
# a list of scores
score_dict = OrderedDict()
i = 0
for label, vals in nbest_dict.items():
score_dict[label] = score[i: i+len(vals)]
i += len(vals)
# fout
fout = open(best, 'wt') if isinstance(best, str) else best
for label, vals in nbest_dict.items():
if score_dict is not None:
s = score_dict[label]
i = np.argmin(s)
else:
i = 0
fout.write('{} {}\n'.format(label, vals[i]))
if isinstance(best, str):
fout.close()
# load the score file
def LoadScore(fname):
s = []
f = open(fname, 'rt')
for line in f:
a = line.split()
s.append(float(a[1]))
f.close()
return np.array(s)
# Load the nbest/score label
def LoadLabel(fname):
s = []
f = open(fname, 'rt')
for line in f:
a = line.split()
s.append(a[0])
f.close()
return s
# Write Score
def WriteScore(fname, s, label=[]):
with open(fname, 'wt') as f:
for i in range(len(s)):
if len(label) == 0:
f.write('line={}\t{}\n'.format(i, s[i]))
else:
f.write('{}\t{}\n'.format(label[i], s[i]))
# write nbest
def WriteNbest(fname, nbest_list, label=None):
with open(fname, 'wt') as f:
for i in range(len(nbest_list)):
if label is None:
f.write('line={}\t{}\n'.format(i, nbest_list[i]))
else:
f.write('{}\t{}\n'.format(label[i], nbest_list[i]))
# cmp interpolate
def ScoreInterpolate(s1, s2, w):
s1 = LoadScore(s1) if isinstance(s1, str) else s1
s2 = LoadScore(s2) if isinstance(s2, str) else s2
return w * s1 + (1-w) * s2
# tune the lmscale and acscale to get the best WER
def TuneWER(nbest, temp, lmscore, acscore, lmscale, acscale=[1]):
opt_wer = 100
opt_lmscale = 0
opt_acscale = 0
if isinstance(lmscore, str):
lmscore = LoadScore(lmscore)
if isinstance(acscore, str):
acscore = LoadScore(acscore)
# tune the lmscale
for ac in acscale:
for lm in lmscale:
s = ac * np.array(acscore) + lm * np.array(lmscore)
# best_file = 'lm{}.ac{}.best'.format(lmscale, acscale)
best_file = io.StringIO()
GetBest(nbest, s, best_file)
best_file.seek(0)
[totale, totalw, wer] = CmpWER(best_file, temp)
# print('acscale={}\tlmscale={}\twer={}\n'.format(acscale, lmscale, wer))
if wer < opt_wer:
opt_wer = wer
opt_lmscale = lm
opt_acscale = ac
# remove the best files
# os.remove(best_file)
best_file.close()
return opt_wer, opt_lmscale, opt_acscale
# Res file, such as
# model LL-train LL-valid LL-test PPL-train PPL-valid PPL-test
# Kn5 100 100 100 200 200 200
# rnn 100 100 100 200 200 200
class FRes:
def __init__(self, fname, print_to_cmd=False):
self.fname = fname # the file name
self.data = [] # recore all the data in files
self.head = [] # recore all the label
self.comment = [] # comments
self.print_to_cmd = print_to_cmd
self.new_add_name = '' # record the current add name
# load data from file
def Read(self):
self.data = []
self.head = []
self.comment = ''
if os.path.exists(self.fname):
with open(self.fname, 'rt') as f:
nline = 0
for line in f:
a = line.split()
if len(a) == 0:
continue
if a[0][0] == '#':
# comments if the first character of the first word is #
self.comment += line
else:
if nline == 0:
self.head = a
else:
self.data.append(a)
nline += 1
else:
self.head.append('models')
# return all the name in files
names = []
for a in self.data:
names.append(a[0])
return names
# write data to file
def Write(self):
n = len(self.head)
width = [len(i) for i in self.head]
for a in self.data:
for i in range(len(a)):
width[i] = max(width[i], len(a[i]))
with open(self.fname, 'wt') as f:
# write comments
f.write(self.comment + '\n')
# write data
for a in [self.head] + self.data:
outputline = ''
for i in range(len(a)):
outputline += '{0:{width}}'.format(a[i], width=width[i]+2)
f.write(outputline + '\n')
# print the new added line
if self.print_to_cmd and a[0] == self.new_add_name:
print(outputline)
# add a line comment
def AddComment(self, s):
self.Read()
self.comment += '# ' + s + '\n'
self.Write()
# clean files
def Clean(self):
remove(self.fname)
# remove default head
def RMDefaultHead(self):
self.head = ['models']
# get the head
def GetHead(self):
self.Read()
return self.head
# get ['KN', '100', '111', 1213']
def GetLine(self, name):
self.Read()
for a in self.data:
if a[0] == name:
return a