Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
70 lines (58 loc) · 2 KB
/
Copy pathutils.py
File metadata and controls
70 lines (58 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import re
from pathlib import Path
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.webp', '.tiff', '.tif', '.bmp', '.gif', '.avif', '.heic', '.heif', '.svg'}
SIZE_PATTERNS = [
(r'^(\d+)x$', 'width'),
(r'^x(\d+)$', 'height'),
(r'^(\d+)x(\d+)$', 'box'),
(r'^(\d+)x(\d+)!$', 'stretch'),
(r'^宽(\d+)$', 'width'),
(r'^宽度(\d+)$', 'width'),
(r'^高(\d+)$', 'height'),
(r'^高度(\d+)$', 'height'),
(r'^(\d+)$', 'width'),
]
OPERATION_ALIASES = {
'右旋': 'rot_right',
'右': 'rot_right',
'左旋': 'rot_left',
'左': 'rot_left',
'左右翻转': 'flip_h',
'左右': 'flip_h',
'上下翻转': 'flip_v',
'上下': 'flip_v',
'批量': 'batch',
'批': 'batch',
'动画': 'keep_animation',
'动': 'keep_animation',
'拉伸': 'stretch',
'拉': 'stretch',
}
def is_image_file(path: str) -> bool:
return Path(path).suffix.lower() in IMAGE_EXTENSIONS
def parse_size(size_str: str):
for pattern, size_type in SIZE_PATTERNS:
match = re.match(pattern, size_str)
if match:
if size_type == 'width':
return ('width', int(match.group(1)))
elif size_type == 'height':
return ('height', int(match.group(1)))
elif size_type == 'box':
return ('box', (int(match.group(1)), int(match.group(2))))
elif size_type == 'stretch':
return ('stretch', (int(match.group(1)), int(match.group(2))))
return None
def get_output_path(input_path: str, output_dir: str, target_ext: str):
input_name = Path(input_path).stem
output_dir_path = Path(output_dir)
output_dir_path.mkdir(parents=True, exist_ok=True)
base_output = output_dir_path / f"{input_name}.{target_ext}"
if not base_output.exists():
return str(base_output)
counter = 0
while True:
candidate = output_dir_path / f"{input_name}-{counter}.{target_ext}"
if not candidate.exists():
return str(candidate)
counter += 1