pyxllib 0.3.197__py3-none-any.whl → 3.201.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyxllib/__init__.py +14 -21
- pyxllib/algo/__init__.py +8 -8
- pyxllib/algo/disjoint.py +54 -54
- pyxllib/algo/geo.py +537 -541
- pyxllib/algo/intervals.py +964 -964
- pyxllib/algo/matcher.py +389 -389
- pyxllib/algo/newbie.py +166 -166
- pyxllib/algo/pupil.py +629 -629
- pyxllib/algo/shapelylib.py +67 -67
- pyxllib/algo/specialist.py +241 -241
- pyxllib/algo/stat.py +494 -494
- pyxllib/algo/treelib.py +145 -149
- pyxllib/algo/unitlib.py +62 -66
- pyxllib/autogui/__init__.py +5 -5
- pyxllib/autogui/activewin.py +246 -246
- pyxllib/autogui/all.py +9 -9
- pyxllib/autogui/autogui.py +846 -852
- pyxllib/autogui/uiautolib.py +362 -362
- pyxllib/autogui/virtualkey.py +102 -102
- pyxllib/autogui/wechat.py +827 -827
- pyxllib/autogui/wechat_msg.py +421 -421
- pyxllib/autogui/wxautolib.py +84 -84
- pyxllib/cv/__init__.py +5 -5
- pyxllib/cv/expert.py +267 -267
- pyxllib/cv/imfile.py +159 -159
- pyxllib/cv/imhash.py +39 -39
- pyxllib/cv/pupil.py +9 -9
- pyxllib/cv/rgbfmt.py +1525 -1525
- pyxllib/cv/slidercaptcha.py +137 -137
- pyxllib/cv/trackbartools.py +251 -251
- pyxllib/cv/xlcvlib.py +1040 -1040
- pyxllib/cv/xlpillib.py +423 -423
- pyxllib/data/echarts.py +236 -240
- pyxllib/data/jsonlib.py +85 -89
- pyxllib/data/oss.py +72 -72
- pyxllib/data/pglib.py +1111 -1127
- pyxllib/data/sqlite.py +568 -568
- pyxllib/data/sqllib.py +297 -297
- pyxllib/ext/JLineViewer.py +505 -505
- pyxllib/ext/__init__.py +6 -6
- pyxllib/ext/demolib.py +251 -246
- pyxllib/ext/drissionlib.py +277 -277
- pyxllib/ext/kq5034lib.py +12 -12
- pyxllib/ext/qt.py +449 -449
- pyxllib/ext/robustprocfile.py +493 -497
- pyxllib/ext/seleniumlib.py +76 -76
- pyxllib/ext/tk.py +173 -173
- pyxllib/ext/unixlib.py +821 -827
- pyxllib/ext/utools.py +345 -351
- pyxllib/ext/webhook.py +124 -119
- pyxllib/ext/win32lib.py +40 -40
- pyxllib/ext/wjxlib.py +91 -88
- pyxllib/ext/wpsapi.py +124 -124
- pyxllib/ext/xlwork.py +9 -9
- pyxllib/ext/yuquelib.py +1110 -1105
- pyxllib/file/__init__.py +17 -17
- pyxllib/file/docxlib.py +757 -761
- pyxllib/file/gitlib.py +309 -309
- pyxllib/file/libreoffice.py +165 -165
- pyxllib/file/movielib.py +144 -148
- pyxllib/file/newbie.py +10 -10
- pyxllib/file/onenotelib.py +1469 -1469
- pyxllib/file/packlib/__init__.py +330 -330
- pyxllib/file/packlib/zipfile.py +2441 -2441
- pyxllib/file/pdflib.py +422 -426
- pyxllib/file/pupil.py +185 -185
- pyxllib/file/specialist/__init__.py +681 -685
- pyxllib/file/specialist/dirlib.py +799 -799
- pyxllib/file/specialist/download.py +193 -193
- pyxllib/file/specialist/filelib.py +2825 -2829
- pyxllib/file/xlsxlib.py +3122 -3131
- pyxllib/file/xlsyncfile.py +341 -341
- pyxllib/prog/__init__.py +5 -5
- pyxllib/prog/cachetools.py +58 -64
- pyxllib/prog/deprecatedlib.py +233 -233
- pyxllib/prog/filelock.py +42 -42
- pyxllib/prog/ipyexec.py +253 -253
- pyxllib/prog/multiprogs.py +940 -940
- pyxllib/prog/newbie.py +451 -451
- pyxllib/prog/pupil.py +1208 -1197
- pyxllib/prog/sitepackages.py +33 -33
- pyxllib/prog/specialist/__init__.py +348 -391
- pyxllib/prog/specialist/bc.py +203 -203
- pyxllib/prog/specialist/browser.py +497 -497
- pyxllib/prog/specialist/common.py +347 -347
- pyxllib/prog/specialist/datetime.py +198 -198
- pyxllib/prog/specialist/tictoc.py +240 -240
- pyxllib/prog/specialist/xllog.py +180 -180
- pyxllib/prog/xlosenv.py +110 -108
- pyxllib/stdlib/__init__.py +17 -17
- pyxllib/stdlib/tablepyxl/__init__.py +10 -10
- pyxllib/stdlib/tablepyxl/style.py +303 -303
- pyxllib/stdlib/tablepyxl/tablepyxl.py +130 -130
- pyxllib/text/__init__.py +8 -8
- pyxllib/text/ahocorasick.py +36 -39
- pyxllib/text/airscript.js +754 -744
- pyxllib/text/charclasslib.py +121 -121
- pyxllib/text/jiebalib.py +267 -267
- pyxllib/text/jinjalib.py +27 -32
- pyxllib/text/jsa_ai_prompt.md +271 -271
- pyxllib/text/jscode.py +922 -922
- pyxllib/text/latex/__init__.py +158 -158
- pyxllib/text/levenshtein.py +303 -303
- pyxllib/text/nestenv.py +1215 -1215
- pyxllib/text/newbie.py +300 -300
- pyxllib/text/pupil/__init__.py +8 -8
- pyxllib/text/pupil/common.py +1121 -1121
- pyxllib/text/pupil/xlalign.py +326 -326
- pyxllib/text/pycode.py +47 -47
- pyxllib/text/specialist/__init__.py +8 -8
- pyxllib/text/specialist/common.py +112 -112
- pyxllib/text/specialist/ptag.py +186 -186
- pyxllib/text/spellchecker.py +172 -172
- pyxllib/text/templates/echart_base.html +10 -10
- pyxllib/text/templates/highlight_code.html +16 -16
- pyxllib/text/templates/latex_editor.html +102 -102
- pyxllib/text/vbacode.py +17 -17
- pyxllib/text/xmllib.py +741 -747
- pyxllib/xl.py +42 -39
- pyxllib/xlcv.py +17 -17
- pyxllib-3.201.1.dist-info/METADATA +296 -0
- pyxllib-3.201.1.dist-info/RECORD +125 -0
- {pyxllib-0.3.197.dist-info → pyxllib-3.201.1.dist-info}/licenses/LICENSE +190 -190
- pyxllib/ext/old.py +0 -663
- pyxllib-0.3.197.dist-info/METADATA +0 -48
- pyxllib-0.3.197.dist-info/RECORD +0 -126
- {pyxllib-0.3.197.dist-info → pyxllib-3.201.1.dist-info}/WHEEL +0 -0
pyxllib/ext/robustprocfile.py
CHANGED
@@ -1,497 +1,493 @@
|
|
1
|
-
#!/usr/bin/env python3
|
2
|
-
# -*- coding: utf-8 -*-
|
3
|
-
# @Author : 陈坤泽
|
4
|
-
# @Email : 877362867@qq.com
|
5
|
-
# @Date : 2024/03/28
|
6
|
-
|
7
|
-
"""
|
8
|
-
处理数据文件常用的拆分逻辑
|
9
|
-
|
10
|
-
半定制化的功能组件
|
11
|
-
"""
|
12
|
-
|
13
|
-
from
|
14
|
-
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
import
|
19
|
-
import
|
20
|
-
|
21
|
-
|
22
|
-
from
|
23
|
-
|
24
|
-
|
25
|
-
|
26
|
-
|
27
|
-
|
28
|
-
|
29
|
-
def
|
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
|
-
func_args
|
125
|
-
|
126
|
-
|
127
|
-
|
128
|
-
|
129
|
-
|
130
|
-
|
131
|
-
|
132
|
-
|
133
|
-
|
134
|
-
|
135
|
-
|
136
|
-
|
137
|
-
|
138
|
-
|
139
|
-
|
140
|
-
|
141
|
-
|
142
|
-
|
143
|
-
self.counters
|
144
|
-
|
145
|
-
def
|
146
|
-
#
|
147
|
-
self.counters
|
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
|
-
self.
|
207
|
-
|
208
|
-
|
209
|
-
self.
|
210
|
-
self.
|
211
|
-
|
212
|
-
|
213
|
-
|
214
|
-
|
215
|
-
|
216
|
-
|
217
|
-
|
218
|
-
|
219
|
-
|
220
|
-
|
221
|
-
|
222
|
-
|
223
|
-
|
224
|
-
|
225
|
-
|
226
|
-
|
227
|
-
|
228
|
-
|
229
|
-
|
230
|
-
|
231
|
-
self.
|
232
|
-
|
233
|
-
|
234
|
-
|
235
|
-
|
236
|
-
|
237
|
-
|
238
|
-
|
239
|
-
|
240
|
-
|
241
|
-
|
242
|
-
|
243
|
-
|
244
|
-
|
245
|
-
|
246
|
-
|
247
|
-
self.
|
248
|
-
|
249
|
-
self.
|
250
|
-
|
251
|
-
|
252
|
-
|
253
|
-
self.
|
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
|
-
if debug: #
|
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
|
-
for k in
|
368
|
-
d
|
369
|
-
|
370
|
-
d =
|
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
|
-
if
|
408
|
-
|
409
|
-
|
410
|
-
d =
|
411
|
-
d
|
412
|
-
|
413
|
-
d
|
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
|
-
:param
|
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
|
-
show_tqdm=processes_num == 1)
|
495
|
-
tasks.append(task)
|
496
|
-
|
497
|
-
Parallel(n_jobs=processes_num, backend=backend)(tasks)
|
1
|
+
#!/usr/bin/env python3
|
2
|
+
# -*- coding: utf-8 -*-
|
3
|
+
# @Author : 陈坤泽
|
4
|
+
# @Email : 877362867@qq.com
|
5
|
+
# @Date : 2024/03/28
|
6
|
+
|
7
|
+
"""
|
8
|
+
处理数据文件常用的拆分逻辑
|
9
|
+
|
10
|
+
半定制化的功能组件
|
11
|
+
"""
|
12
|
+
|
13
|
+
from collections import defaultdict, Counter
|
14
|
+
import datetime
|
15
|
+
import re
|
16
|
+
import json
|
17
|
+
|
18
|
+
from tqdm import tqdm
|
19
|
+
from joblib import Parallel, delayed
|
20
|
+
|
21
|
+
from pyxllib.prog.pupil import check_counter, tprint, typename
|
22
|
+
from pyxllib.file.specialist import XlPath, refinepath
|
23
|
+
|
24
|
+
|
25
|
+
def get_timestamp(fmt='%Y%m%d%H%M%S'):
|
26
|
+
return datetime.datetime.now().strftime(fmt)
|
27
|
+
|
28
|
+
|
29
|
+
def process_file_base(file_func, file, correct_tag, error_tag,
|
30
|
+
*,
|
31
|
+
correct_dir=None, error_dir=None,
|
32
|
+
correct_file_name=None, error_file_name=None,
|
33
|
+
split_group_func=None,
|
34
|
+
reset=False):
|
35
|
+
""" 处理单个文件数据,默认将两套运行结果放在同目录的两个文件中
|
36
|
+
|
37
|
+
:param file_func: 对于自定义的处理函数
|
38
|
+
返回支持1个参数,2个参数。1个参数时,默认没有错误的记录数据。
|
39
|
+
对于数据,支持list[str]或list[dict]等多种格式
|
40
|
+
:param split_group_func: 对正确的数据,按照某种规则进一步分组
|
41
|
+
"""
|
42
|
+
|
43
|
+
# 0 工具函数
|
44
|
+
def remove_old_file(new_file):
|
45
|
+
# 如果目录下有同名函数,仅最后的时间戳不同的旧文件,删除
|
46
|
+
stem = re.sub(r'_\d{14}$', '', new_file.stem)
|
47
|
+
fmt_str = fr'{stem}_\d{{14}}{new_file.suffix}'
|
48
|
+
for f in new_file.parent.glob(f'{stem}_*{new_file.suffix}'):
|
49
|
+
if re.match(fmt_str, f.name):
|
50
|
+
f.delete()
|
51
|
+
|
52
|
+
def write_file(_dir, name, tag, data):
|
53
|
+
if name is None:
|
54
|
+
suffix = file.suffix if isinstance(data[0], str) else '.jsonl'
|
55
|
+
name = f'{file.stem}_{tag}{len(data)}_{get_timestamp()}{suffix}'
|
56
|
+
_file = _dir / name
|
57
|
+
_file.parent.mkdir(exist_ok=True, parents=True)
|
58
|
+
if reset: # 找到旧后缀的文件,删除,排除时间戳差异的文件检索
|
59
|
+
remove_old_file(_file)
|
60
|
+
|
61
|
+
if isinstance(data[0], str):
|
62
|
+
_file.write_text('\n'.join(data))
|
63
|
+
else:
|
64
|
+
_file.write_jsonl(data)
|
65
|
+
|
66
|
+
# 1 处理数据
|
67
|
+
file = XlPath(file)
|
68
|
+
res = file_func(file)
|
69
|
+
if isinstance(res, tuple) and len(res) == 2:
|
70
|
+
correct_data, error_data = res
|
71
|
+
else:
|
72
|
+
correct_data = res
|
73
|
+
error_data = None
|
74
|
+
|
75
|
+
# 2 计算标准文件名
|
76
|
+
if correct_data:
|
77
|
+
correct_dir = file.parent if correct_dir is None else XlPath(correct_dir)
|
78
|
+
suffix = file.suffix if isinstance(correct_data[0], str) else '.jsonl'
|
79
|
+
if split_group_func: # 使用split_group_func的时候,split_group_func不生效
|
80
|
+
group_data = defaultdict(list)
|
81
|
+
for x in correct_data:
|
82
|
+
group_data[split_group_func(x)].append(x)
|
83
|
+
|
84
|
+
for k, correct_data in group_data.items():
|
85
|
+
correct_file_name2 = (f'{file.stem}_{refinepath(k)}_'
|
86
|
+
f'{correct_tag}{len(correct_data)}_{get_timestamp()}{suffix}')
|
87
|
+
write_file(correct_dir, correct_file_name2, correct_tag, correct_data)
|
88
|
+
else:
|
89
|
+
write_file(correct_dir, correct_file_name, correct_tag, correct_data)
|
90
|
+
if error_data:
|
91
|
+
error_dir = file.parent if error_dir is None else XlPath(error_dir)
|
92
|
+
write_file(error_dir, error_file_name, error_tag, error_data)
|
93
|
+
|
94
|
+
|
95
|
+
def process_dir_base(file_func, dir_path, correct_tag, error_tag,
|
96
|
+
*, pattern='*', correct_dir=None, error_dir=None, reset=False,
|
97
|
+
**kwargs):
|
98
|
+
""" 处理一个目录下的所有文件
|
99
|
+
"""
|
100
|
+
dir_path = XlPath(dir_path)
|
101
|
+
correct_dir = XlPath(correct_dir) if correct_dir else (dir_path.parent / f'{dir_path.name}_{correct_tag}')
|
102
|
+
error_dir = XlPath(error_dir) if error_dir else (dir_path.parent / f'{dir_path.name}_{error_tag}')
|
103
|
+
|
104
|
+
files = list(dir_path.rglob(pattern))
|
105
|
+
for idx, file in enumerate(files, start=1):
|
106
|
+
tprint(f'处理完第{idx}/{len(files)}个文件: {file.name} ==> {correct_tag}')
|
107
|
+
process_file_base(file_func, file, correct_tag, error_tag,
|
108
|
+
correct_dir=correct_dir, error_dir=error_dir, reset=reset,
|
109
|
+
**kwargs)
|
110
|
+
|
111
|
+
|
112
|
+
def process_path(file_func, tag, path, **kwargs):
|
113
|
+
""" 对单文件,或者目录处理的封装 """
|
114
|
+
path = XlPath(path)
|
115
|
+
|
116
|
+
if isinstance(file_func, str): # 用命令行等接口的时候,输入可能是字符串名
|
117
|
+
file_func = globals()[file_func]
|
118
|
+
|
119
|
+
# 有些特殊参数,是预设给func使用的
|
120
|
+
func_args = {}
|
121
|
+
if 'remove_repeat_mode' in kwargs:
|
122
|
+
func_args['remove_repeat_mode'] = kwargs.pop('remove_repeat_mode')
|
123
|
+
|
124
|
+
if func_args:
|
125
|
+
file_func2 = lambda x: file_func(x, **func_args)
|
126
|
+
else:
|
127
|
+
file_func2 = file_func
|
128
|
+
|
129
|
+
if path.is_file():
|
130
|
+
process_file_base(file_func2, path, tag, f'{tag}error', **kwargs)
|
131
|
+
elif path.is_dir():
|
132
|
+
process_dir_base(file_func2, path, tag, f'{tag}error', **kwargs)
|
133
|
+
|
134
|
+
|
135
|
+
class Analyzer:
|
136
|
+
""" 分析器,一般用来写一些不影响主体功能,协助调试,分析数据特征的功能 """
|
137
|
+
|
138
|
+
def __init__(self):
|
139
|
+
self.counters = defaultdict(Counter)
|
140
|
+
|
141
|
+
def count_once(self, tag, key):
|
142
|
+
# tag相当于需要分组统计的名称
|
143
|
+
self.counters[tag][key] += 1
|
144
|
+
|
145
|
+
def check_counter(self):
|
146
|
+
# 检查各种特征出现的次数
|
147
|
+
for name, ct in self.counters.items():
|
148
|
+
print(f'【{name}】')
|
149
|
+
check_counter(ct)
|
150
|
+
|
151
|
+
|
152
|
+
def head_data(infile, num=1000, file_size=50):
|
153
|
+
""" 获取infile头部部分数据
|
154
|
+
|
155
|
+
:param file_size: 除了数量限制外,同时限制文件大小不超过file_size MB
|
156
|
+
这里不是精确解法,而是简化大概的写法
|
157
|
+
"""
|
158
|
+
res = []
|
159
|
+
total_size = 0
|
160
|
+
for x in XlPath(infile).yield_line(end=num):
|
161
|
+
sz = len(x)
|
162
|
+
total_size += sz
|
163
|
+
if total_size > file_size * 1024 * 1024:
|
164
|
+
break
|
165
|
+
res.append(x)
|
166
|
+
|
167
|
+
return res
|
168
|
+
|
169
|
+
|
170
|
+
def remove_repeat_base(infile,
|
171
|
+
get_etags_func,
|
172
|
+
exists_etags=set(), # trick: 这里需要全局记录已出现过的etag
|
173
|
+
):
|
174
|
+
""" 去除重复数据,基础函数
|
175
|
+
|
176
|
+
:param get_etags_func: 每道题目的etag,用于判断是否重复
|
177
|
+
可能用于判断的etags数量不止一个,可以返回多个
|
178
|
+
返回一个值的版本也可以,会自动转换为list
|
179
|
+
"""
|
180
|
+
data = XlPath(infile).read_jsonl()
|
181
|
+
src_len = len(data)
|
182
|
+
|
183
|
+
data2 = []
|
184
|
+
for x in data:
|
185
|
+
etags = get_etags_func(x)
|
186
|
+
if isinstance(etags, str):
|
187
|
+
etags = [etags]
|
188
|
+
if any(etag in exists_etags for etag in etags):
|
189
|
+
continue
|
190
|
+
data2.append(x)
|
191
|
+
exists_etags.update(set(etags))
|
192
|
+
|
193
|
+
new_len = len(data2)
|
194
|
+
print(f'去重后剩余 {new_len}/{src_len} ≈ {new_len / src_len:.2%} 的数据')
|
195
|
+
return data2
|
196
|
+
|
197
|
+
|
198
|
+
class CacheJsonlFile:
|
199
|
+
""" 流式存储文件 """
|
200
|
+
|
201
|
+
def __init__(self, parent_dir, prefix_stem, tag, batch_size=2000):
|
202
|
+
self.parent_dir = parent_dir
|
203
|
+
self.prefix_stem = prefix_stem
|
204
|
+
self.tag = tag
|
205
|
+
self.cache_text_lines = []
|
206
|
+
self.batch_size = batch_size
|
207
|
+
|
208
|
+
# 缓存时的文件名
|
209
|
+
self.cache_file = XlPath(parent_dir) / f'{prefix_stem}_{tag}.cache.jsonl'
|
210
|
+
self.total = 0
|
211
|
+
|
212
|
+
def append(self, data):
|
213
|
+
for x in data:
|
214
|
+
if isinstance(x, str):
|
215
|
+
self.cache_text_lines.append(x)
|
216
|
+
else:
|
217
|
+
self.cache_text_lines.append(json.dumps(x, ensure_ascii=False))
|
218
|
+
if len(self.cache_text_lines) >= self.batch_size:
|
219
|
+
self.flush()
|
220
|
+
|
221
|
+
def flush(self):
|
222
|
+
""" 刷新,将当前缓存写入文件 """
|
223
|
+
if self.cache_text_lines:
|
224
|
+
if self.total == 0: # 第一次写入时,删除旧缓存文件
|
225
|
+
self.cache_file.delete()
|
226
|
+
|
227
|
+
self.total += len(self.cache_text_lines)
|
228
|
+
self.parent_dir.mkdir(exist_ok=True, parents=True)
|
229
|
+
with open(self.cache_file, 'a', encoding='utf8') as f:
|
230
|
+
f.write('\n'.join(self.cache_text_lines) + '\n')
|
231
|
+
self.cache_text_lines = []
|
232
|
+
|
233
|
+
def save_all(self):
|
234
|
+
""" 最终存储的文件名 """
|
235
|
+
self.flush()
|
236
|
+
if self.cache_file.is_file():
|
237
|
+
dst_file = self.cache_file.with_stem(f'{self.prefix_stem}_{self.tag}{self.total}_{get_timestamp()}')
|
238
|
+
self.cache_file.rename(dst_file)
|
239
|
+
|
240
|
+
|
241
|
+
class CacheJsonlGroupFiles:
|
242
|
+
def __init__(self, parent_dir, prefix_stem, tag, group_func=None, batch_size=2000):
|
243
|
+
self.files = {}
|
244
|
+
|
245
|
+
self.parent_dir = parent_dir
|
246
|
+
self.prefix_stem = prefix_stem
|
247
|
+
self.tag = tag
|
248
|
+
self.group_func = group_func
|
249
|
+
self.batch_size = batch_size
|
250
|
+
|
251
|
+
def append(self, data):
|
252
|
+
groups = defaultdict(list)
|
253
|
+
if self.group_func:
|
254
|
+
for x in data:
|
255
|
+
groups[self.group_func(x)].append(x)
|
256
|
+
else:
|
257
|
+
groups[''] = data
|
258
|
+
|
259
|
+
for k, v in groups.items():
|
260
|
+
if k not in self.files:
|
261
|
+
subtag = f'{k}_{self.tag}' if k not in ('', None) else self.tag
|
262
|
+
self.files[k] = CacheJsonlFile(self.parent_dir, self.prefix_stem, subtag, self.batch_size)
|
263
|
+
self.files[k].append(v)
|
264
|
+
|
265
|
+
def save_all(self):
|
266
|
+
for file in self.files.values():
|
267
|
+
file.save_all()
|
268
|
+
|
269
|
+
|
270
|
+
def process_single_file(root,
|
271
|
+
infile,
|
272
|
+
tag,
|
273
|
+
row_func,
|
274
|
+
*,
|
275
|
+
cur_idx=1,
|
276
|
+
total=None,
|
277
|
+
if_exists='skip',
|
278
|
+
group_func=None,
|
279
|
+
batch_size=2000,
|
280
|
+
debug=False,
|
281
|
+
show_tqdm=False):
|
282
|
+
def finished():
|
283
|
+
if total:
|
284
|
+
tprint(f'处理第{cur_idx}/{total}个文件:{infile.name} ==> {tag}')
|
285
|
+
else:
|
286
|
+
tprint(f'处理文件:{infile.name} ==> {tag}')
|
287
|
+
|
288
|
+
# 1 缓存路径
|
289
|
+
srcdir = XlPath(root)
|
290
|
+
infile = XlPath.init(infile, root=srcdir)
|
291
|
+
relpath = infile.relative_to(srcdir)
|
292
|
+
|
293
|
+
dstdir = srcdir.parent / f'{srcdir.name}_{tag}' / relpath.parent
|
294
|
+
errdir = srcdir.parent / f'{srcdir.name}_{tag}error' / relpath.parent
|
295
|
+
|
296
|
+
# 2 判断是不是已处理过的文件
|
297
|
+
# stem = re.split(r'\d+_\d{14}', relpath.stem)[0]
|
298
|
+
stem = relpath.stem + f'_{tag}'
|
299
|
+
dstfiles = list(dstdir.glob_files(f'{stem}*.jsonl'))
|
300
|
+
errfiles = list(errdir.glob_files(f'{stem}*.jsonl'))
|
301
|
+
|
302
|
+
# 需要进一步过滤
|
303
|
+
def is_exists_old_file(f):
|
304
|
+
if f.name.endswith('.cache.jsonl'):
|
305
|
+
return False
|
306
|
+
stem2 = f.name[len(stem):]
|
307
|
+
if re.match(r'(error)?\d+_\d{14}.jsonl$', stem2):
|
308
|
+
return True
|
309
|
+
|
310
|
+
# cache文件不算,不用管
|
311
|
+
check_files = [f for f in (dstfiles + errfiles) if is_exists_old_file(f)]
|
312
|
+
|
313
|
+
if check_files:
|
314
|
+
if if_exists == 'skip':
|
315
|
+
finished()
|
316
|
+
return
|
317
|
+
elif if_exists == 'overwrite':
|
318
|
+
for f in check_files:
|
319
|
+
f.delete()
|
320
|
+
elif if_exists == 'error':
|
321
|
+
raise FileExistsError(f'目标文件已存在:{check_files}')
|
322
|
+
else:
|
323
|
+
finished()
|
324
|
+
return
|
325
|
+
|
326
|
+
# 3 处理数据
|
327
|
+
if debug: # 如果开启调试模式,则关闭分组功能
|
328
|
+
group_func = None
|
329
|
+
dstcgf = CacheJsonlGroupFiles(dstdir, infile.stem, tag, group_func, batch_size)
|
330
|
+
errcgf = CacheJsonlGroupFiles(errdir, infile.stem, tag + 'error', batch_size=batch_size)
|
331
|
+
if debug: # 如果开启调试模式,则单独分错误文件
|
332
|
+
errcgf = dstcgf
|
333
|
+
|
334
|
+
for line in tqdm(infile.yield_line(), desc=f'{infile.name} ==> {tag}', disable=not show_tqdm):
|
335
|
+
# todo 出错的数据,应该添加错误信息,也存成一个新的jsonl格式
|
336
|
+
row = row_func(line)
|
337
|
+
if row and (not isinstance(row, dict) or row.get('status', 'ok') == 'ok'):
|
338
|
+
# 必须要有内容,但如果内容有个status字段且不是'ok',也不能要
|
339
|
+
dstcgf.append([row])
|
340
|
+
else:
|
341
|
+
# 注意旧版存储的事line,但是新版的存储成row了
|
342
|
+
# 但如果row确实没内容,还是兼容旧版,存储line
|
343
|
+
errcgf.append([row or line])
|
344
|
+
|
345
|
+
dstcgf.save_all()
|
346
|
+
errcgf.save_all()
|
347
|
+
finished()
|
348
|
+
|
349
|
+
|
350
|
+
class StructureAnalyzer:
|
351
|
+
@classmethod
|
352
|
+
def item_to_json(cls, x, depth):
|
353
|
+
""" 获得字典结构的签名
|
354
|
+
|
355
|
+
todo 这个项目之后,可以对这个函数进一步优化精简,作为以后解析结构的一个通用工具
|
356
|
+
"""
|
357
|
+
if depth <= 0:
|
358
|
+
return typename(x)
|
359
|
+
|
360
|
+
if isinstance(x, dict):
|
361
|
+
d = {}
|
362
|
+
keys = sorted(x.keys())
|
363
|
+
for k in keys:
|
364
|
+
d[k] = cls.item_to_json(x[k], depth - 1)
|
365
|
+
elif isinstance(x, list):
|
366
|
+
d = []
|
367
|
+
for k in x:
|
368
|
+
d.append(cls.item_to_json(k, depth - 1))
|
369
|
+
else:
|
370
|
+
d = typename(x)
|
371
|
+
|
372
|
+
return d
|
373
|
+
|
374
|
+
@classmethod
|
375
|
+
def item_to_str(cls, x, depth):
|
376
|
+
res = cls.item_to_json(x, depth)
|
377
|
+
return json.dumps(res)
|
378
|
+
|
379
|
+
@classmethod
|
380
|
+
def group_items(cls, items, depth):
|
381
|
+
ct = Counter()
|
382
|
+
groups = defaultdict(list)
|
383
|
+
for x in items:
|
384
|
+
desc = cls.item_to_str(x, depth)
|
385
|
+
ct[desc] += 1
|
386
|
+
groups[desc].append(x)
|
387
|
+
# 按照值的数量对groups排序
|
388
|
+
groups = dict(sorted(groups.items(), key=lambda x: -len(x[1])))
|
389
|
+
return groups
|
390
|
+
|
391
|
+
@classmethod
|
392
|
+
def get_items_structures(cls, items, savefile=None):
|
393
|
+
""" 获取jsonl数据的结构分布
|
394
|
+
|
395
|
+
:param list[json] items: 一组json数据
|
396
|
+
:return list[json]: 统计每种结构的分布数量,按树形结构,从多到少排序展示
|
397
|
+
"""
|
398
|
+
|
399
|
+
def add_group(parent, items, depth, res):
|
400
|
+
tag = parent['depth'] if parent else ''
|
401
|
+
groups = cls.group_items(items, depth)
|
402
|
+
for i, (desc, items2) in enumerate(groups.items(), start=1):
|
403
|
+
if desc == parent['desc']: # 再细化的结果跟父结点相同时,不再加深层级
|
404
|
+
continue
|
405
|
+
|
406
|
+
d = {}
|
407
|
+
d['depth'] = f'{tag}-{i}' if tag else f'{i}'
|
408
|
+
d['count'] = len(items2)
|
409
|
+
d['desc'] = desc
|
410
|
+
d['structure'] = cls.item_to_json(items2[0], depth)
|
411
|
+
res.append(d)
|
412
|
+
|
413
|
+
add_group(d, items2, depth + 1, res)
|
414
|
+
|
415
|
+
res = [] # 初始化结果列表
|
416
|
+
add_group({'depth': '', 'desc': ''}, items, 1, res) # 从空标签开始递归
|
417
|
+
|
418
|
+
if savefile:
|
419
|
+
XlPath(savefile).write_jsonl(res)
|
420
|
+
|
421
|
+
return res
|
422
|
+
|
423
|
+
@classmethod
|
424
|
+
def compare_keys(cls, items):
|
425
|
+
""" 对从 get_items_structures 获得的数据,对比structure的覆盖情况 """
|
426
|
+
import pandas as pd
|
427
|
+
from pyxllib.algo.stat import custom_fillna
|
428
|
+
|
429
|
+
ls = []
|
430
|
+
for x in items:
|
431
|
+
row = {}
|
432
|
+
row['__depth'] = x['depth']
|
433
|
+
row['__count'] = x['count']
|
434
|
+
if isinstance(x['structure'], dict):
|
435
|
+
row.update(x['structure'])
|
436
|
+
elif isinstance(x['structure'], list):
|
437
|
+
row.update({f'[{k}]': v for k, v in enumerate(x['structure'])})
|
438
|
+
ls.append(row)
|
439
|
+
|
440
|
+
df = pd.DataFrame.from_dict(ls)
|
441
|
+
# 筛选df,depth中没有'-'
|
442
|
+
df = df[df['__depth'].apply(lambda x: '-' not in x)]
|
443
|
+
df = custom_fillna(df).T
|
444
|
+
|
445
|
+
return df
|
446
|
+
|
447
|
+
|
448
|
+
def process_batch_files(srcdir,
|
449
|
+
dsttag,
|
450
|
+
line_convert_func,
|
451
|
+
pattern='*.jsonl',
|
452
|
+
if_exists='skip',
|
453
|
+
processes_num=1,
|
454
|
+
group_func=None,
|
455
|
+
batch_size=2000,
|
456
|
+
debug=False,
|
457
|
+
):
|
458
|
+
""" 通用批处理函数
|
459
|
+
|
460
|
+
:param srcdir: 输入待处理的目录或文件
|
461
|
+
:param pattern: 文件名检索逻辑,如 '*','*.jsonl', '*_std*.jsonl'等
|
462
|
+
:param if_exists: 如果目标文件已存在,如何处理。'skip'跳过不重复处理,'overwrite'覆盖重新运行,'error'抛出报错
|
463
|
+
:param processes_num: 并发处理的进程数
|
464
|
+
:param batch_size: 每个文件缓存的条目数,超过这个数目后就会先写入文件
|
465
|
+
"""
|
466
|
+
# 1 检索文件
|
467
|
+
srcdir = XlPath(srcdir)
|
468
|
+
if srcdir.is_file():
|
469
|
+
files = [srcdir.name]
|
470
|
+
srcdir = srcdir.parent
|
471
|
+
else:
|
472
|
+
files = [f.relpath(srcdir) for f in srcdir.rglob_files(pattern)]
|
473
|
+
|
474
|
+
file_num = len(files)
|
475
|
+
|
476
|
+
# 2 并发处理多个文件
|
477
|
+
backend = 'loky' if processes_num > 1 else 'sequential'
|
478
|
+
tasks = []
|
479
|
+
for i, f in enumerate(files, start=1):
|
480
|
+
task = delayed(process_single_file)(srcdir,
|
481
|
+
f,
|
482
|
+
dsttag,
|
483
|
+
line_convert_func,
|
484
|
+
cur_idx=i,
|
485
|
+
total=file_num,
|
486
|
+
if_exists=if_exists,
|
487
|
+
group_func=group_func,
|
488
|
+
batch_size=batch_size,
|
489
|
+
debug=debug,
|
490
|
+
show_tqdm=processes_num == 1)
|
491
|
+
tasks.append(task)
|
492
|
+
|
493
|
+
Parallel(n_jobs=processes_num, backend=backend)(tasks)
|