-
Notifications
You must be signed in to change notification settings - Fork 1
/
datautils.py
3307 lines (2841 loc) · 132 KB
/
datautils.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
# !/usr/bin/env python
# coding=utf-8
"""
Miscellaneous utils for IO and NER.
Started from 2019
"""
import argparse
import os, re, glob, shutil, copy, time, datetime
from typing import *
import json
import random
from pathlib import Path
import numpy as np
import logging
import logging.handlers
from collections import Counter, defaultdict
try:
import xlrd, xlwt, openpyxl
except ImportError:
print('找不到xlrd/xlwt/openpyxl包 不能使用xls相关函数')
try:
import paramiko
except ImportError:
print('找不到paramiko包 不能使用remote相关函数')
try:
import prettytable
# import rich
# from rich import table
# from rich import print
# from rich.pretty import pprint
except ImportError:
print('找不到prettytable或rich包 不能使用prettytable相关函数')
def file2list(in_file, strip_nl=True, encoding='U8'):
with open(in_file, 'r', encoding=encoding) as f:
lines = [line.strip('\n') if strip_nl else line for line in f]
print(f'read ok! filename: {in_file}, length: {len(lines)}')
return lines
def file2txt(in_file, encoding='U8'):
with open(in_file, 'r', encoding=encoding) as f:
txt = f.read()
return txt
def file2items(in_file, strip_nl=True, deli='\t', extract=None, filter_fn=None, encoding='U8'):
# extract: [0,2] or (0,2) or '02' # assume indices > 9 should not use str
# filter_fn: lambda item: item[2] == 'Y'
lines = file2list(in_file, strip_nl=strip_nl, encoding=encoding)
items = [line.split(deli) for line in lines]
if filter_fn is not None:
items = list(filter(filter_fn, items))
print(f'after filter, length: {len(lines)}')
if extract is not None:
assert isinstance(extract, (list, tuple, str)), 'invalid extract args'
items = [[item[int(e)] for e in extract] for item in items]
return items
# kv_ids: [0,1] or (0,1) or '01' # assume indices > 9 should not use str
def file2dict(in_file, deli='\t', kv_order='01'):
items = file2items(in_file, deli=deli)
assert isinstance(kv_order, (list, tuple, str)) and len(kv_order) == 2, 'invalid kv_order args'
k_idx = int(kv_order[0])
v_idx = int(kv_order[1])
return {item[k_idx]: item[v_idx] for item in items}
def file2nestlist(in_file, strip_nl=True, encoding='U8', seg_line=''):
# l1,l2,seg_l,l3,l4,l5,seg_l -> [[l1,l2],[l3,l4,l5]]
lst = file2list(in_file, strip_nl=strip_nl, encoding=encoding)
out_lst_lst = []
out_lst = []
for line in lst:
if line == seg_line:
out_lst_lst.append(out_lst)
out_lst = []
continue
out_lst.append(line)
if out_lst:
out_lst_lst.append(out_lst)
return out_lst_lst
def seg_list(lst, is_seg_fn=None):
# [l1,l2,seg,l3,l4,l5] -> [[l1,l2],[l3,l4,l5]]
if is_seg_fn is None:
is_seg_fn = lambda e: e == ''
nest_lst = [[]]
for e in lst:
if is_seg_fn(e):
nest_lst.append([])
continue
nest_lst[-1].append(e)
return nest_lst
def make_sure_dir_exist(file_or_dir):
file_or_dir = Path(file_or_dir)
if not file_or_dir.parent.exists():
file_or_dir.parent.mkdir(parents=True, exist_ok=True)
return True
def np2py(obj):
# np格式不支持json序列号,故转化为python数据类型
if isinstance(obj, (int, float, bool, str)):
return obj
if isinstance(obj, dict):
for k in obj:
obj[k] = np2py(obj[k])
return obj
elif isinstance(obj, (list, tuple)):
for i in range(len(obj)):
obj[i] = np2py(obj[i])
return obj
elif isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
return obj.tolist()
else:
return obj
def save_json(obj, json_file, indent=2, verbose=True):
make_sure_dir_exist(json_file)
obj = np2py(obj)
json.dump(obj, open(json_file, 'w', encoding='U8'),
ensure_ascii=False, indent=indent)
if verbose: print(f'save json file ok! {json_file}')
def load_json(json_file):
with open(json_file, 'r', encoding='U8') as f:
json_data = json.load(f)
return json_data
def save_jsonl(obj_lst, jsonl_file, verbose=True):
"""write data by line with json"""
make_sure_dir_exist(jsonl_file)
with open(jsonl_file, 'w', encoding='U8') as f:
for obj in obj_lst:
obj = np2py(obj)
f.write(json.dumps(obj, ensure_ascii=False) + '\n')
if verbose: print(f'save jsonl file ok! {jsonl_file}, length: {len(obj_lst)}')
def load_jsonl(jsonl_file):
"""read data by line with json"""
with open(jsonl_file, 'r', encoding='U8') as f:
return [json.loads(line.strip()) for line in f]
class MyJSONEncoder(json.JSONEncoder):
"""用以生成json字符时强制列表类型数据不换行显示"""
def iterencode(self, o, _one_shot=False):
list_lvl = 0
for s in super(MyJSONEncoder, self).iterencode(o, _one_shot=_one_shot):
if s.startswith('['):
list_lvl += 1
s = s.replace('\n', '').rstrip()
elif 0 < list_lvl:
s = s.replace('\n', '').rstrip()
if s and s[-1] == ',':
s = s[:-1] + self.item_separator
elif s and s[-1] == ':':
s = s[:-1] + self.key_separator
if s.endswith(']'):
list_lvl -= 1
yield s
def printjson(object, value_func=None, sort=True, collapse_list=False):
"""将python对象用json格式打印"""
object = object.copy()
if value_func is not None and isinstance(object, dict):
for k, v in object.items():
object[k] = value_func(object[k])
# if sort:
# object = {key: object[key] for key in sorted(object.keys())} # sorted了之后输出的json也是sorted的
if collapse_list:
s = json.dumps(object, indent=1, ensure_ascii=False, sort_keys=sort, cls=MyJSONEncoder)
else:
s = json.dumps(object, indent=1, ensure_ascii=False, sort_keys=sort)
print(s)
return s
def stats_lst(lst, digtal=True):
ret = {}
if digtal and lst:
lst.sort()
num = len(lst)
quarter = num // 4
ret['1/4分位'] = lst[quarter:quarter + 1]
ret['2/4分位'] = lst[quarter * 2:quarter * 2 + 1]
ret['3/4分位'] = lst[quarter * 3:quarter * 3 + 1]
ret['mean'] = np.mean(lst)
ret['max'] = np.max(lst)
ret['min'] = np.min(lst)
ret['std'] = np.std(lst)
counts = [(key, cnt, f'{cnt / num:.2%}') for key, cnt in Counter(lst).most_common()]
if len(counts) > 10:
brief_counts = counts[:5] + ['...'] + counts[-5:]
else:
brief_counts = counts
ret['brief_counts'] = brief_counts
return ret
return {}
def aggreate_stats(stats: dict, agg_key_func=lambda k: k.split('_'[0]), reduce='sum'):
"""合并特定键的统计数据
如合并_前缀相同的键 默认reduce=none即列表拼接
"""
agg_stats = {}
for k, v in stats.items():
agg_stats.setdefault(agg_key_func(k), []).append(v)
if reduce == 'none':
return agg_stats
elif reduce == 'sum':
agg_stats = {k: sum(v) for k, v in agg_stats.items()}
return agg_stats
elif reduce == 'mean':
agg_stats = {k: sum(v) / len(v) for k, v in agg_stats.items()}
return agg_stats
return agg_stats
def list_dirs(path, return_type='str'):
dirs = [d for d in Path(path).iterdir() if d.is_dir()]
if return_type == 'str':
dirs = [str(d) for d in dirs]
return dirs
def list_files(path, return_type='str'):
files = [d for d in Path(path).iterdir() if d.is_file()]
if return_type == 'str':
files = [str(f) for f in files]
return files
def list_dir_and_file(path):
lsdir = os.listdir(path)
dirs = [d for d in lsdir if os.path.isdir(os.path.join(path, d))]
files = [f for f in lsdir if os.path.isfile(os.path.join(path, f))]
return dirs, files
def txt2file(txt: str, out_file, encoding='U8'):
with open(out_file, 'w', encoding=encoding) as f:
f.write(txt)
return True
def list2file(lines, out_file, add_nl=True, deli='\t', verbose=True):
make_sure_dir_exist(out_file)
if isinstance(lines, str): # 兼容
lines, out_file = out_file, lines
assert len(lines) > 0, 'lines must be not None'
with open(out_file, 'w', encoding='U8') as f:
if isinstance(lines[0], (list, tuple)):
lines = [deli.join(map(str, item)) for item in lines]
# other: str, int, float, bool, obj will use f'{} to strify
out_list = [f'{line}\n' if add_nl else f'{line}' for line in lines]
f.writelines(out_list)
if verbose:
print(f'save ok! filename: {out_file}, length: {len(out_list)}')
def freqs(lst):
c = Counter(lst)
return c.most_common()
def list2stats(in_lst, out_file=None):
stats = freqs(in_lst)
print(*stats, sep='\n')
if out_file is not None:
list2file(stats, out_file, deli='\t')
# sheet_ids: [0,1,3] default read all sheet
def xls2items(in_xls, start_row=1, sheet_ids=None):
items = []
xls = xlrd.open_workbook(in_xls)
sheet_ids = list(range(xls.nsheets)) if sheet_ids is None else sheet_ids
for sheet_id in sheet_ids:
sheet = xls.sheet_by_index(sheet_id)
nrows, ncols = sheet.nrows, sheet.ncols
print(f'reading... sheet_id:{sheet_id} sheet_name:{sheet.name} rows:{nrows} cols:{ncols}')
for i in range(start_row, nrows):
items.append([sheet.cell_value(i, j) for j in range(ncols)])
return items
# this only support old xls (nrows<65537)
def items2xls_old(items, out_xls=None, sheet_name=None, header=None, workbook=None, max_row_per_sheet=65537):
workbook = xlwt.Workbook(encoding='utf-8') if workbook is None else workbook
sheet_name = '1' if sheet_name is None else sheet_name
num_sheet = 1
worksheet = workbook.add_sheet(f'{sheet_name}_{num_sheet}') # 创建一个sheet
if header is not None:
for j in range(len(header)):
worksheet.write(0, j, header[j])
row_ptr = 1 if header is not None else 0
for item in items:
if row_ptr + 1 > max_row_per_sheet:
num_sheet += 1
worksheet = workbook.add_sheet(f'{sheet_name}_{num_sheet}')
if header is not None:
for j in range(len(header)):
worksheet.write(0, j, header[j])
row_ptr = 1 if header is not None else 0
for j in range(len(item)):
worksheet.write(row_ptr, j, item[j])
row_ptr += 1
if out_xls is not None: # 如果为None表明调用者其实还有新的items要加到新的sheet要中,只想要返回的workbook对象
workbook.save(out_xls)
print(f'save ok! xlsname: {out_xls}, num_sheet: {num_sheet}')
return workbook
def items2xls(items, out_xls=None, sheet_name=None, header=None, workbook=None, max_row_per_sheet=65537):
if workbook is None:
workbook = openpyxl.Workbook() # create new workbook instance
active_worksheet = workbook.active
workbook.remove(active_worksheet)
if sheet_name is None:
sheet_name = 'sheet'
num_sheet = 1
worksheet = workbook.create_sheet(f'{sheet_name}_{num_sheet}' if len(items) > max_row_per_sheet else f'{sheet_name}') # 创建一个sheet
if header is not None:
for j in range(len(header)):
worksheet.cell(0 + 1, j + 1, header[j]) # cell x y 从1开始
row_ptr = 1 if header is not None else 0
for item in items:
if row_ptr + 1 > max_row_per_sheet:
num_sheet += 1
worksheet = workbook.create_sheet(f'{sheet_name}_{num_sheet}')
if header is not None:
for j in range(len(header)):
worksheet.cell(0 + 1, j + 1, header[j])
row_ptr = 1 if header is not None else 0
for j in range(len(item)):
worksheet.cell(row_ptr + 1, j + 1, item[j])
row_ptr += 1
if out_xls is not None: # 如果为None表明调用者其实还有新的items要加到新的sheet表中,只想要返回的workbook对象
workbook.save(out_xls)
print(f'save ok! xlsname: {out_xls}, num_sheet: {num_sheet}')
return workbook
def merge_file(file_list, out_file, shuffle=False):
assert isinstance(file_list, (list, tuple))
ret_lines = []
for i, file in enumerate(file_list):
lines = file2list(file, strip_nl=False)
print(f'已读取第{i}个文件:{file}\t行数{len(lines)}')
ret_lines.extend(lines)
if shuffle:
random.shuffle(ret_lines)
list2file(out_file, ret_lines, add_nl=False)
def merge_file_by_pattern(pattern, out_file, shuffle=False):
file_list = glob.glob(pattern)
merge_file(file_list, out_file, shuffle)
# ratio: [18,1,1] or '18:1:1'
# num: 1000
def split_file(file_or_lines, num=None, ratio=None, files=None, shuffle=True, seed=None):
assert num or ratio, 'invalid args: at least use num or ratio'
if type(file_or_lines) == str:
lines = file2list(file_or_lines, strip_nl=False)
else:
assert isinstance(file_or_lines, (list, tuple)), 'invalid args file_or_lines'
lines = file_or_lines
length = len(lines)
if shuffle:
if seed is not None:
random.seed(seed)
random.shuffle(lines)
if num:
assert num < length, f'invalid args num: num:{num} should < filelen: {length}'
lines1 = lines[:num]
lines2 = lines[num:]
if files:
assert len(files) == 2
list2file(files[0], lines1, add_nl=False)
list2file(files[1], lines2, add_nl=False)
return lines1, lines2
if ratio: # [6,2,2]
if isinstance(ratio, str):
ratio = list(map(int, ratio.split(':')))
cumsum_ratio = np.cumsum(ratio) # [6,8,10]
sum_ratio = cumsum_ratio[-1] # 10
assert sum_ratio <= length, f'invalid args ratio: ratio:{ratio} should <= filelen: {length}'
indices = [length * r // sum_ratio for r in cumsum_ratio] # [6,8,11] if length=11
indices = [0] + indices
split_lines_lst = []
for i in range(len(indices) - 1):
split_lines_lst.append(lines[indices[i]:indices[i + 1]])
if files:
assert len(files) == len(split_lines_lst)
for i, lines in enumerate(split_lines_lst):
list2file(files[i], lines, add_nl=False)
return split_lines_lst
def delete_file(file_or_dir, verbose=True):
if os.path.exists(file_or_dir):
if os.path.isfile(file_or_dir): # 文件file
os.remove(file_or_dir)
if verbose:
print(f'delete ok! file: {file_or_dir}')
return True
else: # 目录dir
for file_lst in os.walk(file_or_dir):
for name in file_lst[2]:
os.remove(os.path.join(file_lst[0], name))
shutil.rmtree(file_or_dir)
if verbose:
print(f'delete ok! dir: {file_or_dir}')
return True
else:
print(f'delete false! file/dir not exists: {file_or_dir}')
return False
def find_duplicates(in_lst):
# duplicates = []
# seen = set()
# for item in in_lst:
# if item not in seen:
# seen.add(item)
# else:
# duplicates.append(item)
# return duplicates
c = Counter(in_lst)
return [k for k, v in c.items() if v > 1]
def remove_duplicates_for_file(in_file, out_file=None, keep_sort=True):
if not out_file:
out_file = in_file
lines = file2list(in_file)
if keep_sort:
out_lines = []
tmp_set = set()
for line in lines:
if line not in tmp_set:
out_lines.append(line)
tmp_set.add(line)
else:
out_lines = list(set(lines))
list2file(out_file, out_lines)
def remove_duplicates(in_list, keep_sort=True):
lines = in_list
if keep_sort:
out_lines = []
tmp_set = set()
for line in lines:
if line not in tmp_set:
out_lines.append(line)
tmp_set.add(line)
else:
out_lines = list(set(lines))
return out_lines
def set_items(items, keep_order=False):
items = [tuple(item) for item in items] # need to be hashable i.e. tuple
ret = []
if keep_order:
seen = set()
for item in items:
if item not in seen:
seen.append(item)
ret.append(list(item))
return ret
if not keep_order:
ret = list(map(list, set(items)))
return ret
def sort_items(items, sort_order):
if isinstance(sort_order, str):
sort_order = map(int, sort_order)
for idx in reversed(sort_order):
items.sort(key=lambda item: item[idx])
return items
def check_overlap(list1, list2, verbose=False):
set1 = set(list1)
set2 = set(list2)
count1 = Counter(list1)
dupli1 = [k for k, v in count1.items() if v > 1]
count2 = Counter(list2)
dupli2 = [k for k, v in count2.items() if v > 1]
print(f'原始长度:{len(list1)}\t去重长度{len(set1)}\t重复项{dupli1}')
print(f'原始长度:{len(list2)}\t去重长度{len(set2)}\t重复项{dupli2}')
union = sorted(set1 & set2) # 变为list
print(f'一样的数量: {len(union)}')
if verbose or len(union) <= 30:
print(*union, sep='\n', end='\n\n')
else:
print(*union[:30], sep='\n', end=f'\n ..more(total:{len(union)})\n\n')
a = sorted(set1 - set2) # 变为list
print(f'前者多了: {len(a)}')
if verbose or len(a) <= 30:
print(*a, sep='\n', end='\n\n')
else:
print(*a[:30], sep='\n', end=f'\n ..more(total:{len(a)})\n\n')
b = sorted(set2 - set1) # 变为list
print(f'后者多了: {len(b)}')
if verbose or len(b) <= 30:
print(*b, sep='\n', end='\n\n')
else:
print(*b[:30], sep='\n', end=f'\n ..more(total:{len(a)})\n\n')
def print_len(files):
if not isinstance(files, list):
files = [files]
len_lst = []
for file in files:
with open(file, 'r', encoding='U8') as f:
len_lst.append(len(f.readlines()))
print(len_lst, f'总和: {sum(len_lst)}')
def f(object):
""" 格式化 """
if 'numpy' in str(type(object)) and len(object.shape) == 1:
object = object.tolist()
if isinstance(object, (list, tuple)):
if len(object) == 0:
return ''
if isinstance(object[0], (int, float)):
ret = list(map(lambda e: f'{e:.2f}', object))
return str(ret)
return str(object)
def get_first_key_or_value_of_dict(dct: dict, mode='key'):
if mode == 'value':
# ret = list(dct.values())[0] # slow but readable
ret = next(iter(dct.values())) # fast
elif mode == 'key':
ret = next(iter(dct.keys())) # fast
return ret
def print_total_param(pt_model):
print('total_params:', sum(p.numel() for p in pt_model.parameters()))
class Dict(dict):
__setattr__ = dict.__setitem__
__getattr__ = dict.__getitem__
def dict2obj(dct):
if not isinstance(dct, dict):
return dct
inst = Dict()
for k, v in dct.items():
inst[k] = dict2obj(v)
return inst
class ImmutableDict(dict):
def __hash__(self):
return id(self)
def _immutable(self, *args, **kws):
raise TypeError('object is immutable')
__setitem__ = _immutable
__delitem__ = _immutable
clear = _immutable
update = _immutable
setdefault = _immutable
pop = _immutable
popitem = _immutable
class Any2Id():
# fix 是否固定住字典不在增加
def __init__(self, use_line_no=False, exist_dict=None, fix=True, counter=None):
self.fix = fix
self.use_line_no = use_line_no
self.file = None
self.counter = Counter() if not counter else counter
self.any2id = {} # 内部核心dict
if exist_dict is not None:
self.any2id.update(exist_dict)
# for method_name in dict.__dict__: # 除了下面显式定义外保证能以dict的各种方法操作Any2id
# setattr(self, method_name, getattr(self.any2id, method_name))
def keys(self):
return self.any2id.keys()
def values(self):
return self.any2id.values()
def items(self):
return self.any2id.items()
def pop(self, key):
return self.any2id.pop(key)
def __getitem__(self, item):
return self.any2id.__getitem__(item)
def __setitem__(self, key, value):
self.any2id.__setitem__(key, value)
def __len__(self):
return self.any2id.__len__()
def __iter__(self):
return self.any2id.__iter__()
def __str__(self):
string = self.any2id.__str__()
return string[:200] + '...' if len(string) > 200 else string
def __repr__(self):
return f'<Any2Id> {str(self)}'
def set_fix(self, fix):
self.fix = fix
def get(self, key, default=None, add=False):
if not add:
return self.any2id.get(key, default)
else:
# new_id = len(self.any2id)
new_id = max(self.any2id.values()) + 1
self.any2id[key] = new_id
return new_id
def get_reverse(self):
return self.__class__(exist_dict={v: k for k, v in self.any2id.items()})
def save(self, file=None, use_line_no=None, deli='\t'):
use_line_no = self.use_line_no if use_line_no is None else use_line_no
items = sorted(self.any2id.items(), key=lambda e: e[1])
out_items = [item[0] for item in items] if use_line_no else items
file = self.file if file is None else file
list2file(out_items, file, deli=deli)
print(f'词表文件生成成功: {file} {items[:5]}...')
def load(self, file, use_line_no=None, deli='\t'):
if use_line_no is None:
use_line_no = self.use_line_no
items = file2items(file, deli=deli)
if use_line_no or len(items[0]) == 1:
self.any2id = {item[0]: i for i, item in enumerate(items)}
else:
self.any2id = {item[0]: int(item[1]) for item in items}
def to_count(self, any_lst):
self.counter.update(any_lst) # 维护一个计数器
def reset_counter(self):
self.counter = Counter()
def rebuild_by_counter(self, restrict=None, min_freq=None, max_vocab_size=None):
if not restrict:
restrict = ['<pad>', '<unk>', '<eos>']
freqs = self.counter.most_common()
tokens_lst = restrict[:]
curr_vocab_size = len(tokens_lst)
for token, cnt in freqs:
if min_freq and cnt < min_freq:
break
if max_vocab_size and curr_vocab_size >= max_vocab_size:
break
tokens_lst.append(token)
curr_vocab_size += 1
self.any2id = {token: i for i, token in enumerate(tokens_lst)}
@classmethod
def from_file(cls, file, use_line_no=False, deli='\t'):
inst = cls(use_line_no=use_line_no)
if os.path.exists(file):
inst.load(file, deli=deli)
else:
# will return inst with empty any2id , e.g. boolean(inst) or len(inst) will return False
print(f'vocab file: {file} not found, need to build and save later')
inst.file = file
return inst
def pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre', truncating='pre', value=0.):
if not hasattr(sequences, '__len__') or not all([hasattr(x, '__len__') for x in sequences]):
raise ValueError(f'sequences invalid: {sequences}')
len_lst = [len(x) for x in sequences]
if len(set(len_lst)) == 1: # 长度均相等
ret = np.array(sequences)
if maxlen is not None:
ret = ret[:, -maxlen:] if truncating == 'pre' else ret[:, :maxlen]
return ret
num_samples = len(sequences)
if maxlen is None:
maxlen = np.max(len_lst)
sample_shape = tuple()
for s in sequences:
if len(s) > 0:
sample_shape = np.asarray(s).shape[1:]
break
is_dtype_str = np.issubdtype(dtype, np.str_) or np.issubdtype(dtype, np.unicode_)
if isinstance(value, str) and dtype != object and not is_dtype_str:
raise ValueError("`dtype` {} is not compatible with `value`'s type: {}\n"
"You should set `dtype=object` for variable length strings."
.format(dtype, type(value)))
x = np.full((num_samples, maxlen) + sample_shape, value, dtype=dtype)
for idx, s in enumerate(sequences):
if not len(s):
continue # empty list/array was found
if truncating == 'pre':
trunc = s[-maxlen:]
elif truncating == 'post':
trunc = s[:maxlen]
else:
raise ValueError(f'Truncating type not support')
# check `trunc` has expected shape
trunc = np.asarray(trunc, dtype=dtype)
if trunc.shape[1:] != sample_shape:
raise ValueError('Shape of sample %s of sequence at position %s '
'is different from expected shape %s' %
(trunc.shape[1:], idx, sample_shape))
if padding == 'post':
x[idx, :len(trunc)] = trunc
elif padding == 'pre':
x[idx, -len(trunc):] = trunc
else:
raise ValueError('Padding type not support')
return x
def get_file_logger(logger_name, log_file='./qiznlp.log', level='DEBUG'):
level = {
'ERROR': logging.ERROR,
'INFO': logging.INFO,
'DEBUG': logging.DEBUG,
'NOTSET': logging.NOTSET,
}.get(level, logging.DEBUG)
logger = logging.getLogger(logger_name)
logger.setLevel(level)
fh = logging.handlers.TimedRotatingFileHandler(log_file, when="D", interval=1, backupCount=7, encoding="utf-8")
fh.suffix = "%Y-%m-%d.log" # 设置后缀名称,跟strftime的格式一样
fh.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}.log$") # _\d{2}-\d{2}
fh.setLevel(level)
fh.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(fh)
logger.propagate = False # 取消传递,只有这样才不会传到logger_root然后又在控制台也打印一遍
return logger
def suppress_tf_warning(tf):
import warnings
warnings.filterwarnings('ignore')
tf.logging.set_verbosity(tf.logging.ERROR)
def flat_list(lst_in_lst):
# lst_in_lst: 二维列表
return sum(lst_in_lst, []) # flatten
def split_list(lst, len_lst):
# 按照len_lst对应的长度来来切分lst
# batch_num_span = list(map(lambda x: int(x * (x + 1) / 2), batch_seq_len))
# num_span_indices = np.cumsum(batch_num_span).tolist()
# split_lst = [ner_span_lst_of_batch[i:j] for i, j in zip([0] + num_span_indices, num_span_indices)]
assert sum(len_lst) == len(lst)
lst_ = copy.deepcopy(lst)
ret_lst = []
for length in len_lst:
ret_lst.append(lst_[:length])
lst_ = lst_[length:]
return ret_lst
def find_files(dir_name, pattern=None):
dir_name = Path(dir_name)
if pattern is None:
files = dir_name.iterdir()
else:
files = list(dir_name.glob(pattern)) # pattern = '*.py'
return files
def find_latest_file(dir_name, pattern=None):
dir_name = Path(dir_name)
if pattern is None:
files = dir_name.iterdir()
else:
files = dir_name.glob(pattern) # pattern = '*.py'
files = sorted(files, key=lambda e: e.lstat().st_mtime, reverse=True)
# files = [os.path.join(dir_name, f) for f in os.listdir(dir_name)]
# files = sorted(glob.glob(dir_name+'/*.pth'), key=os.path.getmtime, reverse=True)
if len(files) > 0:
return str(files[0])
else:
print('not found!')
return None
def del_if_exists(dir_or_path_name, pattern=None):
dir_or_path_name = Path(dir_or_path_name)
if not dir_or_path_name.exists():
return
if dir_or_path_name.is_dir():
if pattern is None:
files = dir_or_path_name.iterdir()
else:
files = dir_or_path_name.glob(pattern) # pattern = '*.py'
for file in files:
file.unlink()
else:
dir_or_path_name.unlink()
def get_curr_time_str(pattern=None):
if pattern is None:
pattern = '%y_%m_%d_%H_%M' # 21_09_12_11_12
# pattern = '%y_%m_%d_%H_%M_%S' # 21_09_12_11_12_34 for seconds
# pattern = '%y_%m_%d_%H_%M_%S_%f' # 21_09_12_11_12_34_123456 for microsecond微秒
# time_str = time.strftime(pattern, time.localtime(time.time()))
time_str = datetime.datetime.now().strftime(pattern)
return time_str
def cal_time(since):
now = time.time()
s = now - since
m = s // 60
s -= m * 60
return '%dm %ds' % (m, s)
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
def get_args_like_object():
return argparse.Namespace()
def save_args_to_json_file(args, json_file, verbose=False):
# args_json = {k: v for k, v in vars(args).items() if isinstance(v, (str, int, float))} # only save certain type supported by json
# def save_list(v):
# if isinstance(v, list):
# if not v or all(isinstance(v_, (str, int, float)) for v_ in v):
# return True
# return False
# args_json = {k: v for k, v in vars(args).items() if isinstance(v, (str, int, float)) or save_list(v)} # only save certain type supported by json
args_json = {}
for k, v in vars(args).items():
if isinstance(v, (str, int, float)): # json valid types
args_json[k] = v
elif isinstance(v, list): # list of valid types
if all(isinstance(v_, (str, int, float)) for v_ in v):
args_json[k] = v
elif isinstance(v, Path): # Path object saved as string
args_json[k] = str(v)
else:
pass
save_json(args_json, json_file, verbose=verbose)
def load_args_by_json_file(json_file, exist_args=None, verbose=True):
args_json = load_json(json_file)
if exist_args is None:
args = argparse.Namespace()
else:
args = exist_args
for k, v in args_json.items():
setattr(args, k, v)
if verbose:
print(f'Load {json_file} for {"exist" if exist_args else "new"} args success!')
return args
def print_vars(obj, sort=False, maxlen=200):
"""
print_vars(args)
"""
if hasattr(obj, '__dict__'): # normal object, args, ...
dct = vars(obj)
else:
dct = obj
assert isinstance(dct, dict)
it = sorted(dct.items()) if sort else dct.items()
for k, v in it:
v = str(v)
print(f'{k}: {v[:maxlen] + "..." if len(v) > maxlen else v}')
def setup_seed(seed: int, np, torch):
os.environ['PYTHONHASHSEED'] = str(seed)
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
# torch.cuda.cudnn_enabled = False
# torch.backends.cudnn.enabled = False
def stats(array):
mean = np.mean(array)
std = np.std(array)
out = f'{mean:.2f}±{std:.2f}'
print(out)
return out
def print_setup(np, torch):
np.set_printoptions(linewidth=4000, suppress=True) # 多长换行 不打印科学计数法
torch.set_printoptions(linewidth=4000, sci_mode=False) # 多长换行 不打印科学计数法
# np.set_printoptions(precision=2) # decimal 小数点位数
# np.set_printoptions(threshold=sys.maxsize) # 打印是否截断
# np.set_printoptions(linewidth=4000) # 多长换行
# np.set_printoptions(suppress=True) # 不打印科学计数法
def sort_by_idx(lst, ids=None, prev_num=None):
if ids is None:
return lst
sorted_lst = []
for idx in ids:
sorted_lst.append(lst[idx])
if prev_num is not None:
sorted_lst.extend(lst[prev_num:])
return sorted_lst
class Remote_Open:
"""
ro = Remote_Open(host_ip, port, username, password)
f = ro.open(json_file_path) # need close()
json = ro.load_json(json_file_path)
jsonl = ro.load_jsonl(jsonl_file_path)
nparray = ro.load_np(np_file_path)
tenosr = ro.load_pt(pt_file_path)
"""