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
@@ -2,7 +2,7 @@
2
2
  # -*- coding: utf-8 -*-
3
3
  # @Author : 陈坤泽
4
4
  # @Email : 877362867@qq.com
5
- # @Data : 2020/05/30 11:50
5
+ # @Date : 2020/05/30 11:50
6
6
 
7
7
 
8
8
  """
@@ -19,20 +19,28 @@ TODO 清单
19
19
  3、将数据以图片的直观形式展现
20
20
  """
21
21
 
22
- import subprocess
22
+ from pyxllib.prog.pupil import check_install_package
23
23
 
24
- try:
25
- import git
26
- except ModuleNotFoundError:
27
- subprocess.run(['pip', 'install', 'gitpython'])
28
- import git
24
+ check_install_package('git', 'gitpython')
29
25
 
30
- from pyxllib.util.filelib import *
26
+ import os
27
+ import re
31
28
 
29
+ import git
30
+ import pandas as pd
32
31
 
33
- class Git:
32
+ from pyxllib.prog.newbie import swap_rowcol
33
+ from pyxllib.prog.pupil import dprint
34
+ from pyxllib.prog.specialist import dataframe_str, bcompare
35
+ from pyxllib.text.pupil import digit2weektag
36
+ from pyxllib.file.specialist import Dir, File, filesmatch
37
+
38
+
39
+ # TODO 可以学习了解使用二次封装的 https://github.com/ishepard/pydriller 库来实现需求
40
+
41
+ class Git(git.Git):
34
42
  def __init__(self, repo_path):
35
- self.g = git.Git(repo_path)
43
+ super().__init__(str(repo_path))
36
44
 
37
45
  def commits_name(self, n=None, file=None):
38
46
  """ 每条commit的标题名称
@@ -45,29 +53,31 @@ class Git:
45
53
  cmd.append(f'-{n}')
46
54
  if file:
47
55
  cmd.append(file)
48
- return self.g.log(*cmd).splitlines()
56
+ return self.log(*cmd).splitlines()
49
57
 
50
58
  def commits_time0(self, n=None, file=None):
51
59
  """每条commit的提交时间
52
- 使用excel可以识别的时间格式"""
60
+ 使用excel可以识别的时间格式
61
+ """
53
62
  cmd = ['--pretty=%cd', '--date=format:%Y/%m/%d %H:%M']
54
63
  if n:
55
64
  cmd.append(f'-{n}')
56
65
  if file:
57
66
  cmd.append(file)
58
- t = self.g.log(*cmd)
67
+ t = self.log(*cmd)
59
68
 
60
69
  return t.splitlines()
61
70
 
62
71
  def commits_time(self, n=None, file=None):
63
72
  """每条commit的提交时间
64
- 参数含义参考commits_name里的解释"""
73
+ 参数含义参考commits_name里的解释
74
+ """
65
75
  cmd = ['--pretty=%cd', '--date=format:%y%m%d-%w-%H:%M']
66
76
  if n:
67
77
  cmd.append(f'-{n}')
68
78
  if file:
69
79
  cmd.append(file)
70
- t = self.g.log(*cmd)
80
+ t = self.log(*cmd)
71
81
 
72
82
  def myweektag(m):
73
83
  s = m.group().replace('0', '7')
@@ -79,16 +89,18 @@ class Git:
79
89
 
80
90
  def commits_sha(self, n=None, file=None) -> [str, str, ...]:
81
91
  """每条commit的sha哈希值
82
- 参数含义参考commits_name里的解释"""
92
+ 参数含义参考commits_name里的解释
93
+ """
83
94
  cmd = ['--pretty=%h']
84
95
  if n:
85
96
  cmd.append(f'-{n}')
86
97
  if file:
87
98
  cmd.append(file)
88
- return self.g.log(*cmd).splitlines()
99
+ return self.log(*cmd).splitlines()
89
100
 
90
101
  def commits_stat(self, n=None, file=None):
91
- """统计每个commits修改的文件数和插入行数、删除行数
102
+ """ 统计每个commits修改的文件数和插入行数、删除行数
103
+
92
104
  :param n: 输出条目数,默认为全部
93
105
  :param file: 仅摘取file文件(文件夹)的历史记录
94
106
  :return: 一个n*3的二维list,第0列是修改的文件数,第1列是插入的代码行数,第2列是删除的代码行数
