batch-img 0.0.7__tar.gz
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.
- batch_img-0.0.7/LICENSE +21 -0
- batch_img-0.0.7/MANIFEST.in +3 -0
- batch_img-0.0.7/PKG-INFO +154 -0
- batch_img-0.0.7/README.md +129 -0
- batch_img-0.0.7/batch_img/__init__.py +0 -0
- batch_img-0.0.7/batch_img/border.py +86 -0
- batch_img-0.0.7/batch_img/common.py +259 -0
- batch_img-0.0.7/batch_img/const.py +26 -0
- batch_img-0.0.7/batch_img/defaults.py +134 -0
- batch_img-0.0.7/batch_img/interface.py +148 -0
- batch_img-0.0.7/batch_img/main.py +137 -0
- batch_img-0.0.7/batch_img/orientation.py +112 -0
- batch_img-0.0.7/batch_img/resize.py +79 -0
- batch_img-0.0.7/batch_img/rotate.py +121 -0
- batch_img-0.0.7/batch_img.egg-info/PKG-INFO +154 -0
- batch_img-0.0.7/batch_img.egg-info/SOURCES.txt +20 -0
- batch_img-0.0.7/batch_img.egg-info/dependency_links.txt +1 -0
- batch_img-0.0.7/batch_img.egg-info/entry_points.txt +2 -0
- batch_img-0.0.7/batch_img.egg-info/requires.txt +8 -0
- batch_img-0.0.7/batch_img.egg-info/top_level.txt +3 -0
- batch_img-0.0.7/pyproject.toml +38 -0
- batch_img-0.0.7/setup.cfg +4 -0
batch_img-0.0.7/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 John Liu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
batch_img-0.0.7/PKG-INFO
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: batch_img
|
|
3
|
+
Version: 0.0.7
|
|
4
|
+
Summary: Batch processing image files by utilizing Pillow / PIL library
|
|
5
|
+
Author: John Liu
|
|
6
|
+
Project-URL: Download, https://artifacts.some.where
|
|
7
|
+
Project-URL: Homepage, https://github.com/john-liu2/batch_img
|
|
8
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
11
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Requires-Python: >=3.12
|
|
14
|
+
Description-Content-Type: text/markdown
|
|
15
|
+
License-File: LICENSE
|
|
16
|
+
Requires-Dist: click
|
|
17
|
+
Requires-Dist: loguru
|
|
18
|
+
Requires-Dist: piexif
|
|
19
|
+
Requires-Dist: pillow
|
|
20
|
+
Requires-Dist: pillow-heif
|
|
21
|
+
Requires-Dist: tqdm
|
|
22
|
+
Requires-Dist: numpy
|
|
23
|
+
Requires-Dist: opencv-python
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
## batch_img
|
|
27
|
+
|
|
28
|
+
Batch processing image files by utilizing **[Pillow / PIL](https://github.com/python-pillow/Pillow)** library.
|
|
29
|
+
Resize, rotate, add border or do default actions on a single image file or all image files in a folder.
|
|
30
|
+
Tested these image file formats (**HEIC, JPG, PNG**) on macOS.
|
|
31
|
+
|
|
32
|
+
### Installation
|
|
33
|
+
|
|
34
|
+
#### One Time Setup
|
|
35
|
+
|
|
36
|
+
One time installation of the `uv` tool to prepare for **All** future Python tools installation.
|
|
37
|
+
Install `uv` tool by its standalone installers:
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
# On macOS and Linux.
|
|
41
|
+
curl -LsSf https://astral.sh/uv/install.sh | sh
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
```
|
|
45
|
+
# On Windows.
|
|
46
|
+
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
#### Install the `batch_img` tool
|
|
50
|
+
|
|
51
|
+
Install the `batch_img` tool from PyPI:
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
uv pip install --upgrade batch_img
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
### Usage
|
|
58
|
+
|
|
59
|
+
#### Sample command lines:
|
|
60
|
+
|
|
61
|
+
```
|
|
62
|
+
✗ batch_img --version
|
|
63
|
+
0.0.7
|
|
64
|
+
|
|
65
|
+
✗ batch_img rotate --degree 90 ~/Downloads/IMG_0070.HEIC
|
|
66
|
+
...
|
|
67
|
+
✅ Processed the image file(s)
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### Help
|
|
71
|
+
|
|
72
|
+
#### Top level commands help:
|
|
73
|
+
|
|
74
|
+
```
|
|
75
|
+
✗ batch_img --help
|
|
76
|
+
Usage: batch_img [OPTIONS] COMMAND [ARGS]...
|
|
77
|
+
|
|
78
|
+
Options:
|
|
79
|
+
--version Show this tool's version
|
|
80
|
+
--help Show this message and exit.
|
|
81
|
+
|
|
82
|
+
Commands:
|
|
83
|
+
border Add border to image file(s)
|
|
84
|
+
defaults Process image file(s) with default actions: 1) resize to...
|
|
85
|
+
resize Resize image file(s)
|
|
86
|
+
rotate Rotate image file(s)
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
#### The `border` sub-command CLI options:
|
|
90
|
+
|
|
91
|
+
```
|
|
92
|
+
✗ batch_img border --help
|
|
93
|
+
Usage: batch_img border [OPTIONS] SRC_PATH
|
|
94
|
+
|
|
95
|
+
Add internal border to image file(s), not expand the size
|
|
96
|
+
|
|
97
|
+
Options:
|
|
98
|
+
-bw, --border_width INTEGER RANGE
|
|
99
|
+
Add border to image file(s) with the
|
|
100
|
+
border_width. 0 - no border [default: 5;
|
|
101
|
+
0<=x<=30]
|
|
102
|
+
-bc, --border_color TEXT Add border to image file(s) with the
|
|
103
|
+
border_color string [default: gray]
|
|
104
|
+
-o, --output TEXT Output file path. If skipped, use the
|
|
105
|
+
current dir path [default: ""]
|
|
106
|
+
--help Show this message and exit.
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
#### The `defaults` sub-command CLI options:
|
|
110
|
+
|
|
111
|
+
```
|
|
112
|
+
✗ batch_img defaults --help
|
|
113
|
+
Usage: batch_img defaults [OPTIONS] SRC_PATH
|
|
114
|
+
|
|
115
|
+
Process image file(s) with default actions: 1) resize to 1280; 2) add
|
|
116
|
+
5-pixel gray color border; 3) auto-rotate if needed
|
|
117
|
+
|
|
118
|
+
Options:
|
|
119
|
+
-o, --output TEXT Output file path. If skipped, use the current dir path
|
|
120
|
+
[default: ""]
|
|
121
|
+
--help Show this message and exit.
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
#### The `resize` sub-command CLI options:
|
|
125
|
+
|
|
126
|
+
```
|
|
127
|
+
✗ batch_img resize --help
|
|
128
|
+
Usage: batch_img resize [OPTIONS] SRC_PATH
|
|
129
|
+
|
|
130
|
+
Resize image file(s)
|
|
131
|
+
|
|
132
|
+
Options:
|
|
133
|
+
-l, --length INTEGER RANGE Resize image file(s) on original aspect ratio to
|
|
134
|
+
the length. 0 - no resize [default: 0; x>=0]
|
|
135
|
+
-o, --output TEXT Output file path. If skipped, use the current
|
|
136
|
+
dir path [default: ""]
|
|
137
|
+
--help Show this message and exit.
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
#### The `rotate` sub-command CLI options:
|
|
141
|
+
|
|
142
|
+
```
|
|
143
|
+
✗ batch_img rotate --help
|
|
144
|
+
Usage: batch_img rotate [OPTIONS] SRC_PATH
|
|
145
|
+
|
|
146
|
+
Rotate image file(s)
|
|
147
|
+
|
|
148
|
+
Options:
|
|
149
|
+
-a, --angle INTEGER RANGE Rotate image file(s) to the clockwise angle. 0 -
|
|
150
|
+
no rotate [default: 0; x>=0]
|
|
151
|
+
-o, --output TEXT Output file path. If skipped, use the current dir
|
|
152
|
+
path [default: ""]
|
|
153
|
+
--help Show this message and exit.
|
|
154
|
+
```
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
## batch_img
|
|
2
|
+
|
|
3
|
+
Batch processing image files by utilizing **[Pillow / PIL](https://github.com/python-pillow/Pillow)** library.
|
|
4
|
+
Resize, rotate, add border or do default actions on a single image file or all image files in a folder.
|
|
5
|
+
Tested these image file formats (**HEIC, JPG, PNG**) on macOS.
|
|
6
|
+
|
|
7
|
+
### Installation
|
|
8
|
+
|
|
9
|
+
#### One Time Setup
|
|
10
|
+
|
|
11
|
+
One time installation of the `uv` tool to prepare for **All** future Python tools installation.
|
|
12
|
+
Install `uv` tool by its standalone installers:
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
# On macOS and Linux.
|
|
16
|
+
curl -LsSf https://astral.sh/uv/install.sh | sh
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
```
|
|
20
|
+
# On Windows.
|
|
21
|
+
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
#### Install the `batch_img` tool
|
|
25
|
+
|
|
26
|
+
Install the `batch_img` tool from PyPI:
|
|
27
|
+
|
|
28
|
+
```
|
|
29
|
+
uv pip install --upgrade batch_img
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
### Usage
|
|
33
|
+
|
|
34
|
+
#### Sample command lines:
|
|
35
|
+
|
|
36
|
+
```
|
|
37
|
+
✗ batch_img --version
|
|
38
|
+
0.0.7
|
|
39
|
+
|
|
40
|
+
✗ batch_img rotate --degree 90 ~/Downloads/IMG_0070.HEIC
|
|
41
|
+
...
|
|
42
|
+
✅ Processed the image file(s)
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### Help
|
|
46
|
+
|
|
47
|
+
#### Top level commands help:
|
|
48
|
+
|
|
49
|
+
```
|
|
50
|
+
✗ batch_img --help
|
|
51
|
+
Usage: batch_img [OPTIONS] COMMAND [ARGS]...
|
|
52
|
+
|
|
53
|
+
Options:
|
|
54
|
+
--version Show this tool's version
|
|
55
|
+
--help Show this message and exit.
|
|
56
|
+
|
|
57
|
+
Commands:
|
|
58
|
+
border Add border to image file(s)
|
|
59
|
+
defaults Process image file(s) with default actions: 1) resize to...
|
|
60
|
+
resize Resize image file(s)
|
|
61
|
+
rotate Rotate image file(s)
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
#### The `border` sub-command CLI options:
|
|
65
|
+
|
|
66
|
+
```
|
|
67
|
+
✗ batch_img border --help
|
|
68
|
+
Usage: batch_img border [OPTIONS] SRC_PATH
|
|
69
|
+
|
|
70
|
+
Add internal border to image file(s), not expand the size
|
|
71
|
+
|
|
72
|
+
Options:
|
|
73
|
+
-bw, --border_width INTEGER RANGE
|
|
74
|
+
Add border to image file(s) with the
|
|
75
|
+
border_width. 0 - no border [default: 5;
|
|
76
|
+
0<=x<=30]
|
|
77
|
+
-bc, --border_color TEXT Add border to image file(s) with the
|
|
78
|
+
border_color string [default: gray]
|
|
79
|
+
-o, --output TEXT Output file path. If skipped, use the
|
|
80
|
+
current dir path [default: ""]
|
|
81
|
+
--help Show this message and exit.
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
#### The `defaults` sub-command CLI options:
|
|
85
|
+
|
|
86
|
+
```
|
|
87
|
+
✗ batch_img defaults --help
|
|
88
|
+
Usage: batch_img defaults [OPTIONS] SRC_PATH
|
|
89
|
+
|
|
90
|
+
Process image file(s) with default actions: 1) resize to 1280; 2) add
|
|
91
|
+
5-pixel gray color border; 3) auto-rotate if needed
|
|
92
|
+
|
|
93
|
+
Options:
|
|
94
|
+
-o, --output TEXT Output file path. If skipped, use the current dir path
|
|
95
|
+
[default: ""]
|
|
96
|
+
--help Show this message and exit.
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
#### The `resize` sub-command CLI options:
|
|
100
|
+
|
|
101
|
+
```
|
|
102
|
+
✗ batch_img resize --help
|
|
103
|
+
Usage: batch_img resize [OPTIONS] SRC_PATH
|
|
104
|
+
|
|
105
|
+
Resize image file(s)
|
|
106
|
+
|
|
107
|
+
Options:
|
|
108
|
+
-l, --length INTEGER RANGE Resize image file(s) on original aspect ratio to
|
|
109
|
+
the length. 0 - no resize [default: 0; x>=0]
|
|
110
|
+
-o, --output TEXT Output file path. If skipped, use the current
|
|
111
|
+
dir path [default: ""]
|
|
112
|
+
--help Show this message and exit.
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
#### The `rotate` sub-command CLI options:
|
|
116
|
+
|
|
117
|
+
```
|
|
118
|
+
✗ batch_img rotate --help
|
|
119
|
+
Usage: batch_img rotate [OPTIONS] SRC_PATH
|
|
120
|
+
|
|
121
|
+
Rotate image file(s)
|
|
122
|
+
|
|
123
|
+
Options:
|
|
124
|
+
-a, --angle INTEGER RANGE Rotate image file(s) to the clockwise angle. 0 -
|
|
125
|
+
no rotate [default: 0; x>=0]
|
|
126
|
+
-o, --output TEXT Output file path. If skipped, use the current dir
|
|
127
|
+
path [default: ""]
|
|
128
|
+
--help Show this message and exit.
|
|
129
|
+
```
|
|
File without changes
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""class Border: add border to the image file(s)
|
|
2
|
+
Copyright © 2025 John Liu
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import piexif
|
|
8
|
+
import pillow_heif
|
|
9
|
+
from loguru import logger
|
|
10
|
+
from PIL import Image
|
|
11
|
+
|
|
12
|
+
from batch_img.common import Common
|
|
13
|
+
|
|
14
|
+
pillow_heif.register_heif_opener() # allow Pillow to open HEIC files
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Border:
|
|
18
|
+
@staticmethod
|
|
19
|
+
def add_border_1_image(
|
|
20
|
+
in_path: Path, out_path: Path, border_width: int, border_color: str
|
|
21
|
+
) -> tuple:
|
|
22
|
+
"""Add internal border to an image file, not to expand the size
|
|
23
|
+
|
|
24
|
+
Args:
|
|
25
|
+
in_path: input file path
|
|
26
|
+
out_path: output dir path
|
|
27
|
+
border_width: border width int
|
|
28
|
+
border_color: border color str
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
tuple: bool, str
|
|
32
|
+
"""
|
|
33
|
+
try:
|
|
34
|
+
with Image.open(in_path) as img:
|
|
35
|
+
width, height = img.size
|
|
36
|
+
box = Common.get_crop_box(width, height, border_width)
|
|
37
|
+
cropped_img = img.crop(box)
|
|
38
|
+
bd_img = Image.new(img.mode, (width, height), border_color)
|
|
39
|
+
bd_img.paste(cropped_img, (border_width, border_width))
|
|
40
|
+
|
|
41
|
+
out_path.mkdir(parents=True, exist_ok=True)
|
|
42
|
+
out_file = out_path
|
|
43
|
+
if out_path.is_dir():
|
|
44
|
+
filename = f"{in_path.stem}_bw{border_width}{in_path.suffix}"
|
|
45
|
+
out_file = Path(f"{out_path}/{filename}")
|
|
46
|
+
exif_dict = None
|
|
47
|
+
if "exif" in img.info:
|
|
48
|
+
exif_dict = piexif.load(img.info["exif"])
|
|
49
|
+
if exif_dict:
|
|
50
|
+
exif_bytes = piexif.dump(exif_dict)
|
|
51
|
+
bd_img.save(out_file, img.format, optimize=True, exif=exif_bytes)
|
|
52
|
+
else:
|
|
53
|
+
bd_img.save(out_file, img.format, optimize=True)
|
|
54
|
+
logger.info(f"Saved {out_file}")
|
|
55
|
+
return True, out_file
|
|
56
|
+
except (AttributeError, FileNotFoundError, ValueError) as e:
|
|
57
|
+
return False, f"{in_path}:\n{e}"
|
|
58
|
+
|
|
59
|
+
@staticmethod
|
|
60
|
+
def add_border_all_in_dir(
|
|
61
|
+
in_path: Path, out_path: Path, border_width: int, border_color: str
|
|
62
|
+
) -> bool:
|
|
63
|
+
"""Add border to all image files in the given dir
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
in_path: input dir path
|
|
67
|
+
out_path: output dir path
|
|
68
|
+
border_width: border width int
|
|
69
|
+
border_color: border color str
|
|
70
|
+
|
|
71
|
+
Returns:
|
|
72
|
+
bool: True - Success. False - Error
|
|
73
|
+
"""
|
|
74
|
+
image_files = Common.prepare_all_files(in_path, out_path)
|
|
75
|
+
if not image_files:
|
|
76
|
+
logger.error(f"No image files at {in_path}")
|
|
77
|
+
return False
|
|
78
|
+
tasks = [(f, out_path, border_width, border_color) for f in image_files]
|
|
79
|
+
files_cnt = len(tasks)
|
|
80
|
+
|
|
81
|
+
logger.info(f"Add border to {files_cnt} image files in multiprocess ...")
|
|
82
|
+
success_cnt = Common.multiprocess_progress_bar(
|
|
83
|
+
Border.add_border_1_image, "Add border to image files", tasks
|
|
84
|
+
)
|
|
85
|
+
logger.info(f"\nSuccessfully added border to {success_cnt}/{files_cnt} files")
|
|
86
|
+
return True
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""class Common: common utilities
|
|
2
|
+
Copyright © 2025 John Liu
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import itertools
|
|
6
|
+
import json
|
|
7
|
+
import subprocess
|
|
8
|
+
import tomllib
|
|
9
|
+
from datetime import datetime
|
|
10
|
+
from importlib.metadata import version
|
|
11
|
+
from multiprocessing import Pool, cpu_count
|
|
12
|
+
from os.path import getmtime, getsize
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
import piexif
|
|
16
|
+
import pillow_heif
|
|
17
|
+
from loguru import logger
|
|
18
|
+
from PIL import Image, ImageChops
|
|
19
|
+
from PIL.TiffImagePlugin import IFDRational
|
|
20
|
+
from tqdm import tqdm
|
|
21
|
+
|
|
22
|
+
from batch_img.const import PATTERNS, PKG_NAME, TS_FORMAT, VER
|
|
23
|
+
|
|
24
|
+
pillow_heif.register_heif_opener() # allow Pillow to open HEIC files
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Common:
|
|
28
|
+
@staticmethod
|
|
29
|
+
def get_version() -> str:
|
|
30
|
+
"""
|
|
31
|
+
Get this package version using several ways
|
|
32
|
+
"""
|
|
33
|
+
try:
|
|
34
|
+
return version(PKG_NAME)
|
|
35
|
+
except (FileNotFoundError, ImportError, ValueError) as e:
|
|
36
|
+
# Use lazy % formatting in logging for efficiency
|
|
37
|
+
logger.warning(f"importlib.metadata.version Error: {e}")
|
|
38
|
+
logger.debug("Try to get version from pyproject.toml file")
|
|
39
|
+
pyproject = Path(__file__).parent.parent / "pyproject.toml"
|
|
40
|
+
with open(pyproject, "rb") as f:
|
|
41
|
+
return tomllib.load(f)["project"][VER]
|
|
42
|
+
|
|
43
|
+
@staticmethod
|
|
44
|
+
def run_cmd(cmd: str) -> tuple:
|
|
45
|
+
"""Run a command on the host and get the output
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
cmd (str): a command line with options
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
tuple: returnCode, StdOut, StdErr
|
|
52
|
+
"""
|
|
53
|
+
logger.debug(f"{cmd=}")
|
|
54
|
+
try:
|
|
55
|
+
p = subprocess.run(
|
|
56
|
+
cmd, capture_output=True, text=True, shell=True, check=True
|
|
57
|
+
)
|
|
58
|
+
r_code = p.returncode
|
|
59
|
+
stdout = p.stdout
|
|
60
|
+
stderr = p.stderr
|
|
61
|
+
logger.debug(f"'{cmd}'\n {r_code=}\n {stdout=}\n {stderr=}")
|
|
62
|
+
return r_code, stdout, stderr
|
|
63
|
+
except subprocess.CalledProcessError as e:
|
|
64
|
+
logger.exception(e)
|
|
65
|
+
raise e
|
|
66
|
+
|
|
67
|
+
@staticmethod
|
|
68
|
+
def readable_file_size(in_bytes: int) -> str:
|
|
69
|
+
"""Convert bytes to human-readable KB, MB, or GB
|
|
70
|
+
|
|
71
|
+
Args:
|
|
72
|
+
in_bytes: input bytes integer
|
|
73
|
+
|
|
74
|
+
Returns:
|
|
75
|
+
str
|
|
76
|
+
"""
|
|
77
|
+
for _unit in ["B", "KB", "MB", "GB"]:
|
|
78
|
+
if in_bytes < 1024:
|
|
79
|
+
break
|
|
80
|
+
in_bytes /= 1024
|
|
81
|
+
res = f"{in_bytes} B" if _unit == "B" else f"{in_bytes:.1f} {_unit}"
|
|
82
|
+
return res
|
|
83
|
+
|
|
84
|
+
@staticmethod
|
|
85
|
+
def decode_exif(exif_data: str) -> dict:
|
|
86
|
+
"""Decode the EXIF data
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
exif_data: str
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
dict
|
|
93
|
+
"""
|
|
94
|
+
exif_dict = piexif.load(exif_data)
|
|
95
|
+
_dict = {}
|
|
96
|
+
for ifd_name, val in exif_dict.items():
|
|
97
|
+
# Canon EOS 5D Mark II 'thumbnail': b'\xff\xd8\xff\xdb...
|
|
98
|
+
# 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
|
|
99
|
+
if not val or ifd_name == "thumbnail":
|
|
100
|
+
continue
|
|
101
|
+
for tag_id, value in val.items():
|
|
102
|
+
tag_name = piexif.TAGS[ifd_name].get(tag_id, {}).get("name", tag_id)
|
|
103
|
+
_dict[tag_name] = value
|
|
104
|
+
# logger.info(f"{_dict=}")
|
|
105
|
+
for key in (
|
|
106
|
+
"FNumber",
|
|
107
|
+
"FocalLength",
|
|
108
|
+
"MakerNote",
|
|
109
|
+
"SceneType",
|
|
110
|
+
"SubjectArea",
|
|
111
|
+
"Software",
|
|
112
|
+
"HostComputer",
|
|
113
|
+
"UserComment",
|
|
114
|
+
):
|
|
115
|
+
if key in _dict:
|
|
116
|
+
_dict.pop(key)
|
|
117
|
+
keys = list(_dict.keys())
|
|
118
|
+
for keyword in (
|
|
119
|
+
"DateTime",
|
|
120
|
+
"GPS",
|
|
121
|
+
"OffsetTime",
|
|
122
|
+
"SubSecTime",
|
|
123
|
+
"Tile",
|
|
124
|
+
"Pixel",
|
|
125
|
+
"Lens",
|
|
126
|
+
"Resolution",
|
|
127
|
+
"Value",
|
|
128
|
+
):
|
|
129
|
+
for key in keys:
|
|
130
|
+
if key.startswith(keyword) or key.endswith(keyword):
|
|
131
|
+
_dict.pop(key)
|
|
132
|
+
_res = {
|
|
133
|
+
k: (v.decode() if isinstance(v, bytes) else v) for k, v in _dict.items()
|
|
134
|
+
}
|
|
135
|
+
logger.info(f"{_res=}")
|
|
136
|
+
return _res
|
|
137
|
+
|
|
138
|
+
@staticmethod
|
|
139
|
+
def get_image_data(file: Path) -> tuple:
|
|
140
|
+
"""Get image file data
|
|
141
|
+
|
|
142
|
+
Args:
|
|
143
|
+
file: image file path
|
|
144
|
+
|
|
145
|
+
Returns:
|
|
146
|
+
tuple: data, info
|
|
147
|
+
"""
|
|
148
|
+
size = getsize(file)
|
|
149
|
+
m_ts = datetime.fromtimestamp(getmtime(file)).strftime(TS_FORMAT)
|
|
150
|
+
with Image.open(file) as img:
|
|
151
|
+
data = img.convert("RGB")
|
|
152
|
+
d_info = {
|
|
153
|
+
"file_size": Common.readable_file_size(size),
|
|
154
|
+
"file_ts": m_ts,
|
|
155
|
+
"format": img.format,
|
|
156
|
+
"mode": img.mode,
|
|
157
|
+
"size": img.size,
|
|
158
|
+
"info": img.info,
|
|
159
|
+
}
|
|
160
|
+
for key in ("icc_profile", "xmp"):
|
|
161
|
+
if key in img.info:
|
|
162
|
+
img.info.pop(key)
|
|
163
|
+
if "exif" in img.info:
|
|
164
|
+
exif_data = img.info.pop("exif")
|
|
165
|
+
d_info["exif"] = Common.decode_exif(exif_data)
|
|
166
|
+
|
|
167
|
+
return data, d_info
|
|
168
|
+
|
|
169
|
+
@staticmethod
|
|
170
|
+
def jsn_serial(obj):
|
|
171
|
+
"""JSON serializer for objects not serializable by default json code"""
|
|
172
|
+
if isinstance(obj, IFDRational):
|
|
173
|
+
return float(obj)
|
|
174
|
+
if isinstance(obj, bytes):
|
|
175
|
+
return obj.decode()
|
|
176
|
+
raise TypeError(
|
|
177
|
+
f"Object of type {obj.__class__.__name__} is not JSON serializable"
|
|
178
|
+
)
|
|
179
|
+
|
|
180
|
+
@staticmethod
|
|
181
|
+
def are_images_equal(path1: Path, path2: Path) -> bool:
|
|
182
|
+
"""Check if two image files are visually equal pixel-wise
|
|
183
|
+
|
|
184
|
+
Args:
|
|
185
|
+
path1: image1 file path
|
|
186
|
+
path2: image2 file path
|
|
187
|
+
|
|
188
|
+
Returns:
|
|
189
|
+
bool: True - visually equal, False - not visually equal
|
|
190
|
+
"""
|
|
191
|
+
data1, meta1 = Common.get_image_data(path1)
|
|
192
|
+
data2, meta2 = Common.get_image_data(path2)
|
|
193
|
+
|
|
194
|
+
logger.info(
|
|
195
|
+
f"{path1}:\n{json.dumps(meta1, indent=2, default=Common.jsn_serial)}"
|
|
196
|
+
)
|
|
197
|
+
logger.info(
|
|
198
|
+
f"{path2}:\n{json.dumps(meta2, indent=2, default=Common.jsn_serial)}"
|
|
199
|
+
)
|
|
200
|
+
return ImageChops.difference(data1, data2).getbbox() is None
|
|
201
|
+
|
|
202
|
+
@staticmethod
|
|
203
|
+
def get_crop_box(width, height, border_width) -> tuple[float, float, float, float]:
|
|
204
|
+
"""Get the crop box tuple
|
|
205
|
+
|
|
206
|
+
Args:
|
|
207
|
+
width: image width int
|
|
208
|
+
height: image height int
|
|
209
|
+
border_width: border width int
|
|
210
|
+
|
|
211
|
+
Returns:
|
|
212
|
+
tuple[float, float, float, float]
|
|
213
|
+
"""
|
|
214
|
+
crop_left = border_width
|
|
215
|
+
crop_top = border_width
|
|
216
|
+
crop_right = width - border_width
|
|
217
|
+
crop_bottom = height - border_width
|
|
218
|
+
return crop_left, crop_top, crop_right, crop_bottom
|
|
219
|
+
|
|
220
|
+
@staticmethod
|
|
221
|
+
def prepare_all_files(in_path: Path, out_path: Path):
|
|
222
|
+
"""
|
|
223
|
+
|
|
224
|
+
Args:
|
|
225
|
+
in_path: input dir path
|
|
226
|
+
out_path: output dir path
|
|
227
|
+
|
|
228
|
+
Returns:
|
|
229
|
+
iterable: files list generator
|
|
230
|
+
"""
|
|
231
|
+
out_path.mkdir(parents=True, exist_ok=True)
|
|
232
|
+
_files = itertools.chain.from_iterable(in_path.glob(p) for p in PATTERNS)
|
|
233
|
+
return _files
|
|
234
|
+
|
|
235
|
+
@staticmethod
|
|
236
|
+
def multiprocess_progress_bar(func, desc, tasks: list) -> int:
|
|
237
|
+
"""Run task in multiprocess with progress bar
|
|
238
|
+
|
|
239
|
+
Args:
|
|
240
|
+
func: function to be run in multiprocess
|
|
241
|
+
desc: description str
|
|
242
|
+
tasks: tasks list for multiprocess pool
|
|
243
|
+
|
|
244
|
+
Returns:
|
|
245
|
+
int: success_cnt
|
|
246
|
+
"""
|
|
247
|
+
success_cnt = 0
|
|
248
|
+
files_cnt = len(tasks)
|
|
249
|
+
workers = max(cpu_count(), 4)
|
|
250
|
+
|
|
251
|
+
with Pool(workers) as pool:
|
|
252
|
+
with tqdm(total=files_cnt, desc=desc) as pbar:
|
|
253
|
+
for ok, res in pool.starmap(func, tasks):
|
|
254
|
+
if ok:
|
|
255
|
+
success_cnt += 1
|
|
256
|
+
else:
|
|
257
|
+
tqdm.write(f"Error: {res}")
|
|
258
|
+
pbar.update()
|
|
259
|
+
return success_cnt
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""const.py - define constants
|
|
2
|
+
Copyright © 2025 John Liu
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
PKG_NAME = "batch_img"
|
|
6
|
+
VER = "version"
|
|
7
|
+
NAME = "name"
|
|
8
|
+
UNKNOWN = "unknown"
|
|
9
|
+
|
|
10
|
+
MSG_OK = "✅ Processed the image file(s)"
|
|
11
|
+
MSG_BAD = "❌ Failed to process the image file(s)."
|
|
12
|
+
|
|
13
|
+
TS_FORMAT = "%Y-%m-%d_%H-%M-%S"
|
|
14
|
+
PATTERNS = (
|
|
15
|
+
"*.HEIC",
|
|
16
|
+
"*.heic",
|
|
17
|
+
"*.JPG",
|
|
18
|
+
"*.jpg",
|
|
19
|
+
"*.JPEG",
|
|
20
|
+
"*.jpeg",
|
|
21
|
+
"*.PNG",
|
|
22
|
+
"*.png",
|
|
23
|
+
)
|
|
24
|
+
MAX_LENGTH = 1280
|
|
25
|
+
BD_WIDTH = 5
|
|
26
|
+
BD_COLOR = "green"
|