bcmd 0.6.4__py3-none-any.whl → 0.6.6__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.
Potentially problematic release.
This version of bcmd might be problematic. Click here for more details.
- {bcmd-0.6.4.dist-info → bcmd-0.6.6.dist-info}/METADATA +1 -1
- bcmd-0.6.6.dist-info/RECORD +6 -0
- bcmd-0.6.6.dist-info/entry_points.txt +2 -0
- bcmd-0.6.6.dist-info/top_level.txt +1 -0
- bcmd-0.6.4.dist-info/RECORD +0 -27
- bcmd-0.6.4.dist-info/entry_points.txt +0 -2
- bcmd-0.6.4.dist-info/top_level.txt +0 -1
- bcmdx/__init__.py +0 -0
- bcmdx/common/__init__.py +0 -0
- bcmdx/common/func.py +0 -19
- bcmdx/common/password.py +0 -35
- bcmdx/resources/project/main.py +0 -1
- bcmdx/tasks/__init__.py +0 -16
- bcmdx/tasks/bin.py +0 -104
- bcmdx/tasks/code.py +0 -132
- bcmdx/tasks/crypto.py +0 -105
- bcmdx/tasks/debian.py +0 -78
- bcmdx/tasks/download.py +0 -74
- bcmdx/tasks/image.py +0 -304
- bcmdx/tasks/json.py +0 -25
- bcmdx/tasks/lib.py +0 -58
- bcmdx/tasks/math.py +0 -97
- bcmdx/tasks/mirror.py +0 -46
- bcmdx/tasks/pdf.py +0 -43
- bcmdx/tasks/proxy.py +0 -55
- bcmdx/tasks/time.py +0 -81
- bcmdx/tasks/upgrade.py +0 -22
- bcmdx/tasks/wasabi.py +0 -94
- /bcmdx/main.py → /bcmd/__init__.py +0 -0
- {bcmd-0.6.4.dist-info → bcmd-0.6.6.dist-info}/WHEEL +0 -0
bcmdx/tasks/image.py
DELETED
|
@@ -1,304 +0,0 @@
|
|
|
1
|
-
import asyncio
|
|
2
|
-
import os
|
|
3
|
-
import random
|
|
4
|
-
from enum import StrEnum
|
|
5
|
-
from pathlib import Path
|
|
6
|
-
from typing import Final, List, Tuple
|
|
7
|
-
|
|
8
|
-
import httpx
|
|
9
|
-
import typer
|
|
10
|
-
from beni import bcolor, bfile, bhttp, binput, block, bpath, btask
|
|
11
|
-
from beni.bbyte import BytesReader, BytesWriter
|
|
12
|
-
from beni.bfunc import syncCall
|
|
13
|
-
from beni.btype import Null, XPath
|
|
14
|
-
from PIL import Image, ImageDraw, ImageFont
|
|
15
|
-
|
|
16
|
-
app: Final = btask.newSubApp('图片工具集')
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
class _OutputType(StrEnum):
|
|
20
|
-
'输出类型'
|
|
21
|
-
normal = '0'
|
|
22
|
-
replace_ = '1'
|
|
23
|
-
crc_replace = '2'
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
@app.command()
|
|
27
|
-
@syncCall
|
|
28
|
-
async def convert(
|
|
29
|
-
path: Path = typer.Option(None, '--path', '-p', help='指定目录或具体图片文件,默认当前目录'),
|
|
30
|
-
src_format: str = typer.Option('jpg|jpeg|png', '--src-format', '-s', help='如果path是目录,指定源格式,可以指定多个,默认值:jpg|jpeg|png'),
|
|
31
|
-
dst_format: str = typer.Option('webp', '--dst-format', '-d', help='目标格式,只能是单个'),
|
|
32
|
-
rgb: bool = typer.Option(False, '--rgb', help='转换为RGB格式'),
|
|
33
|
-
quality: int = typer.Option(85, '--quality', '-q', help='图片质量,0-100,默认85'),
|
|
34
|
-
output_type: _OutputType = typer.Option(_OutputType.normal, '--output-type', help='输出类型,0:普通输出,1:删除源文件,2:输出文件使用CRC32命名并删除源文件'),
|
|
35
|
-
):
|
|
36
|
-
'图片格式转换'
|
|
37
|
-
path = path or Path(os.getcwd())
|
|
38
|
-
fileList: list[Path] = []
|
|
39
|
-
if path.is_file():
|
|
40
|
-
fileList.append(path)
|
|
41
|
-
elif path.is_dir():
|
|
42
|
-
extNameList = [x for x in src_format.strip().split('|')]
|
|
43
|
-
fileList = [x for x in bpath.listFile(path, True) if x.suffix[1:].lower() in extNameList]
|
|
44
|
-
if not fileList:
|
|
45
|
-
return bcolor.printRed(f'未找到图片文件({path})')
|
|
46
|
-
for file in fileList:
|
|
47
|
-
with Image.open(file) as img:
|
|
48
|
-
if rgb:
|
|
49
|
-
img = img.convert('RGB')
|
|
50
|
-
with bpath.useTempFile() as tempFile:
|
|
51
|
-
img.save(tempFile, format=dst_format, quality=quality)
|
|
52
|
-
outputFile = file.with_suffix(f'.{dst_format}')
|
|
53
|
-
if output_type == _OutputType.crc_replace:
|
|
54
|
-
outputFile = outputFile.with_stem(await bfile.crc(tempFile))
|
|
55
|
-
bpath.copy(tempFile, outputFile)
|
|
56
|
-
if output_type in [_OutputType.replace_, _OutputType.crc_replace]:
|
|
57
|
-
if outputFile != file:
|
|
58
|
-
bpath.remove(file)
|
|
59
|
-
bcolor.printGreen(f'{file} -> {outputFile}')
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
# ------------------------------------------------------------------------------------
|
|
63
|
-
|
|
64
|
-
@app.command()
|
|
65
|
-
@syncCall
|
|
66
|
-
async def tiny(
|
|
67
|
-
path: Path = typer.Option(None, '--path', help='指定目录或具体图片文件,默认当前目录'),
|
|
68
|
-
optimization: int = typer.Option(25, '--optimization', help='指定优化大小,如果没有达到优化效果就不处理,单位:%,默认25'),
|
|
69
|
-
isKeepOriginal: bool = typer.Option(False, '--keep-original', help='保留原始图片'),
|
|
70
|
-
):
|
|
71
|
-
|
|
72
|
-
keyList = [
|
|
73
|
-
'MB3QmtvZ8HKRkXcDnxhWCNTXzvx6cNF3',
|
|
74
|
-
'7L7X2CJ35GM1bChSHdT14yZPLx7FlpNk',
|
|
75
|
-
'q8YLcvrXVW2NYcr5mMyzQhsSHF4j7gny',
|
|
76
|
-
]
|
|
77
|
-
random.shuffle(keyList)
|
|
78
|
-
|
|
79
|
-
class _TinyFile:
|
|
80
|
-
|
|
81
|
-
_endian: Final = '>'
|
|
82
|
-
_sep = BytesWriter(_endian).writeStr('tiny').writeUint(9527).writeUint(709394).toBytes()
|
|
83
|
-
|
|
84
|
-
@property
|
|
85
|
-
def compression(self):
|
|
86
|
-
return self._compression
|
|
87
|
-
|
|
88
|
-
@property
|
|
89
|
-
def isTiny(self):
|
|
90
|
-
return self._isTiny
|
|
91
|
-
|
|
92
|
-
@property
|
|
93
|
-
def file(self):
|
|
94
|
-
return self._file
|
|
95
|
-
|
|
96
|
-
def __init__(self, file: XPath):
|
|
97
|
-
self._file = file
|
|
98
|
-
self._compression: float = 0.0
|
|
99
|
-
self._isTiny: bool = False
|
|
100
|
-
|
|
101
|
-
def getSizeDisplay(self):
|
|
102
|
-
size = bpath.get(self._file).stat().st_size / 1024
|
|
103
|
-
return f'{size:,.2f}KB'
|
|
104
|
-
|
|
105
|
-
async def updateInfo(self):
|
|
106
|
-
fileBytes = await bfile.readBytes(self._file)
|
|
107
|
-
self._compression = 0.0
|
|
108
|
-
self._isTiny = False
|
|
109
|
-
blockAry = fileBytes.split(self._sep)
|
|
110
|
-
if len(blockAry) > 1:
|
|
111
|
-
info = BytesReader(self._endian, blockAry[1])
|
|
112
|
-
size = info.readUint()
|
|
113
|
-
if size == len(blockAry[0]):
|
|
114
|
-
self._compression = round(info.readFloat(), 2)
|
|
115
|
-
self._isTiny = info.readBool()
|
|
116
|
-
|
|
117
|
-
async def _flushInfo(self, compression: float, isTiny: bool):
|
|
118
|
-
self._compression = compression
|
|
119
|
-
self._isTiny = isTiny
|
|
120
|
-
content = await self._getPureContent()
|
|
121
|
-
info = (
|
|
122
|
-
BytesWriter(self._endian)
|
|
123
|
-
.writeUint(len(content))
|
|
124
|
-
.writeFloat(compression)
|
|
125
|
-
.writeBool(isTiny)
|
|
126
|
-
.toBytes()
|
|
127
|
-
)
|
|
128
|
-
content += self._sep + info
|
|
129
|
-
await bfile.writeBytes(self._file, content)
|
|
130
|
-
|
|
131
|
-
async def _getPureContent(self):
|
|
132
|
-
content = await bfile.readBytes(self._file)
|
|
133
|
-
content = content.split(self._sep)[0]
|
|
134
|
-
return content
|
|
135
|
-
|
|
136
|
-
@block.limit(1)
|
|
137
|
-
async def runTiny(self, key: str, compression: float, isKeepOriginal: bool):
|
|
138
|
-
content = await self._getPureContent()
|
|
139
|
-
async with httpx.AsyncClient() as client:
|
|
140
|
-
response = await client.post(
|
|
141
|
-
'https://api.tinify.com/shrink',
|
|
142
|
-
auth=('api', key),
|
|
143
|
-
content=content,
|
|
144
|
-
timeout=30,
|
|
145
|
-
)
|
|
146
|
-
response.raise_for_status()
|
|
147
|
-
result = response.json()
|
|
148
|
-
outputCompression = round(result['output']['ratio'] * 100, 2)
|
|
149
|
-
if outputCompression < compression:
|
|
150
|
-
# 下载文件
|
|
151
|
-
url = result['output']['url']
|
|
152
|
-
with bpath.useTempFile() as tempFile:
|
|
153
|
-
await bhttp.download(url, tempFile)
|
|
154
|
-
await _TinyFile(tempFile)._flushInfo(outputCompression, True)
|
|
155
|
-
outputFile = bpath.get(self._file)
|
|
156
|
-
if isKeepOriginal:
|
|
157
|
-
outputFile = outputFile.with_stem(f'{outputFile.stem}_tiny')
|
|
158
|
-
bpath.move(tempFile, outputFile, True)
|
|
159
|
-
bcolor.printGreen(f'{outputFile}({outputCompression - 100:.2f}% / 压缩 / {self.getSizeDisplay()})')
|
|
160
|
-
else:
|
|
161
|
-
# 不进行压缩
|
|
162
|
-
await self._flushInfo(outputCompression, False)
|
|
163
|
-
bcolor.printMagenta(f'{self._file} ({outputCompression - 100:.2f}% / 不处理 / {self.getSizeDisplay()})')
|
|
164
|
-
|
|
165
|
-
btask.assertTrue(0 < optimization < 100, '优化大小必须在0-100之间')
|
|
166
|
-
compression = 100 - optimization
|
|
167
|
-
await block.setLimit(_TinyFile.runTiny, len(keyList))
|
|
168
|
-
|
|
169
|
-
# 整理文件列表
|
|
170
|
-
fileList = []
|
|
171
|
-
path = path or Path(os.getcwd())
|
|
172
|
-
if path.is_file():
|
|
173
|
-
fileList.append(path)
|
|
174
|
-
elif path.is_dir():
|
|
175
|
-
fileList = [x for x in bpath.listFile(path, True) if x.suffix[1:].lower() in ['jpg', 'jpeg', 'png']]
|
|
176
|
-
else:
|
|
177
|
-
btask.abort('未找到图片文件', path)
|
|
178
|
-
fileList.sort()
|
|
179
|
-
|
|
180
|
-
# 将文件列表整理成 _TinyFile 对象
|
|
181
|
-
fileList = [_TinyFile(x) for x in fileList]
|
|
182
|
-
await asyncio.gather(*[x.updateInfo() for x in fileList])
|
|
183
|
-
|
|
184
|
-
# 过滤掉已经处理过的图片
|
|
185
|
-
for i in range(len(fileList)):
|
|
186
|
-
file = fileList[i]
|
|
187
|
-
if file.compression == 0:
|
|
188
|
-
# 未处理过的图片,进行图片的压缩处理
|
|
189
|
-
pass
|
|
190
|
-
elif not file.isTiny and file.compression < compression:
|
|
191
|
-
# 之前测试的压缩率不符合要求,不过现在符合了,进行图片的压缩处理
|
|
192
|
-
pass
|
|
193
|
-
else:
|
|
194
|
-
# 要忽略掉的文件
|
|
195
|
-
if file.isTiny:
|
|
196
|
-
bcolor.printYellow(f'{file.file}({file.compression - 100:.2f}% / 已压缩 / {file.getSizeDisplay()})')
|
|
197
|
-
else:
|
|
198
|
-
bcolor.printMagenta(f'{file.file}({file.compression - 100:.2f}% / 不处理 / {file.getSizeDisplay()})')
|
|
199
|
-
|
|
200
|
-
fileList[i] = Null
|
|
201
|
-
fileList = [x for x in fileList if x]
|
|
202
|
-
|
|
203
|
-
# 开始压缩
|
|
204
|
-
taskList = [
|
|
205
|
-
x.runTiny(keyList[i % len(keyList)], compression, isKeepOriginal)
|
|
206
|
-
for i, x in enumerate(fileList)
|
|
207
|
-
]
|
|
208
|
-
await asyncio.gather(*taskList)
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
@app.command()
|
|
212
|
-
@syncCall
|
|
213
|
-
async def merge(
|
|
214
|
-
path: Path = typer.Argument(Path.cwd(), help='workspace 路径'),
|
|
215
|
-
force: bool = typer.Option(False, '--force', '-f', help='强制覆盖'),
|
|
216
|
-
):
|
|
217
|
-
'合并多张图片'
|
|
218
|
-
|
|
219
|
-
def _get_watermark_font(font_size: int) -> ImageFont.FreeTypeFont:
|
|
220
|
-
font_candidates = [
|
|
221
|
-
'arial.ttf', # Windows
|
|
222
|
-
'Arial.ttf', # macOS(部分系统可能区分大小写)
|
|
223
|
-
'Helvetica.ttc', # macOS
|
|
224
|
-
'DejaVuSans.ttf', # Linux
|
|
225
|
-
'FreeSans.ttf', # 某些Linux发行版
|
|
226
|
-
'LiberationSans-Regular.ttf' # RHEL系发行版
|
|
227
|
-
]
|
|
228
|
-
for font_name in font_candidates:
|
|
229
|
-
try:
|
|
230
|
-
return ImageFont.truetype(font_name, font_size)
|
|
231
|
-
except (IOError, OSError):
|
|
232
|
-
continue
|
|
233
|
-
raise Exception('No font found!')
|
|
234
|
-
|
|
235
|
-
def _add_watermark(image: Image.Image, text: str, position: Tuple[float, float]) -> Image.Image:
|
|
236
|
-
"""添加圆形背景水印"""
|
|
237
|
-
draw = ImageDraw.Draw(image)
|
|
238
|
-
font_size = 100
|
|
239
|
-
font = _get_watermark_font(font_size)
|
|
240
|
-
|
|
241
|
-
# 计算文本尺寸并确定圆形参数
|
|
242
|
-
text_bbox = draw.textbbox(position, text, font=font)
|
|
243
|
-
text_width = text_bbox[2] - text_bbox[0]
|
|
244
|
-
text_height = text_bbox[3] - text_bbox[1]
|
|
245
|
-
|
|
246
|
-
# 计算圆形参数(直径取文本宽高的最大值 + 边距)
|
|
247
|
-
diameter = max(text_width, text_height) + 20 # 10像素边距
|
|
248
|
-
radius = diameter // 2
|
|
249
|
-
|
|
250
|
-
# 计算圆形中心坐标(保持与原矩形左上角一致)
|
|
251
|
-
circle_center = (
|
|
252
|
-
position[0] + text_width // 2 + 5, # 原位置向右偏移边距
|
|
253
|
-
position[1] + text_height // 2 + 5 # 原位置向下偏移边距
|
|
254
|
-
)
|
|
255
|
-
|
|
256
|
-
# 绘制圆形背景
|
|
257
|
-
ellipse_box = (
|
|
258
|
-
circle_center[0] - radius,
|
|
259
|
-
circle_center[1] - radius,
|
|
260
|
-
circle_center[0] + radius,
|
|
261
|
-
circle_center[1] + radius
|
|
262
|
-
)
|
|
263
|
-
draw.ellipse(ellipse_box, fill='#B920D9')
|
|
264
|
-
|
|
265
|
-
# 绘制居中文字
|
|
266
|
-
draw.text(
|
|
267
|
-
circle_center,
|
|
268
|
-
text,
|
|
269
|
-
(255, 255, 255),
|
|
270
|
-
font=font,
|
|
271
|
-
anchor="mm" # 设置锚点为水平垂直居中
|
|
272
|
-
)
|
|
273
|
-
return image
|
|
274
|
-
|
|
275
|
-
def _merge_images(image_paths: List[Path], output_path: Path) -> None:
|
|
276
|
-
images = [Image.open(img_path) for img_path in image_paths]
|
|
277
|
-
max_width = max(img.width for img in images)
|
|
278
|
-
total_height = sum(img.height for img in images)
|
|
279
|
-
merged_image = Image.new('RGB', (max_width, total_height))
|
|
280
|
-
y_offset = 0
|
|
281
|
-
for idx, img in enumerate(images):
|
|
282
|
-
merged_image.paste(img, (0, y_offset))
|
|
283
|
-
_add_watermark(merged_image, f'{idx + 1}', (22, y_offset + 17))
|
|
284
|
-
y_offset += img.height
|
|
285
|
-
# 修改保存参数为 WebP 格式
|
|
286
|
-
merged_image.save(
|
|
287
|
-
output_path,
|
|
288
|
-
format='JPEG',
|
|
289
|
-
quality=80, # 质量参数(0-100),推荐 80-90 之间
|
|
290
|
-
method=6, # 压缩方法(0-6),6 为最佳压缩
|
|
291
|
-
lossless=False, # 不使用无损压缩(更小的文件体积)
|
|
292
|
-
)
|
|
293
|
-
|
|
294
|
-
image_files = [x for x in bpath.listFile(path) if x.suffix in ('.png', '.jpg', '.jpeg', '.webp', '.bmp')]
|
|
295
|
-
output_image = path / f'merge_{path.name}.jpg' # 修改文件扩展名为 webp
|
|
296
|
-
if output_image in image_files:
|
|
297
|
-
if not force:
|
|
298
|
-
print(output_image)
|
|
299
|
-
await binput.confirm(f'生成文件已经存在,是否覆盖?')
|
|
300
|
-
image_files.remove(output_image)
|
|
301
|
-
image_files.sort(key=lambda x: x.as_posix())
|
|
302
|
-
_merge_images(image_files, output_image)
|
|
303
|
-
bcolor.printMagenta(output_image)
|
|
304
|
-
bcolor.printGreen('OK')
|
bcmdx/tasks/json.py
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import json
|
|
2
|
-
from typing import Final
|
|
3
|
-
|
|
4
|
-
import pyperclip
|
|
5
|
-
from beni import bcolor, btask
|
|
6
|
-
from beni.bfunc import syncCall
|
|
7
|
-
from rich.console import Console
|
|
8
|
-
|
|
9
|
-
app: Final = btask.app
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
@app.command('json')
|
|
13
|
-
@syncCall
|
|
14
|
-
async def format_json():
|
|
15
|
-
'格式化 JSON (使用复制文本)'
|
|
16
|
-
content = pyperclip.paste()
|
|
17
|
-
try:
|
|
18
|
-
Console().print_json(content, indent=4, ensure_ascii=False, sort_keys=True)
|
|
19
|
-
data = json.loads(content)
|
|
20
|
-
pyperclip.copy(
|
|
21
|
-
json.dumps(data, indent=4, ensure_ascii=False, sort_keys=True)
|
|
22
|
-
)
|
|
23
|
-
except:
|
|
24
|
-
bcolor.printRed('无效的 JSON')
|
|
25
|
-
bcolor.printRed(content)
|
bcmdx/tasks/lib.py
DELETED
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
import os
|
|
2
|
-
from pathlib import Path
|
|
3
|
-
from typing import Final
|
|
4
|
-
|
|
5
|
-
import typer
|
|
6
|
-
from beni import bcolor, bfile, bpath, brun, btask
|
|
7
|
-
from beni.bfunc import syncCall
|
|
8
|
-
|
|
9
|
-
from ..common import password
|
|
10
|
-
|
|
11
|
-
app: Final = btask.newSubApp('lib 工具')
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
@app.command()
|
|
15
|
-
@syncCall
|
|
16
|
-
async def update_version(
|
|
17
|
-
path: Path = typer.Argument(Path.cwd(), help='workspace 路径'),
|
|
18
|
-
isNotCommit: bool = typer.Option(False, '--no-commit', '-d', help='是否提交git'),
|
|
19
|
-
):
|
|
20
|
-
'修改 pyproject.toml 版本号'
|
|
21
|
-
file = path / 'pyproject.toml'
|
|
22
|
-
btask.assertTrue(file.is_file(), '文件不存在', file)
|
|
23
|
-
data = await bfile.readToml(file)
|
|
24
|
-
version = data['project']['version']
|
|
25
|
-
versionList = [int(x) for x in version.split('.')]
|
|
26
|
-
versionList[-1] += 1
|
|
27
|
-
newVersion = '.'.join([str(x) for x in versionList])
|
|
28
|
-
content = await bfile.readText(file)
|
|
29
|
-
if f"version = '{version}'" in content:
|
|
30
|
-
content = content.replace(f"version = '{version}'", f"version = '{newVersion}'")
|
|
31
|
-
elif f'version = "{version}"' in content:
|
|
32
|
-
content = content.replace(f'version = "{version}"', f'version = "{newVersion}"')
|
|
33
|
-
else:
|
|
34
|
-
raise Exception('版本号修改失败,先检查文件中定义的版本号格式是否正常')
|
|
35
|
-
await bfile.writeText(file, content)
|
|
36
|
-
bcolor.printCyan(newVersion)
|
|
37
|
-
if not isNotCommit:
|
|
38
|
-
msg = f'更新版本号 {newVersion}'
|
|
39
|
-
os.system(
|
|
40
|
-
rf'TortoiseGitProc.exe /command:commit /path:{file} /logmsg:"{msg}"'
|
|
41
|
-
)
|
|
42
|
-
bcolor.printGreen('OK')
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
@app.command()
|
|
46
|
-
@syncCall
|
|
47
|
-
async def build(
|
|
48
|
-
path: Path = typer.Argument(Path.cwd(), help='workspace 路径'),
|
|
49
|
-
):
|
|
50
|
-
'发布项目'
|
|
51
|
-
user, pwd = await password.getPypi()
|
|
52
|
-
bpath.remove(path / 'dist')
|
|
53
|
-
bpath.remove(
|
|
54
|
-
*list(path.glob('*.egg-info'))
|
|
55
|
-
)
|
|
56
|
-
with bpath.changePath(path):
|
|
57
|
-
await brun.run(f'uv build')
|
|
58
|
-
await brun.run(f'uv publish -u {user} -p {pwd}')
|
bcmdx/tasks/math.py
DELETED
|
@@ -1,97 +0,0 @@
|
|
|
1
|
-
from typing import Final
|
|
2
|
-
|
|
3
|
-
import typer
|
|
4
|
-
from beni import bcolor, btask
|
|
5
|
-
from beni.bfunc import Counter, syncCall, toFloat
|
|
6
|
-
from prettytable import PrettyTable
|
|
7
|
-
|
|
8
|
-
app: Final = btask.newSubApp('math 工具集')
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
@app.command()
|
|
12
|
-
@syncCall
|
|
13
|
-
async def scale(
|
|
14
|
-
a: float = typer.Argument(..., help='原始数值'),
|
|
15
|
-
b: float = typer.Argument(..., help='原始数值'),
|
|
16
|
-
c: str = typer.Argument(..., help='数值 或 ?'),
|
|
17
|
-
d: str = typer.Argument(..., help='数值 或 ?'),
|
|
18
|
-
):
|
|
19
|
-
'按比例计算数值,例子:beni math scale 1 2 3 ?'
|
|
20
|
-
if not ((c == '?') != (d == '?')):
|
|
21
|
-
return bcolor.printRed('参数C和参数D必须有且仅有一个为?')
|
|
22
|
-
print()
|
|
23
|
-
table = PrettyTable(
|
|
24
|
-
title=bcolor.yellow('按比例计算数值'),
|
|
25
|
-
)
|
|
26
|
-
if c == '?':
|
|
27
|
-
dd = toFloat(d)
|
|
28
|
-
cc = a * dd / b
|
|
29
|
-
table.add_rows([
|
|
30
|
-
['A', a, bcolor.magenta(str(cc)), bcolor.magenta('C')],
|
|
31
|
-
['B', b, dd, 'D'],
|
|
32
|
-
])
|
|
33
|
-
elif d == '?':
|
|
34
|
-
cc = toFloat(c)
|
|
35
|
-
dd = b * cc / a
|
|
36
|
-
table.add_rows([
|
|
37
|
-
['A', a, cc, 'C'],
|
|
38
|
-
['B', b, bcolor.magenta(str(dd)), bcolor.magenta('D')],
|
|
39
|
-
])
|
|
40
|
-
print(table.get_string(header=False))
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
@app.command()
|
|
44
|
-
@syncCall
|
|
45
|
-
async def discount(
|
|
46
|
-
values: list[str] = typer.Argument(..., help='每组数据使用#作为分隔符,注意后面的数据不能为0,例:123#500'),
|
|
47
|
-
):
|
|
48
|
-
'计算折扣,例子:beni math discount 123#500 130#550'
|
|
49
|
-
btask.assertTrue(len(values) >= 2, '至少需要提供2组数据用作比较')
|
|
50
|
-
|
|
51
|
-
class Data:
|
|
52
|
-
def __init__(self, value: str):
|
|
53
|
-
try:
|
|
54
|
-
ary = [x.strip() for x in value.strip().split('#')]
|
|
55
|
-
self.a = float(ary[0])
|
|
56
|
-
self.b = float(ary[1])
|
|
57
|
-
self.v = self.a / self.b
|
|
58
|
-
self.discount = 0.0
|
|
59
|
-
except:
|
|
60
|
-
btask.abort(f'数据格式错误', value)
|
|
61
|
-
|
|
62
|
-
datas = [Data(x) for x in values]
|
|
63
|
-
table = PrettyTable(
|
|
64
|
-
title=bcolor.yellow('计算折扣'),
|
|
65
|
-
)
|
|
66
|
-
vAry = [x.v for x in datas]
|
|
67
|
-
minV = min(vAry)
|
|
68
|
-
maxV = max(vAry)
|
|
69
|
-
for data in datas:
|
|
70
|
-
data.discount = -(maxV - data.v) / maxV
|
|
71
|
-
table.add_column(
|
|
72
|
-
'',
|
|
73
|
-
[
|
|
74
|
-
'前数据',
|
|
75
|
-
'后数据',
|
|
76
|
-
'单价',
|
|
77
|
-
'折扣',
|
|
78
|
-
],
|
|
79
|
-
)
|
|
80
|
-
counter = Counter(-1)
|
|
81
|
-
for data in datas:
|
|
82
|
-
colorFunc = bcolor.white
|
|
83
|
-
if data.v == minV:
|
|
84
|
-
colorFunc = bcolor.green
|
|
85
|
-
elif data.v == maxV:
|
|
86
|
-
colorFunc = bcolor.red
|
|
87
|
-
columns = [
|
|
88
|
-
f'{data.a:,}',
|
|
89
|
-
f'{data.b:,}',
|
|
90
|
-
f'{data.v:,.3f}',
|
|
91
|
-
f'{data.discount * 100:+,.3f}%' if data.discount else '',
|
|
92
|
-
]
|
|
93
|
-
table.add_column(
|
|
94
|
-
chr(65 + counter()),
|
|
95
|
-
[colorFunc(x) for x in columns],
|
|
96
|
-
)
|
|
97
|
-
print(table.get_string())
|
bcmdx/tasks/mirror.py
DELETED
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
|
|
3
|
-
import platform
|
|
4
|
-
from typing import Final
|
|
5
|
-
|
|
6
|
-
import typer
|
|
7
|
-
from beni import bcolor, bfile, bpath, btask
|
|
8
|
-
from beni.bfunc import syncCall
|
|
9
|
-
|
|
10
|
-
app: Final = btask.app
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
@app.command()
|
|
14
|
-
@syncCall
|
|
15
|
-
async def mirror(
|
|
16
|
-
disabled: bool = typer.Option(False, '--disabled', '-d', help="是否禁用"),
|
|
17
|
-
):
|
|
18
|
-
'设置镜像'
|
|
19
|
-
|
|
20
|
-
# 根据不同的系统平台
|
|
21
|
-
match platform.system():
|
|
22
|
-
case 'Windows':
|
|
23
|
-
file = bpath.user('pip/pip.ini')
|
|
24
|
-
case 'Linux':
|
|
25
|
-
file = bpath.user('.pip/pip.conf')
|
|
26
|
-
case _:
|
|
27
|
-
btask.abort('暂时不支持该平台', platform.system())
|
|
28
|
-
return
|
|
29
|
-
|
|
30
|
-
if disabled:
|
|
31
|
-
bpath.remove(file)
|
|
32
|
-
bcolor.printRed('删除文件', file)
|
|
33
|
-
else:
|
|
34
|
-
content = _content.strip()
|
|
35
|
-
await bfile.writeText(file, content)
|
|
36
|
-
bcolor.printYellow(file)
|
|
37
|
-
bcolor.printMagenta(content)
|
|
38
|
-
bcolor.printGreen('OK')
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
# ------------------------------------------------------------------------------------
|
|
42
|
-
|
|
43
|
-
_content = '''
|
|
44
|
-
[global]
|
|
45
|
-
index-url = https://mirrors.aliyun.com/pypi/simple
|
|
46
|
-
'''
|
bcmdx/tasks/pdf.py
DELETED
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
from pathlib import Path
|
|
2
|
-
from typing import Final
|
|
3
|
-
|
|
4
|
-
import fitz
|
|
5
|
-
import typer
|
|
6
|
-
from beni import bcolor, bfile, btask
|
|
7
|
-
from beni.bfunc import syncCall
|
|
8
|
-
|
|
9
|
-
app: Final = btask.newSubApp('PDF相关')
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
@app.command()
|
|
13
|
-
@syncCall
|
|
14
|
-
async def output_images(
|
|
15
|
-
target: Path = typer.Option(Path.cwd(), '--target', help='PDF文件路径或多个PDF文件所在的目录'),
|
|
16
|
-
):
|
|
17
|
-
'保存 PDF 文件里面的图片'
|
|
18
|
-
|
|
19
|
-
# 列出需要检查的PDF文件
|
|
20
|
-
pdfFileList: list[Path] = []
|
|
21
|
-
if target.is_dir():
|
|
22
|
-
pdfFileList = list(target.glob('*.pdf'))
|
|
23
|
-
elif target.is_file():
|
|
24
|
-
pdfFileList = [target]
|
|
25
|
-
else:
|
|
26
|
-
raise ValueError("目标路径不存在")
|
|
27
|
-
|
|
28
|
-
for pdf_file in pdfFileList:
|
|
29
|
-
pdf_document = fitz.open(pdf_file)
|
|
30
|
-
output_dir = pdf_file.with_name(pdf_file.stem + '-PDF图片文件')
|
|
31
|
-
for page_num in range(len(pdf_document)):
|
|
32
|
-
page = pdf_document.load_page(page_num)
|
|
33
|
-
images = page.get_images(full=True)
|
|
34
|
-
for img_index, img in enumerate(images):
|
|
35
|
-
xref = img[0]
|
|
36
|
-
base_image = pdf_document.extract_image(xref)
|
|
37
|
-
image_bytes = base_image["image"]
|
|
38
|
-
image_ext = base_image["ext"]
|
|
39
|
-
image_filename = f"page{page_num + 1}_img{img_index + 1}.{image_ext}"
|
|
40
|
-
image_path = output_dir / image_filename
|
|
41
|
-
output_dir.mkdir(exist_ok=True)
|
|
42
|
-
bcolor.printGreen(image_path)
|
|
43
|
-
await bfile.writeBytes(image_path, image_bytes)
|
bcmdx/tasks/proxy.py
DELETED
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
from __future__ import annotations
|
|
2
|
-
|
|
3
|
-
from typing import Final
|
|
4
|
-
|
|
5
|
-
import psutil
|
|
6
|
-
import pyperclip
|
|
7
|
-
import typer
|
|
8
|
-
from beni import bcolor, btask
|
|
9
|
-
from beni.bfunc import syncCall, textToAry
|
|
10
|
-
|
|
11
|
-
app: Final = btask.app
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
@app.command()
|
|
15
|
-
@syncCall
|
|
16
|
-
async def proxy(
|
|
17
|
-
port: int = typer.Argument(15236, help="代理服务器端口"),
|
|
18
|
-
):
|
|
19
|
-
'生成终端设置代理服务器的命令'
|
|
20
|
-
processNameAry: list[str] = []
|
|
21
|
-
process = psutil.Process().parent()
|
|
22
|
-
while process:
|
|
23
|
-
processNameAry.append(process.name())
|
|
24
|
-
process = process.parent()
|
|
25
|
-
template = ''
|
|
26
|
-
|
|
27
|
-
# 针对不同的终端使用不同的模板
|
|
28
|
-
if 'cmd.exe' in processNameAry:
|
|
29
|
-
template = cmdTemplate
|
|
30
|
-
elif set(['powershell.exe', 'pwsh.exe']) & set(processNameAry):
|
|
31
|
-
template = powerShellTemplate
|
|
32
|
-
|
|
33
|
-
btask.assertTrue(template, f'不支持当前终端({processNameAry})')
|
|
34
|
-
lineAry = textToAry(template.format(port))
|
|
35
|
-
msg = '\n'.join(lineAry)
|
|
36
|
-
bcolor.printMagenta('\r\n' + msg)
|
|
37
|
-
msg += '\n' # 多增加一个换行,直接粘贴的时候相当于最后一行也执行完
|
|
38
|
-
pyperclip.copy(msg)
|
|
39
|
-
bcolor.printYellow('已复制,可直接粘贴使用')
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
# ------------------------------------------------------------------------------------
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
cmdTemplate = '''
|
|
46
|
-
set http_proxy=http://localhost:{0}
|
|
47
|
-
set https_proxy=http://localhost:{0}
|
|
48
|
-
set all_proxy=http://localhost:{0}
|
|
49
|
-
'''
|
|
50
|
-
|
|
51
|
-
powerShellTemplate = '''
|
|
52
|
-
$env:http_proxy="http://localhost:{0}"
|
|
53
|
-
$env:https_proxy="http://localhost:{0}"
|
|
54
|
-
$env:all_proxy="http://localhost:{0}"
|
|
55
|
-
'''
|