@@ -98,7 +110,7 @@ class Git:
98
110
  cmd.append(f'-{n}')
99
111
  if file:
100
112
  cmd.append(file)
101
- s = self.g.log(*cmd)
113
+ s = self.log(*cmd)
102
114
 
103
115
  file_changed = []
104
116
  insertion = []
@@ -116,13 +128,14 @@ class Git:
116
128
 
117
129
  def commits_author(self, n=None, file=None):
118
130
  """每条commit的作者
119
- 参数含义参考commits_name里的解释"""
131
+ 参数含义参考commits_name里的解释
132
+ """
120
133
  cmd = ['--pretty=%an']
121
134
  if n:
122
135
  cmd.append(f'-{n}')
123
136
  if file:
124
137
  cmd.append(file)
125
- return self.g.log(*cmd).splitlines()
138
+ return self.log(*cmd).splitlines()
126
139
 
127
140
  def list_commits(self, n=None, file=None, exceltime=False) -> pd.DataFrame:
128
141
  """
@@ -147,7 +160,7 @@ class Git:
147
160
  ls.extend(self.commits_stat(n, file))
148
161
  ls.append(self.commits_author(n, file))
149
162
  ls = swap_rowcol(ls)
150
- t = file or self.g.working_dir
163
+ t = file or self.working_dir
151
164
  col_tag = (t + ' / commit名称', '时间', 'sha', 'files_changed', 'insertions', 'deletions', 'author')
152
165
  df = pd.DataFrame.from_records(ls, columns=col_tag)
153
166
  return df
@@ -220,9 +233,9 @@ class Git:
220
233
  sha = self.smartsha(sha, file)
221
234
 
222
235
  if sha:
223
- s = self.g.show(f'{sha}:{file}')
236
+ s = self.show(f'{sha}:{file}')
224
237
  else:
225
- s = ensure_content(os.path.join(self.g.working_dir, file))
238
+ s = File(os.path.join(self.working_dir, file)).read()
226
239
  return s
227
240
 
228
241
  def bcompare(self, file, sha1=0, sha2=None):
@@ -248,7 +261,7 @@ class Git:
248
261
  s2 = self.show(file, sha2_id)
249
262
  else:
250
263
  sha2_id = None
251
- s2 = os.path.join(self.g.working_dir, file) # 存储文件名而不是内容
264
+ s2 = os.path.join(self.working_dir, file) # 存储文件名而不是内容
252
265
 
253
266
  # 3 对比
254
267
  dprint(sha1, sha2, sha1_id, sha2_id)
@@ -262,7 +275,7 @@ class Git:
262
275
  :param files: 要搜索的文件清单
263
276
 
264
277
  191108周五10:40,目前跑 c:/pycode 要2分钟
265
- >> chrome(Git('C:/pycode/').find_pattern(re.compile(r'ssb等改明文')))
278
+ >> browser(Git('C:/pycode/').find_pattern(re.compile(r'ssb等改明文')))
266
279
 
