imagex 0.3.0__tar.gz → 0.4.0__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.
- {imagex-0.3.0 → imagex-0.4.0}/PKG-INFO +16 -12
- {imagex-0.3.0 → imagex-0.4.0}/README.md +15 -11
- imagex-0.4.0/imagex/__init__.py +1 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex/cli.py +59 -32
- {imagex-0.3.0 → imagex-0.4.0}/imagex/features/__init__.py +6 -0
- imagex-0.4.0/imagex/features/compress.py +237 -0
- imagex-0.4.0/imagex/features/to_pdf.py +47 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex/utils/file_ops.py +25 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex/utils/progress.py +24 -1
- imagex-0.4.0/imagex/utils/wizard.py +37 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex.egg-info/PKG-INFO +16 -12
- {imagex-0.3.0 → imagex-0.4.0}/imagex.egg-info/SOURCES.txt +3 -0
- {imagex-0.3.0 → imagex-0.4.0}/pyproject.toml +1 -1
- {imagex-0.3.0 → imagex-0.4.0}/tests/test_cli.py +34 -1
- imagex-0.4.0/tests/test_compress.py +172 -0
- imagex-0.4.0/tests/test_to_pdf.py +59 -0
- imagex-0.3.0/imagex/__init__.py +0 -1
- imagex-0.3.0/imagex/features/compress.py +0 -102
- imagex-0.3.0/tests/test_compress.py +0 -78
- {imagex-0.3.0 → imagex-0.4.0}/LICENSE +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex/__main__.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex/config.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex/features/add_noise.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex/features/convert.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex/features/flip.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex/features/grayscale.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex/features/invert.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex/features/remove_metadata.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex/features/rename_batch.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex/features/resize.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex/features/rotate.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex/features/watermark.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex/utils/__init__.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex.egg-info/dependency_links.txt +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex.egg-info/entry_points.txt +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex.egg-info/requires.txt +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/imagex.egg-info/top_level.txt +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/setup.cfg +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/tests/test_add_noise.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/tests/test_convert.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/tests/test_file_ops.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/tests/test_flip.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/tests/test_grayscale.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/tests/test_invert.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/tests/test_remove_metadata.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/tests/test_rename_batch.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/tests/test_resize.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/tests/test_rotate.py +0 -0
- {imagex-0.3.0 → imagex-0.4.0}/tests/test_watermark.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: imagex
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: All-in-one image processing CLI — resize, convert, watermark, compress, and more
|
|
5
5
|
Author-email: kushal1o1 <kushal1o1@users.noreply.github.com>
|
|
6
6
|
License: MIT License
|
|
@@ -67,7 +67,9 @@ Dynamic: license-file
|
|
|
67
67
|
╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝
|
|
68
68
|
```
|
|
69
69
|
|
|
70
|
-
Image processing CLI tool
|
|
70
|
+
Image processing CLI tool - right in your terminal.
|
|
71
|
+
|
|
72
|
+
Runs entirely on your computer. No uploads, no accounts. Interactive menu, no flags to remember.
|
|
71
73
|
|
|
72
74
|
```bash
|
|
73
75
|
pip install imagex
|
|
@@ -84,31 +86,33 @@ Navigate to any folder with images and run `imagex`.
|
|
|
84
86
|
| Flip | Mirror horizontally or vertically |
|
|
85
87
|
| Remove Metadata | Strip EXIF/XMP/IPTC (incl. AI generation markers) |
|
|
86
88
|
| Convert Format | JPG ↔ PNG ↔ WEBP ↔ TIFF ↔ BMP ↔ GIF ↔ HEIC |
|
|
87
|
-
| Compress / Optimize |
|
|
89
|
+
| Compress / Optimize | Shrink to a target size (e.g. `300kb`, `3mb`) or use a quality slider |
|
|
88
90
|
| Resize | Percentage, exact dimensions, fit within bounds |
|
|
89
91
|
| Rename Batch | Pattern-based renaming (%n, %o) |
|
|
90
92
|
| Add Noise | Gaussian or salt & pepper (bypass AI detection) |
|
|
91
93
|
| Watermark | Add text/image or remove existing |
|
|
92
94
|
| Grayscale / B&W | Convert to grayscale or true black & white |
|
|
93
|
-
| Invert Colors | Negative effect
|
|
95
|
+
| Invert Colors | Negative effect, invert all colors |
|
|
96
|
+
| Convert to PDF | Combine selected images into one PDF (one page per image) |
|
|
94
97
|
|
|
95
98
|
Full details in [OPERATIONS.md](https://github.com/kushal1o1/ImageX/blob/main/OPERATIONS.md).
|
|
96
99
|
|
|
97
100
|
## Install
|
|
98
101
|
|
|
99
102
|
```bash
|
|
100
|
-
#
|
|
101
|
-
pip install imagex
|
|
102
|
-
|
|
103
|
-
# Dev mode from repo (changes take effect immediately)
|
|
104
|
-
pip install -e .
|
|
103
|
+
pip install imagex # from PyPI
|
|
104
|
+
pip install imagex[heif] # optional: HEIC support
|
|
105
105
|
```
|
|
106
106
|
|
|
107
|
-
|
|
107
|
+
Dev mode from the repo: `pip install -e ".[dev]"`
|
|
108
|
+
|
|
109
|
+
## Built with
|
|
110
|
+
|
|
111
|
+
Built on [Pillow](https://python-pillow.org) for image work, [rich](https://github.com/Textualize/rich) for terminal output, and [questionary](https://github.com/tmbo/questionary) for the menus. The math is light as well :)
|
|
108
112
|
|
|
109
|
-
##
|
|
113
|
+
## Contributing
|
|
110
114
|
|
|
111
|
-
See [CONTRIBUTION.md](https://github.com/kushal1o1/ImageX/blob/main/CONTRIBUTION.md)
|
|
115
|
+
See [CONTRIBUTION.md](https://github.com/kushal1o1/ImageX/blob/main/CONTRIBUTION.md).
|
|
112
116
|
|
|
113
117
|
## License
|
|
114
118
|
|
|
@@ -7,7 +7,9 @@
|
|
|
7
7
|
╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝
|
|
8
8
|
```
|
|
9
9
|
|
|
10
|
-
Image processing CLI tool
|
|
10
|
+
Image processing CLI tool - right in your terminal.
|
|
11
|
+
|
|
12
|
+
Runs entirely on your computer. No uploads, no accounts. Interactive menu, no flags to remember.
|
|
11
13
|
|
|
12
14
|
```bash
|
|
13
15
|
pip install imagex
|
|
@@ -24,31 +26,33 @@ Navigate to any folder with images and run `imagex`.
|
|
|
24
26
|
| Flip | Mirror horizontally or vertically |
|
|
25
27
|
| Remove Metadata | Strip EXIF/XMP/IPTC (incl. AI generation markers) |
|
|
26
28
|
| Convert Format | JPG ↔ PNG ↔ WEBP ↔ TIFF ↔ BMP ↔ GIF ↔ HEIC |
|
|
27
|
-
| Compress / Optimize |
|
|
29
|
+
| Compress / Optimize | Shrink to a target size (e.g. `300kb`, `3mb`) or use a quality slider |
|
|
28
30
|
| Resize | Percentage, exact dimensions, fit within bounds |
|
|
29
31
|
| Rename Batch | Pattern-based renaming (%n, %o) |
|
|
30
32
|
| Add Noise | Gaussian or salt & pepper (bypass AI detection) |
|
|
31
33
|
| Watermark | Add text/image or remove existing |
|
|
32
34
|
| Grayscale / B&W | Convert to grayscale or true black & white |
|
|
33
|
-
| Invert Colors | Negative effect
|
|
35
|
+
| Invert Colors | Negative effect, invert all colors |
|
|
36
|
+
| Convert to PDF | Combine selected images into one PDF (one page per image) |
|
|
34
37
|
|
|
35
38
|
Full details in [OPERATIONS.md](https://github.com/kushal1o1/ImageX/blob/main/OPERATIONS.md).
|
|
36
39
|
|
|
37
40
|
## Install
|
|
38
41
|
|
|
39
42
|
```bash
|
|
40
|
-
#
|
|
41
|
-
pip install imagex
|
|
42
|
-
|
|
43
|
-
# Dev mode from repo (changes take effect immediately)
|
|
44
|
-
pip install -e .
|
|
43
|
+
pip install imagex # from PyPI
|
|
44
|
+
pip install imagex[heif] # optional: HEIC support
|
|
45
45
|
```
|
|
46
46
|
|
|
47
|
-
|
|
47
|
+
Dev mode from the repo: `pip install -e ".[dev]"`
|
|
48
|
+
|
|
49
|
+
## Built with
|
|
50
|
+
|
|
51
|
+
Built on [Pillow](https://python-pillow.org) for image work, [rich](https://github.com/Textualize/rich) for terminal output, and [questionary](https://github.com/tmbo/questionary) for the menus. The math is light as well :)
|
|
48
52
|
|
|
49
|
-
##
|
|
53
|
+
## Contributing
|
|
50
54
|
|
|
51
|
-
See [CONTRIBUTION.md](https://github.com/kushal1o1/ImageX/blob/main/CONTRIBUTION.md)
|
|
55
|
+
See [CONTRIBUTION.md](https://github.com/kushal1o1/ImageX/blob/main/CONTRIBUTION.md).
|
|
52
56
|
|
|
53
57
|
## License
|
|
54
58
|
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.4.0"
|
|
@@ -12,7 +12,8 @@ from rich.panel import Panel
|
|
|
12
12
|
from imagex import __version__
|
|
13
13
|
from imagex.features import get_features
|
|
14
14
|
from imagex.utils.file_ops import find_images
|
|
15
|
-
from imagex.utils.progress import process_files
|
|
15
|
+
from imagex.utils.progress import process_batch, process_files
|
|
16
|
+
from imagex.utils.wizard import BACK, run_steps
|
|
16
17
|
|
|
17
18
|
console = Console()
|
|
18
19
|
|
|
@@ -103,7 +104,7 @@ def select_features() -> Optional[list[str]]:
|
|
|
103
104
|
return selected
|
|
104
105
|
|
|
105
106
|
|
|
106
|
-
def ask_output_mode() -> tuple[str, Optional[Path]]:
|
|
107
|
+
def ask_output_mode() -> tuple[str, Optional[Path]] | str | None:
|
|
107
108
|
mode = questionary.select(
|
|
108
109
|
"Where should the processed images go?",
|
|
109
110
|
choices=[
|
|
@@ -119,21 +120,28 @@ def ask_output_mode() -> tuple[str, Optional[Path]]:
|
|
|
119
120
|
title="Save to custom folder",
|
|
120
121
|
value="custom",
|
|
121
122
|
),
|
|
123
|
+
questionary.Separator(),
|
|
124
|
+
questionary.Choice(title="← Back", value=BACK),
|
|
122
125
|
],
|
|
123
126
|
).ask()
|
|
124
127
|
|
|
128
|
+
if mode in (BACK, None):
|
|
129
|
+
return mode
|
|
130
|
+
|
|
125
131
|
output_dir = None
|
|
126
132
|
if mode == "custom":
|
|
127
133
|
custom = questionary.text(
|
|
128
134
|
"Enter output folder path:",
|
|
129
135
|
validate=lambda p: len(p.strip()) > 0 or "Path cannot be empty",
|
|
130
136
|
).ask()
|
|
137
|
+
if custom is None: # Ctrl+C / Esc on the prompt: cancel the flow
|
|
138
|
+
return None
|
|
131
139
|
output_dir = Path(custom.strip())
|
|
132
140
|
|
|
133
141
|
return mode, output_dir
|
|
134
142
|
|
|
135
143
|
|
|
136
|
-
def select_files(all_files: list[Path]) ->
|
|
144
|
+
def select_files(all_files: list[Path]) -> list[Path] | str | None:
|
|
137
145
|
if not all_files:
|
|
138
146
|
return None
|
|
139
147
|
|
|
@@ -153,9 +161,13 @@ def select_files(all_files: list[Path]) -> Optional[list[Path]]:
|
|
|
153
161
|
|
|
154
162
|
selected = questionary.checkbox(
|
|
155
163
|
"Which images to process? (Space to toggle, Enter to confirm)",
|
|
156
|
-
choices=[all_choice
|
|
164
|
+
choices=[all_choice, *file_choices, questionary.Separator(),
|
|
165
|
+
questionary.Choice(title="← Back", value=BACK)],
|
|
157
166
|
).ask()
|
|
158
167
|
|
|
168
|
+
if selected and BACK in selected:
|
|
169
|
+
return BACK
|
|
170
|
+
|
|
159
171
|
if not selected:
|
|
160
172
|
return None
|
|
161
173
|
|
|
@@ -188,49 +200,64 @@ def main():
|
|
|
188
200
|
try:
|
|
189
201
|
show_banner()
|
|
190
202
|
|
|
191
|
-
|
|
192
|
-
if selected is None:
|
|
193
|
-
console.print("[yellow]No feature selected. Exiting.[/yellow]")
|
|
194
|
-
return
|
|
203
|
+
features = get_features()
|
|
195
204
|
|
|
196
205
|
all_files = find_images(Path.cwd())
|
|
197
206
|
if not all_files:
|
|
198
207
|
console.print("[red]No image files found in current directory.[/red]")
|
|
199
|
-
console.print(
|
|
208
|
+
console.print(
|
|
209
|
+
"[dim]Supported: .jpg .jpeg .png .webp .tiff .tif .bmp .gif .ico[/dim]"
|
|
210
|
+
)
|
|
200
211
|
return
|
|
201
212
|
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
console.print("[yellow]No files selected. Exiting.[/yellow]")
|
|
205
|
-
return
|
|
213
|
+
def step_features(_results):
|
|
214
|
+
return select_features()
|
|
206
215
|
|
|
207
|
-
|
|
216
|
+
def step_files(_results):
|
|
217
|
+
files = select_files(all_files)
|
|
218
|
+
if files not in (None, BACK):
|
|
219
|
+
console.print(f"[green]Selected {len(files)} image(s)[/green]")
|
|
220
|
+
return files
|
|
208
221
|
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
222
|
+
def step_output(results):
|
|
223
|
+
selected = results[0]
|
|
224
|
+
needs_output = any(
|
|
225
|
+
features.get(name, {}).get("needs_output", True)
|
|
226
|
+
for name in selected
|
|
227
|
+
)
|
|
228
|
+
return ask_output_mode() if needs_output else ("overwrite", None)
|
|
215
229
|
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
230
|
+
result = run_steps([step_features, step_files, step_output])
|
|
231
|
+
if result is None:
|
|
232
|
+
console.print("[yellow]Nothing to do. Exiting.[/yellow]")
|
|
233
|
+
return
|
|
234
|
+
|
|
235
|
+
selected, files, (mode, output_dir) = result
|
|
220
236
|
|
|
221
237
|
for feature_name in selected:
|
|
222
238
|
info = features[feature_name]
|
|
223
239
|
ask_args = info.get("ask_args")
|
|
224
240
|
feature_args = ask_args(files) if ask_args else {}
|
|
225
241
|
console.print(f"\n[bold]→ {info['name']}[/bold]")
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
242
|
+
if info.get("run_batch"):
|
|
243
|
+
process_batch(
|
|
244
|
+
files=files,
|
|
245
|
+
batch_func=info["run_batch"],
|
|
246
|
+
feature_name=info["name"],
|
|
247
|
+
output_mode=mode,
|
|
248
|
+
output_name=info["output_name"],
|
|
249
|
+
output_dir=output_dir,
|
|
250
|
+
args=feature_args,
|
|
251
|
+
)
|
|
252
|
+
else:
|
|
253
|
+
process_files(
|
|
254
|
+
files=files,
|
|
255
|
+
process_func=info["run"],
|
|
256
|
+
feature_name=info["name"],
|
|
257
|
+
output_mode=mode,
|
|
258
|
+
output_dir=output_dir,
|
|
259
|
+
args=feature_args,
|
|
260
|
+
)
|
|
234
261
|
|
|
235
262
|
console.print("\n[bold green]✓ All done![/bold green]")
|
|
236
263
|
_check_version()
|
|
@@ -11,12 +11,18 @@ def _register(module):
|
|
|
11
11
|
run_func = getattr(module, "run", None)
|
|
12
12
|
ask_args_func = getattr(module, "ask_args", None)
|
|
13
13
|
needs_output = getattr(module, "NEEDS_OUTPUT_MODE", True)
|
|
14
|
+
# Batch features take every selected file at once and write one output
|
|
15
|
+
# (e.g. a multi-page PDF) instead of one output per file.
|
|
16
|
+
batch_func = getattr(module, "run_batch", None)
|
|
17
|
+
output_name = getattr(module, "OUTPUT_NAME", None)
|
|
14
18
|
|
|
15
19
|
if name and run_func:
|
|
16
20
|
REGISTRY[name] = {
|
|
17
21
|
"name": name,
|
|
18
22
|
"description": description,
|
|
19
23
|
"run": run_func,
|
|
24
|
+
"run_batch": batch_func,
|
|
25
|
+
"output_name": output_name,
|
|
20
26
|
"ask_args": ask_args_func,
|
|
21
27
|
"needs_output": needs_output,
|
|
22
28
|
"module": module.__name__,
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import re
|
|
3
|
+
import shutil
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Optional
|
|
6
|
+
|
|
7
|
+
import questionary
|
|
8
|
+
from PIL import Image
|
|
9
|
+
from rich.console import Console
|
|
10
|
+
|
|
11
|
+
NAME = "Compress / Optimize"
|
|
12
|
+
DESCRIPTION = "Reduce file size (quality slider or target size in KB)"
|
|
13
|
+
|
|
14
|
+
console = Console()
|
|
15
|
+
|
|
16
|
+
MODE_QUALITY = "Quality slider (1-100)"
|
|
17
|
+
MODE_TARGET = "Target size (e.g. under 300 KB)"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def ask_args(files: list[Path]) -> dict[str, Any]:
|
|
21
|
+
mode = questionary.select(
|
|
22
|
+
"How do you want to compress?",
|
|
23
|
+
choices=[MODE_TARGET, MODE_QUALITY],
|
|
24
|
+
).ask()
|
|
25
|
+
|
|
26
|
+
if mode == MODE_TARGET:
|
|
27
|
+
size = questionary.text(
|
|
28
|
+
"Max size per image (e.g. 300kb, 3mb, 1.5 MB; no unit = KB):",
|
|
29
|
+
default="300kb",
|
|
30
|
+
validate=lambda v: parse_size(v) is not None or "Try 300kb, 3mb or 1.5mb",
|
|
31
|
+
).ask()
|
|
32
|
+
return {"target_bytes": parse_size(size)}
|
|
33
|
+
|
|
34
|
+
quality = questionary.text(
|
|
35
|
+
"Quality (1-100):",
|
|
36
|
+
default="80",
|
|
37
|
+
validate=lambda v: v.isdigit() and 1 <= int(v) <= 100 or "Enter a number 1-100",
|
|
38
|
+
).ask()
|
|
39
|
+
|
|
40
|
+
return {"quality": max(1, min(100, int(quality)))}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def run(file: Path, output_path: Path, args: Optional[dict[str, Any]] = None) -> bool:
|
|
44
|
+
if args is None:
|
|
45
|
+
msg = "args required for compress (quality or target_bytes)"
|
|
46
|
+
raise ValueError(msg)
|
|
47
|
+
|
|
48
|
+
img = Image.open(file)
|
|
49
|
+
meta = {}
|
|
50
|
+
if exif := img.info.get("exif"):
|
|
51
|
+
meta["exif"] = exif
|
|
52
|
+
if icc := img.info.get("icc_profile"):
|
|
53
|
+
meta["icc_profile"] = icc
|
|
54
|
+
fmt = img.format
|
|
55
|
+
original_size = file.stat().st_size
|
|
56
|
+
|
|
57
|
+
target = args.get("target_bytes")
|
|
58
|
+
note = ""
|
|
59
|
+
if target and original_size <= target:
|
|
60
|
+
# Already under the target: don't re-encode (that would only lose quality).
|
|
61
|
+
if output_path.resolve() != file.resolve():
|
|
62
|
+
shutil.copyfile(file, output_path)
|
|
63
|
+
note = "already under target, left unchanged"
|
|
64
|
+
elif target:
|
|
65
|
+
note = _fit_to_target(img, output_path, fmt, meta, target)
|
|
66
|
+
else:
|
|
67
|
+
_encode(img, output_path, fmt, args.get("quality", 80), meta)
|
|
68
|
+
|
|
69
|
+
new_size = output_path.stat().st_size
|
|
70
|
+
saved = original_size - new_size
|
|
71
|
+
pct = (1 - new_size / original_size) * 100 if original_size else 0
|
|
72
|
+
console.print(
|
|
73
|
+
f" [dim]{file.name}: {_fmt_size(original_size)} → {_fmt_size(new_size)} "
|
|
74
|
+
f"({'−' if saved >= 0 else '+'}{abs(pct):.0f}%)[/dim]"
|
|
75
|
+
+ (f" [yellow]{note}[/yellow]" if note else "")
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
return True
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _encode(img: Image.Image, dest, fmt: Optional[str], quality: int, meta: dict):
|
|
82
|
+
if fmt == "JPEG":
|
|
83
|
+
_compress_jpeg(img, dest, quality, meta)
|
|
84
|
+
elif fmt == "PNG":
|
|
85
|
+
_compress_png(img, dest, quality, meta)
|
|
86
|
+
elif fmt == "WEBP":
|
|
87
|
+
_compress_webp(img, dest, quality, meta)
|
|
88
|
+
else:
|
|
89
|
+
_compress_other(img, dest, fmt, quality, meta)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _fit_to_target(
|
|
93
|
+
img: Image.Image, output_path: Path, fmt: Optional[str], meta: dict, target: int,
|
|
94
|
+
) -> str:
|
|
95
|
+
"""Write the image as small as possible while staying <= target bytes.
|
|
96
|
+
|
|
97
|
+
Lossy formats (JPEG, WEBP) get a binary search over quality, and PNG
|
|
98
|
+
falls back to palette reduction if lossless is too big. Returns a note
|
|
99
|
+
for the console if the target could not be met.
|
|
100
|
+
"""
|
|
101
|
+
if fmt in ("JPEG", "WEBP"):
|
|
102
|
+
def encode(q: int) -> bytes:
|
|
103
|
+
buf = io.BytesIO()
|
|
104
|
+
_encode(img, buf, fmt, q, meta)
|
|
105
|
+
return buf.getvalue()
|
|
106
|
+
|
|
107
|
+
data, best = _search_largest(encode, lo=1, hi=95, target=target)
|
|
108
|
+
output_path.write_bytes(data)
|
|
109
|
+
if len(data) > target:
|
|
110
|
+
return f"can't reach target, smallest possible (quality {best})"
|
|
111
|
+
return f"quality {best}"
|
|
112
|
+
|
|
113
|
+
if fmt == "PNG":
|
|
114
|
+
data = _encode_bytes(img, fmt, 100, meta)
|
|
115
|
+
if len(data) <= target:
|
|
116
|
+
output_path.write_bytes(data)
|
|
117
|
+
return ""
|
|
118
|
+
|
|
119
|
+
def encode_colors(c: int) -> bytes:
|
|
120
|
+
return _png_palette_bytes(img, c, meta)
|
|
121
|
+
|
|
122
|
+
data, colors = _search_largest(encode_colors, lo=2, hi=256, target=target)
|
|
123
|
+
output_path.write_bytes(data)
|
|
124
|
+
if len(data) > target:
|
|
125
|
+
return f"can't reach target, smallest possible ({colors} colors)"
|
|
126
|
+
return f"{colors} colors"
|
|
127
|
+
|
|
128
|
+
# BMP, GIF, TIFF, ...: no quality knob to turn.
|
|
129
|
+
_encode(img, output_path, fmt, 80, meta)
|
|
130
|
+
if output_path.stat().st_size > target:
|
|
131
|
+
return f"{fmt} has no quality setting, can't reach target"
|
|
132
|
+
return ""
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _search_largest(encode, lo: int, hi: int, target: int):
|
|
136
|
+
"""Return (bytes, param) for the largest param in [lo, hi] whose output fits.
|
|
137
|
+
|
|
138
|
+
Assumes output size grows with the parameter. If even ``lo`` is too big,
|
|
139
|
+
returns the ``lo`` encoding so the caller can still write the smallest
|
|
140
|
+
result.
|
|
141
|
+
"""
|
|
142
|
+
smallest = encode(lo)
|
|
143
|
+
if len(smallest) > target:
|
|
144
|
+
return smallest, lo
|
|
145
|
+
|
|
146
|
+
best_data, best = smallest, lo
|
|
147
|
+
while lo <= hi:
|
|
148
|
+
mid = (lo + hi) // 2
|
|
149
|
+
data = encode(mid)
|
|
150
|
+
if len(data) <= target:
|
|
151
|
+
best_data, best = data, mid
|
|
152
|
+
lo = mid + 1
|
|
153
|
+
else:
|
|
154
|
+
hi = mid - 1
|
|
155
|
+
return best_data, best
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _encode_bytes(img: Image.Image, fmt: str, quality: int, meta: dict) -> bytes:
|
|
159
|
+
buf = io.BytesIO()
|
|
160
|
+
_encode(img, buf, fmt, quality, meta)
|
|
161
|
+
return buf.getvalue()
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _png_palette_bytes(img: Image.Image, colors: int, meta: dict) -> bytes:
|
|
165
|
+
flat = _flatten(img)
|
|
166
|
+
buf = io.BytesIO()
|
|
167
|
+
flat.quantize(colors=colors, method=Image.Quantize.MEDIANCUT).save(
|
|
168
|
+
buf, format="PNG", optimize=True, **meta,
|
|
169
|
+
)
|
|
170
|
+
return buf.getvalue()
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _flatten(img: Image.Image) -> Image.Image:
|
|
174
|
+
if img.mode == "RGBA":
|
|
175
|
+
bg = Image.new("RGB", img.size, (255, 255, 255))
|
|
176
|
+
bg.paste(img, mask=img.split()[3])
|
|
177
|
+
return bg
|
|
178
|
+
if img.mode != "RGB":
|
|
179
|
+
return img.convert("RGB")
|
|
180
|
+
return img
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _compress_jpeg(img: Image.Image, dest, quality: int, meta: dict):
|
|
184
|
+
img = _flatten(img)
|
|
185
|
+
img.save(dest, format="JPEG", quality=quality, optimize=True, **meta)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _compress_png(img: Image.Image, dest, quality: int, meta: dict):
|
|
189
|
+
if quality < 50:
|
|
190
|
+
colors = max(quality * 2, 16)
|
|
191
|
+
img = _flatten(img).quantize(colors=colors, method=Image.Quantize.MEDIANCUT)
|
|
192
|
+
img.save(dest, format="PNG", optimize=True, **meta)
|
|
193
|
+
else:
|
|
194
|
+
img.save(dest, format="PNG", optimize=True, **meta)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _compress_webp(img: Image.Image, dest, quality: int, meta: dict):
|
|
198
|
+
img.save(dest, format="WEBP", quality=quality, **meta)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _compress_other(img: Image.Image, dest, fmt: Optional[str], quality: int, meta: dict):
|
|
202
|
+
params = {"format": fmt, **meta}
|
|
203
|
+
if fmt == "GIF":
|
|
204
|
+
params["save_all"] = True
|
|
205
|
+
img.save(dest, **params)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
_SIZE_UNITS = {
|
|
209
|
+
"b": 1,
|
|
210
|
+
"kb": 1024,
|
|
211
|
+
"k": 1024,
|
|
212
|
+
"mb": 1024**2,
|
|
213
|
+
"m": 1024**2,
|
|
214
|
+
"gb": 1024**3,
|
|
215
|
+
}
|
|
216
|
+
_SIZE_RE = re.compile(r"^\s*(\d+(?:\.\d+)?)\s*([a-zA-Z]*)\s*$")
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def parse_size(text: str) -> Optional[int]:
|
|
220
|
+
"""Turn '300kb', '3 MB', '1.5mb' or '300' (KB) into bytes. None if invalid."""
|
|
221
|
+
match = _SIZE_RE.match(text or "")
|
|
222
|
+
if not match:
|
|
223
|
+
return None
|
|
224
|
+
number, unit = match.groups()
|
|
225
|
+
multiplier = _SIZE_UNITS.get(unit.lower() or "kb")
|
|
226
|
+
if multiplier is None or float(number) <= 0:
|
|
227
|
+
return None
|
|
228
|
+
return int(float(number) * multiplier)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _fmt_size(size: int) -> str:
|
|
232
|
+
value = float(size)
|
|
233
|
+
for unit in ("B", "KB", "MB"):
|
|
234
|
+
if value < 1024:
|
|
235
|
+
return f"{value:.0f} {unit}"
|
|
236
|
+
value /= 1024
|
|
237
|
+
return f"{value:.1f} GB"
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import Any, Optional
|
|
3
|
+
|
|
4
|
+
from PIL import Image, ImageOps
|
|
5
|
+
|
|
6
|
+
NAME = "Convert to PDF"
|
|
7
|
+
DESCRIPTION = "Combine selected images into one PDF (one page per image)"
|
|
8
|
+
|
|
9
|
+
# Batch feature: receives every selected file at once and writes one PDF.
|
|
10
|
+
OUTPUT_NAME = "imagex_output.pdf"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def run_batch(
|
|
14
|
+
files: list[Path], output_path: Path, args: Optional[dict[str, Any]] = None,
|
|
15
|
+
) -> bool:
|
|
16
|
+
if not files:
|
|
17
|
+
msg = "no images to convert"
|
|
18
|
+
raise ValueError(msg)
|
|
19
|
+
|
|
20
|
+
pages = [_load_page(Path(f)) for f in files]
|
|
21
|
+
first, rest = pages[0], pages[1:]
|
|
22
|
+
first.save(
|
|
23
|
+
str(output_path),
|
|
24
|
+
format="PDF",
|
|
25
|
+
save_all=True,
|
|
26
|
+
append_images=rest,
|
|
27
|
+
resolution=72.0, # 1 pixel = 1 point, so each page is the full image
|
|
28
|
+
)
|
|
29
|
+
return True
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def run(file: Path, output_path: Path, args: Optional[dict[str, Any]] = None) -> bool:
|
|
33
|
+
return run_batch([file], output_path, args)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _load_page(path: Path) -> Image.Image:
|
|
37
|
+
"""Open an image as a PDF-ready page (RGB or grayscale, no alpha)."""
|
|
38
|
+
with Image.open(path) as img:
|
|
39
|
+
img = ImageOps.exif_transpose(img)
|
|
40
|
+
if img.mode in ("RGB", "L", "CMYK"):
|
|
41
|
+
return img.copy()
|
|
42
|
+
if img.mode in ("RGBA", "LA", "PA", "P"):
|
|
43
|
+
rgba = img.convert("RGBA")
|
|
44
|
+
page = Image.new("RGB", rgba.size, (255, 255, 255))
|
|
45
|
+
page.paste(rgba, mask=rgba.split()[3])
|
|
46
|
+
return page
|
|
47
|
+
return img.convert("RGB")
|
|
@@ -40,3 +40,28 @@ def get_output_path(
|
|
|
40
40
|
return output_dir / file.name
|
|
41
41
|
msg = f"Unknown output mode: {mode}"
|
|
42
42
|
raise ValueError(msg)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def get_batch_output_path(
|
|
46
|
+
files: list[Path],
|
|
47
|
+
mode: str,
|
|
48
|
+
name: str,
|
|
49
|
+
output_dir: Optional[Path] = None,
|
|
50
|
+
) -> Path:
|
|
51
|
+
"""Where a single combined output (e.g. one PDF) goes, next to the inputs."""
|
|
52
|
+
if not files:
|
|
53
|
+
msg = "no input files"
|
|
54
|
+
raise ValueError(msg)
|
|
55
|
+
if mode == "overwrite":
|
|
56
|
+
base = files[0].parent
|
|
57
|
+
elif mode == "output":
|
|
58
|
+
base = files[0].parent / "output"
|
|
59
|
+
elif mode == "custom":
|
|
60
|
+
if output_dir is None:
|
|
61
|
+
msg = "output_dir required for custom mode"
|
|
62
|
+
raise ValueError(msg)
|
|
63
|
+
base = output_dir
|
|
64
|
+
else:
|
|
65
|
+
msg = f"Unknown output mode: {mode}"
|
|
66
|
+
raise ValueError(msg)
|
|
67
|
+
return base / name
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
from pathlib import Path
|
|
2
2
|
from typing import Any, Callable, Optional
|
|
3
3
|
|
|
4
|
+
from rich.console import Console
|
|
4
5
|
from rich.progress import (
|
|
5
6
|
BarColumn,
|
|
6
7
|
Progress,
|
|
@@ -8,7 +9,7 @@ from rich.progress import (
|
|
|
8
9
|
TimeRemainingColumn,
|
|
9
10
|
)
|
|
10
11
|
|
|
11
|
-
from imagex.utils.file_ops import backup_file, get_output_path
|
|
12
|
+
from imagex.utils.file_ops import backup_file, get_batch_output_path, get_output_path
|
|
12
13
|
|
|
13
14
|
|
|
14
15
|
def process_files(
|
|
@@ -47,3 +48,25 @@ def process_files(
|
|
|
47
48
|
)
|
|
48
49
|
|
|
49
50
|
progress.advance(task)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def process_batch(
|
|
54
|
+
files: list[Path],
|
|
55
|
+
batch_func: Callable[[list[Path], Path, dict[str, Any]], bool],
|
|
56
|
+
feature_name: str,
|
|
57
|
+
output_mode: str,
|
|
58
|
+
output_name: str,
|
|
59
|
+
output_dir: Optional[Path] = None,
|
|
60
|
+
args: Optional[dict[str, Any]] = None,
|
|
61
|
+
):
|
|
62
|
+
"""Run a feature that turns all selected files into one output file."""
|
|
63
|
+
console = Console()
|
|
64
|
+
try:
|
|
65
|
+
output_path = get_batch_output_path(files, output_mode, output_name, output_dir)
|
|
66
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
67
|
+
batch_func(files, output_path, args or {})
|
|
68
|
+
console.print(
|
|
69
|
+
f" [green]✓ {feature_name}: {len(files)} image(s) → {output_path}[/green]"
|
|
70
|
+
)
|
|
71
|
+
except Exception as e:
|
|
72
|
+
console.print(f"[red]✗ {feature_name}: {e}[/red]")
|