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