267
280
  """
268
281
  # 1 主对象
@@ -272,7 +285,7 @@ class Git:
272
285
  # 2 files没有设置则匹配所有文件
273
286
  # TODO 当前已经不存在的文件这样是找不到的,有办法把历史文件也挖出来?
274
287
  if not files:
275
- with Dir(self.g.working_dir):
288
+ with Dir(self.working_dir):
276
289
  files = filesmatch('**/*.py')
277
290
 
278
291
  # 3 遍历文件
@@ -0,0 +1,165 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # @Author : 陈坤泽
4
+ # @Email : 877362867@qq.com
5
+ # @Date : 2024/04/27
6
+
7
+ """
8
+ libreoffice这个软件相关的功能
9
+
10
+ 官网:https://www.libreoffice.org/download/download-libreoffice/
11
+
12
+ linux的安装:
13
+ sudo apt-get update
14
+ sudo apt-get install libreoffice -y
15
+ """
16
+
17
+ import os
18
+ from pathlib import Path
19
+ import subprocess
20
+ import sys
21
+ import tempfile
22
+ from datetime import datetime
23
+
24
+
25
+ def check_libreoffice():
26
+ """ 检查LibreOffice是否安装 """
27
+ executor = get_libreoffice_executor()
28
+ try:
29
+ subprocess.run([executor, '--version'], check=True)
30
+ except FileNotFoundError:
31
+ return False
32
+ except subprocess.CalledProcessError:
33
+ return False
34
+ return True
35
+
36
+
37
+ def get_libreoffice_executor():
38
+ """ 获得可执行文件的名称 """
39
+ # 根据所在系统区分
40
+ if sys.platform == 'win32':
41
+ return 'soffice.exe'
42
+ else:
43
+ return 'libreoffice'
44
+
45
+
46
+ def infer_file_format(file_path):
47
+ """ 推断文件所属办公文档的'主类' """
48
+ ext = Path(file_path).suffix.lower()
49
+ if ext in ['.doc', '.docx']:
50
+ fmt = 'docx'
51
+ elif ext in ['.ppt', '.pptx']:
52
+ fmt = 'pptx'
53
+ elif ext in ['.xls', '.xlsx']:
54
+ # todo 其实excel还有xlsm的可能,但是用libreoffice可能没有微软365那样可以判断出宏的情况保存为xlsm
55
+ fmt = 'xlsx'
56
+ else:
57
+ raise ValueError("不支持的文件格式")
58
+ return fmt
59
+
60
+
61
+ class UpgradeOfficeFile:
62
+ @classmethod
63
+ def to_dir(cls, file_path, out_dir=None, fmt=None, timeout=10):
64
+ """ 将doc文件转换为docx文件
65
+
66
+ :param file_path: 待升级的文件路径
67
+ :param out_dir: 输出文件目录
68
+ 官方接口默认只能设置导出目录,不能设置导出文件名,文件名是跟原始文件一样的
69
+ :param fmt: 输出文件格式
70
+ docx, xlsx, pptx
71
+ """
72
+ if isinstance(file_path, Path):
73
+ file_path = file_path.as_posix()
74
+
75
+ # 获取LibreOffice可执行文件的名称
76
+ executor = get_libreoffice_executor()
77
+
78
+ # 如果未指定输出路径,则默认在输入文件的同目录下生成同名的DOCX文件
79
+ if out_dir is None:
80
+ out_dir = os.path.dirname(file_path)
81
+
82
+ if fmt is None:
83
+ fmt = infer_file_format(file_path)
84
+
85
+ # 构建转换命令
86
+ command = [
87
+ executor,
88
+ '--headless', # 无界面模式
89
+ '--convert-to', fmt, # 转换为docx格式
90
+ '--outdir', str(out_dir), # 输出目录
91
+ file_path # 输入文件路径
92
+ ]
93
+
94
+ subprocess.run(command, timeout=timeout, check=True)
95
+
96
+ # 返回转换后的文件路径
97
+ base_name = os.path.basename(file_path)
98
+ name, _ = os.path.splitext(base_name)
99
+ new_file_path = os.path.join(out_dir, f"{name}.{fmt}")
100
+
101
+ # todo 以目标文件是否存在判断转换是否成功也是有一定bug的,可能目标文件本来就存在
102
+ # 但如果严谨判断,就要分析subprocess.run的输出结果了,那个太麻烦,先用简便方法处理
103
+ if not Path(new_file_path).exists():
104
+ raise ValueError(f"升级文档失败")
105
+
106
+ return new_file_path
107
+
108
+ @classmethod
109
+ def to_file(cls, in_file, out_file=None, fmt=None, timeout=10):
110
+ """ 可以指定转换出的文件名的版本
111
+
112
+ :param in_file: 待转换的文件路径
113
+ :param out_file: 输出文件路径
114
+ 若未指定,默认与原文件同名,在原文件所在目录生成
115
+ :param fmt: 输出文件格式
116
+ docx, xlsx, pptx
117
+ 若未指定,则根据in_file的后缀名自动判断
118
+ """
119
+ # 将in_file转换为Path对象
120
+ in_file = Path(in_file)
121
+
122
+ # 如果fmt为None,则根据in_file推断
123
+ if fmt is None:
124
+ fmt = infer_file_format(in_file)
125
+
126
+ # 如果out_file为None,则默认在原文件目录生成同名的新格式文件
127
+ if out_file is None:
128
+ out_file = in_file.with_suffix(f'.{fmt}')
129
+ else:
130
+ out_file = Path(out_file)
131
+
132
+ # 确保out_file的父目录存在,不存在则创建
133
+ out_file.parent.mkdir(parents=True, exist_ok=True)
134
+
135
+ # 调用upgrade_office_file函数进行转换
136
+ temp_file = cls.to_dir(in_file, out_dir=out_file.parent, fmt=fmt, timeout=timeout)
137
+
138
+ # 将生成的临时文件重命名为out_file
139
+ os.rename(temp_file, out_file)
140
+
141
+ return out_file
142
+
143
+ @classmethod
144
+ def to_tempfile(cls, in_file, fmt=None, *, timestamp_stem=False, create_subdir=False, timeout=10):
145
+ """ 将文件转换为临时文件
146
+
147
+ :param timestamp_stem: 时间戳文件名
148
+ :param create_subdir: 是否在临时目录中创建新的子目录
149
+ """
150
+ if fmt is None:
151
+ fmt = infer_file_format(in_file)
152
+
153
+ root = Path(tempfile.gettempdir())
154
+ if create_subdir:
155
+ root2 = root / datetime.now().strftime('%Y%m%d.%H%M%S.%f')
156
+ root2.mkdir(parents=True, exist_ok=True)
157
+ root = root2
158
+
159
+ if timestamp_stem:
160
+ stem = datetime.now().strftime('%Y%m%d.%H%M%S.%f')
161
+ out_file = cls.to_file(in_file, out_file=root / f"{stem}.{fmt}", fmt=fmt, timeout=timeout)
162
+ else:
163
+ out_file = cls.to_dir(in_file, out_dir=root, fmt=fmt, timeout=timeout)
164
+
165
+ return out_file
@@ -0,0 +1,148 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # @Author : 陈坤泽
4
+ # @Email : 877362867@qq.com
5
+ # @Date : 2022/02/25 17:54
6
+
7
+ from pyxllib.prog.pupil import check_install_package
8
+
9
+ check_install_package('moviepy')
10
+
11
+ import cv2
12
+ from moviepy.editor import VideoFileClip
13
+ from moviepy.editor import cvsecs
14
+ import numpy as np
15
+ from tqdm import tqdm
16
+
17
+ from pyxllib.prog.pupil import inject_members
18
+ from pyxllib.file.specialist import XlPath
19
+ from pyxllib.cv.imhash import get_init_hash, phash
20
+ from pyxllib.cv.xlcvlib import xlcv
21
+
22
+
23
+ class XlVideoFileClip(VideoFileClip):
24
+
25
+ def get_frame2(self, time_point, *, scale=None):
26
+ """ 官方获得的图片通道是RGB,但是cv2处理的统一规则是BGR,要转换过来
27
+
28
+ :param scale: 获取图片后是否要按统一的比例再缩放一下
29
+ """
30
+ frame = self.get_frame(time_point)
31
+ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
32
+
33
+ if scale:
34
+ frame = cv2.resize(frame, (0, 0), fx=scale, fy=scale)
35
+
36
+ return frame
37
+
38
+ def get_frames(self, time_points=None, *, interval_second=0.1, cur_hash=None, head_frame=None, scale=None,
39
+ filter_mode=2, print_mode=True):
40
+ """ 同时获得多帧图片
41
+
42
+ :param time_points: 类list对象,元素是时间点(可以是字符串格式,也可以是数值秒数)
43
+ 常见生成方法参考:np.array(0, clip.duration, 0.1)
44
+ :param filter_mode: 过滤强度
45
+ 因为times如果取的非常密集,比如每0.1秒取一帧,会有很大概率是重复、相近的图
46
+ 此时可以用这个参数控制误差在多大以内的图会保留
47
+ 使用phash判断帧之间相似度,只要误差在该设定阈值内,都会被跳过
48
+ 可以设置0,不过这样过滤程度是最低的
49
+ 也可以输入-1,表示完全不过滤,不计算phash。当这种情况也不太必要用这个函数了,可以直接普通循环。
50
+ 也可以故意设置的特别大(phash最大差距是64),那这样相当于差异很大的也过滤掉了
51
+ :param head_frame: 提供一张初始图片,主要是配合filter_mode用于去重的
52
+ :param cur_hash: 类似head_frame作用,但直接提供hash值
53
+ :return: 使用yield机制,防止图片数据太多,内存爆炸了
54
+ 当filter_mode>=0时,返回 时间点time_point和对应的图片im
55
+ """
56
+ if cur_hash is None:
57
+ if head_frame is None:
58
+ cur_hash = get_init_hash()
59
+ else:
60
+ cur_hash = phash(head_frame)
61
+
62
+ if time_points is None:
63
+ time_points = np.arange(0, self.duration, interval_second)
64
+
65
+ for time_point in tqdm(time_points, disable=not print_mode):
66
+ im = self.get_frame2(time_point, scale=scale)
67
+
68
+ if filter_mode >= 0:
69
+ last_hash, cur_hash = cur_hash, phash(im)
70
+ if cur_hash - last_hash <= filter_mode:
71
+ continue
72
+ yield time_point, im
73
+ else:
74
+ yield im
75
+
76
+ def save_frames(self, out_dir, time_points=None, interval_second=0.1, **kwargs):
77
+ """ 跟get_frames差不多,多了一步自动存储图片文件到目录里
78
+
79
+ 这个功能是比较定制化的,不是那么泛用,但会有很多相关类似的操作需求,可以参考这里的代码实现
80
+ """
81
+ # 1 time_points
82
+ if time_points is None:
83
+ time_points = np.arange(0, self.duration, interval_second)
84
+ out_dir = XlPath(out_dir)
85
+
86
+ # 2 按时间点取图片,保存文件
87
+ for time_point, frame in self.get_frames(time_points, **kwargs):
88
+ tt = int(time_point * 10)
89
+ m, s, ms = tt // 600, (tt // 10) % 60, tt % 10
90
+ xlcv.write(frame, out_dir / f'{m:03}_{s:02}.{ms}.jpg')
91
+
92
+ def join_subtitles_image(self, time_points, ltrb_pos=None, *,
93
+ crop_first_frame=False,
94
+ filter_mode=2):
95
+ """ 生成字幕拼图
96
+
97
+ :param time_points: 在哪些时间点截图
98
+ :param ltrb_pos: 字幕所在位置,没有输入则默认全部全图拼接,
99
+ 一般指定上下就行了,即 [None, 640, None, 700]
100
+ :param crop_first_frame:
101
+ False,保留第一帧的完整性
102
+ True,第一帧也只裁剪字幕部分
103
+ :param filter_mode: 对于给出的时间点图片,去除相邻相同的图片
104
+ :return:
105
+
106
+ 参考用法:
107
+ from pyxllib.file.movielib import VideoFileClip
108
+ clip = VideoFileClip(str(Paths.videos / '觉观01.mp4')) # 必须要转str类型
109
+ im = clip.join_subtitles_image(np.arange(30, 40, 0.1), [None, 640, None, 695])
110
+ xlcv.write(im, Paths.videos / 'test.jpg')
111
+ """
112
+ # 1 如果有左右裁剪要提前处理
113
+ x1, y1, x2, y2 = ltrb_pos
114
+ if x1 or x2:
115
+ clip = self.crop(x1=x1, x2=x2)
116
+ else:
117
+ clip = self
118
+
119
+ # 2 第1帧是否要保留全图
120
+ frame_list = []
121
+ if crop_first_frame:
122
+ head_frame = None
123
+ else:
124
+ time_points = tuple(time_points)
125
+ head_frame = clip.get_frame2(time_points[0])
126
+ frame_list.append(head_frame[:y2])
127
+ head_frame = head_frame[y1:y2]
128
+ time_points = time_points[1:]
129
+
130
+ # 3 裁剪字幕区域
131
+ clip = clip.crop(y1=y1, y2=y2)
132
+ for time_point, frame in clip.get_frames(time_points, filter_mode=filter_mode, head_frame=head_frame):
133
+ frame_list.append(frame)
134
+
135
+ # 4 拼接完整图
136
+ im = xlcv.concat(frame_list, pad=0)
137
+ return im
138
+
139
+
140
+ inject_members(XlVideoFileClip, VideoFileClip)
141
+
142
+
143
+ def clip_video(input_file, output_file, start_time, end_time):
144
+ start_time = cvsecs(start_time)
145
+ end_time = cvsecs(end_time)
146
+ clip = VideoFileClip(input_file).subclip(start_time, end_time)
147
+ clip.write_videofile(output_file)
148
+ clip.reader.close()
pyxllib/file/newbie.py ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # @Author : 陈坤泽
4
+ # @Email : 877362867@qq.com
5
+ # @Date : 2021/06/06 10:51
6
+
7
+ def linux_path_fmt(p):
8
+ p = str(p)
9
+ p = p.replace('\\', '/')
10
+ return p