imagex 0.1.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.
Files changed (35) hide show
  1. imagex-0.1.0/LICENSE +21 -0
  2. imagex-0.1.0/PKG-INFO +78 -0
  3. imagex-0.1.0/README.md +51 -0
  4. imagex-0.1.0/imagex/__init__.py +1 -0
  5. imagex-0.1.0/imagex/__main__.py +3 -0
  6. imagex-0.1.0/imagex/cli.py +223 -0
  7. imagex-0.1.0/imagex/config.py +13 -0
  8. imagex-0.1.0/imagex/features/__init__.py +34 -0
  9. imagex-0.1.0/imagex/features/add_noise.py +80 -0
  10. imagex-0.1.0/imagex/features/compress.py +95 -0
  11. imagex-0.1.0/imagex/features/convert.py +96 -0
  12. imagex-0.1.0/imagex/features/remove_metadata.py +48 -0
  13. imagex-0.1.0/imagex/features/rename_batch.py +64 -0
  14. imagex-0.1.0/imagex/features/resize.py +90 -0
  15. imagex-0.1.0/imagex/features/watermark.py +248 -0
  16. imagex-0.1.0/imagex/utils/__init__.py +0 -0
  17. imagex-0.1.0/imagex/utils/file_ops.py +42 -0
  18. imagex-0.1.0/imagex/utils/progress.py +49 -0
  19. imagex-0.1.0/imagex.egg-info/PKG-INFO +78 -0
  20. imagex-0.1.0/imagex.egg-info/SOURCES.txt +33 -0
  21. imagex-0.1.0/imagex.egg-info/dependency_links.txt +1 -0
  22. imagex-0.1.0/imagex.egg-info/entry_points.txt +2 -0
  23. imagex-0.1.0/imagex.egg-info/requires.txt +11 -0
  24. imagex-0.1.0/imagex.egg-info/top_level.txt +1 -0
  25. imagex-0.1.0/pyproject.toml +57 -0
  26. imagex-0.1.0/setup.cfg +4 -0
  27. imagex-0.1.0/tests/test_add_noise.py +86 -0
  28. imagex-0.1.0/tests/test_cli.py +61 -0
  29. imagex-0.1.0/tests/test_compress.py +78 -0
  30. imagex-0.1.0/tests/test_convert.py +145 -0
  31. imagex-0.1.0/tests/test_file_ops.py +90 -0
  32. imagex-0.1.0/tests/test_remove_metadata.py +65 -0
  33. imagex-0.1.0/tests/test_rename_batch.py +59 -0
  34. imagex-0.1.0/tests/test_resize.py +88 -0
  35. imagex-0.1.0/tests/test_watermark.py +182 -0
imagex-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kushal Baral
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.
imagex-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,78 @@
1
+ Metadata-Version: 2.4
2
+ Name: imagex
3
+ Version: 0.1.0
4
+ Summary: Image processing CLI tool - right in your terminal
5
+ Author: kushal1o1
6
+ License: MIT
7
+ Classifier: Development Status :: 3 - Alpha
8
+ Classifier: Environment :: Console
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.10
12
+ Classifier: Programming Language :: Python :: 3.11
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: rich>=13.0
18
+ Requires-Dist: questionary>=2.0
19
+ Requires-Dist: Pillow>=10.0
20
+ Provides-Extra: heif
21
+ Requires-Dist: pillow-heif>=0.16; extra == "heif"
22
+ Provides-Extra: dev
23
+ Requires-Dist: pytest>=7.0; extra == "dev"
24
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
25
+ Requires-Dist: pillow-heif>=0.16; extra == "dev"
26
+ Dynamic: license-file
27
+
28
+ ```
29
+ ██╗███╗ ███╗ █████╗ ██████╗ ███████╗██╗ ██╗
30
+ ██║████╗ ████║██╔══██╗██╔════╝ ██╔════╝╚██╗██╔╝
31
+ ██║██╔████╔██║███████║██║ ███╗█████╗ ╚███╔╝
32
+ ██║██║╚██╔╝██║██╔══██║██║ ██║██╔══╝ ██╔██╗
33
+ ██║██║ ╚═╝ ██║██║ ██║╚██████╔╝███████╗██╔╝ ██╗
34
+ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝
35
+ ```
36
+
37
+ Image processing CLI tool — right in your terminal.
38
+
39
+ ```bash
40
+ pip install .
41
+ imagex
42
+ ```
43
+
44
+ Navigate to any folder with images and run `imagex`.
45
+
46
+ ## Features
47
+
48
+ | Feature | Description |
49
+ |---|---|
50
+ | Remove Metadata | Strip EXIF/XMP/IPTC (incl. AI generation markers) |
51
+ | Convert Format | JPG ↔ PNG ↔ WEBP ↔ TIFF ↔ BMP ↔ GIF ↔ HEIC |
52
+ | Compress / Optimize | Reduce file size with quality slider |
53
+ | Resize | Percentage, exact dimensions, fit within bounds |
54
+ | Rename Batch | Pattern-based renaming (%n, %o) |
55
+ | Add Noise | Gaussian or salt & pepper (bypass AI detection) |
56
+ | Watermark | Add text/image or remove existing |
57
+
58
+ Full details in [OPERATIONS.md](OPERATIONS.md).
59
+
60
+ ## Install
61
+
62
+ ```bash
63
+ # From the repo directory
64
+ pip install .
65
+
66
+ # Dev mode (changes take effect immediately)
67
+ pip install -e .
68
+ ```
69
+
70
+ Then run `imagex` from any folder.
71
+
72
+ ## Adding Features
73
+
74
+ See [CONTRIBUTION.md](CONTRIBUTION.md) for the contribution guide.
75
+
76
+ ## License
77
+
78
+ MIT
imagex-0.1.0/README.md ADDED
@@ -0,0 +1,51 @@
1
+ ```
2
+ ██╗███╗ ███╗ █████╗ ██████╗ ███████╗██╗ ██╗
3
+ ██║████╗ ████║██╔══██╗██╔════╝ ██╔════╝╚██╗██╔╝
4
+ ██║██╔████╔██║███████║██║ ███╗█████╗ ╚███╔╝
5
+ ██║██║╚██╔╝██║██╔══██║██║ ██║██╔══╝ ██╔██╗
6
+ ██║██║ ╚═╝ ██║██║ ██║╚██████╔╝███████╗██╔╝ ██╗
7
+ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝
8
+ ```
9
+
10
+ Image processing CLI tool — right in your terminal.
11
+
12
+ ```bash
13
+ pip install .
14
+ imagex
15
+ ```
16
+
17
+ Navigate to any folder with images and run `imagex`.
18
+
19
+ ## Features
20
+
21
+ | Feature | Description |
22
+ |---|---|
23
+ | Remove Metadata | Strip EXIF/XMP/IPTC (incl. AI generation markers) |
24
+ | Convert Format | JPG ↔ PNG ↔ WEBP ↔ TIFF ↔ BMP ↔ GIF ↔ HEIC |
25
+ | Compress / Optimize | Reduce file size with quality slider |
26
+ | Resize | Percentage, exact dimensions, fit within bounds |
27
+ | Rename Batch | Pattern-based renaming (%n, %o) |
28
+ | Add Noise | Gaussian or salt & pepper (bypass AI detection) |
29
+ | Watermark | Add text/image or remove existing |
30
+
31
+ Full details in [OPERATIONS.md](OPERATIONS.md).
32
+
33
+ ## Install
34
+
35
+ ```bash
36
+ # From the repo directory
37
+ pip install .
38
+
39
+ # Dev mode (changes take effect immediately)
40
+ pip install -e .
41
+ ```
42
+
43
+ Then run `imagex` from any folder.
44
+
45
+ ## Adding Features
46
+
47
+ See [CONTRIBUTION.md](CONTRIBUTION.md) for the contribution guide.
48
+
49
+ ## License
50
+
51
+ MIT
@@ -0,0 +1 @@
1
+ __version__ = "0.1.1"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
@@ -0,0 +1,223 @@
1
+ import argparse
2
+ import sys
3
+ from pathlib import Path
4
+ from typing import Optional
5
+
6
+ import questionary
7
+ from rich.console import Console
8
+ from rich.panel import Panel
9
+
10
+ from imagex import __version__
11
+ from imagex.features import get_features
12
+ from imagex.utils.file_ops import find_images
13
+ from imagex.utils.progress import process_files
14
+
15
+ console = Console()
16
+
17
+ USAGE = """
18
+ Image processing CLI tool — right in your terminal.
19
+
20
+ Run without arguments to launch the interactive menu:
21
+
22
+ imagex
23
+
24
+ Features:
25
+ • Remove Metadata Strip EXIF/XMP/IPTC (incl. AI generation markers)
26
+ • Convert Format JPG ↔ PNG ↔ WEBP ↔ TIFF ↔ BMP ↔ GIF ↔ HEIC
27
+ • Compress/Optimize Reduce file size with quality slider
28
+ • Resize Percentage, exact dimensions, fit within bounds
29
+ • Rename Batch Pattern-based renaming (%%n, %%o)
30
+ • Add Noise Gaussian or salt & pepper (bypass AI detection)
31
+ • Watermark Add text/image or remove existing
32
+ """
33
+
34
+
35
+ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace:
36
+ parser = argparse.ArgumentParser(
37
+ prog="imagex",
38
+ description="Image processing CLI tool — right in your terminal",
39
+ formatter_class=argparse.RawDescriptionHelpFormatter,
40
+ epilog="Run without arguments to launch the interactive menu.",
41
+ )
42
+ parser.add_argument(
43
+ "--version",
44
+ action="version",
45
+ version=f"imagex v{__version__}",
46
+ )
47
+ return parser.parse_args(argv)
48
+
49
+
50
+ def fmt_size(size: int) -> str:
51
+ for unit in ("B", "KB", "MB"):
52
+ if size < 1024:
53
+ return f"{size:.0f} {unit}"
54
+ size /= 1024
55
+ return f"{size:.1f} GB"
56
+
57
+
58
+ def show_banner():
59
+ art = """[bold cyan]
60
+ ██╗███╗ ███╗ █████╗ ██████╗ ███████╗██╗ ██╗
61
+ ██║████╗ ████║██╔══██╗██╔════╝ ██╔════╝╚██╗██╔╝
62
+ ██║██╔████╔██║███████║██║ ███╗█████╗ ╚███╔╝
63
+ ██║██║╚██╔╝██║██╔══██║██║ ██║██╔══╝ ██╔██╗
64
+ ██║██║ ╚═╝ ██║██║ ██║╚██████╔╝███████╗██╔╝ ██╗
65
+ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝
66
+ [/bold cyan]"""
67
+
68
+ text = (
69
+ f"{art}"
70
+ f"[white]v{__version__}[/white]\n"
71
+ "[dim]Image processing, right in ur CLI[/dim]"
72
+ )
73
+ console.print(Panel(text, width=60))
74
+
75
+
76
+ def select_features() -> Optional[list[str]]:
77
+ features = get_features()
78
+
79
+ if not features:
80
+ console.print("[red]No features found! Add a .py file to imagex/features/.[/red]")
81
+ return None
82
+
83
+ choices = []
84
+ for name, info in features.items():
85
+ label = f"{info['name']:<30} {info['description']}"
86
+ choices.append(questionary.Choice(title=label, value=name))
87
+
88
+ choices.append(questionary.Choice(title="[Done] Quit", value="__quit__"))
89
+
90
+ selected = questionary.checkbox(
91
+ "What do you want to do? (↑↓ to move, Space to toggle, Enter to confirm)",
92
+ choices=choices,
93
+ ).ask()
94
+
95
+ if not selected:
96
+ return None
97
+
98
+ if "__quit__" in selected:
99
+ return None
100
+
101
+ return selected
102
+
103
+
104
+ def ask_output_mode() -> tuple[str, Optional[Path]]:
105
+ mode = questionary.select(
106
+ "Where should the processed images go?",
107
+ choices=[
108
+ questionary.Choice(
109
+ title="Overwrite originals (backup created in .imagex_backup/)",
110
+ value="overwrite",
111
+ ),
112
+ questionary.Choice(
113
+ title="Save to ./output/ folder",
114
+ value="output",
115
+ ),
116
+ questionary.Choice(
117
+ title="Save to custom folder",
118
+ value="custom",
119
+ ),
120
+ ],
121
+ ).ask()
122
+
123
+ output_dir = None
124
+ if mode == "custom":
125
+ custom = questionary.text(
126
+ "Enter output folder path:",
127
+ validate=lambda p: len(p.strip()) > 0 or "Path cannot be empty",
128
+ ).ask()
129
+ output_dir = Path(custom.strip())
130
+
131
+ return mode, output_dir
132
+
133
+
134
+ def select_files(all_files: list[Path]) -> Optional[list[Path]]:
135
+ if not all_files:
136
+ return None
137
+
138
+ if len(all_files) == 1:
139
+ return all_files
140
+
141
+ all_choice = questionary.Choice(
142
+ title=f"All images ({len(all_files)} files)",
143
+ value="__all__",
144
+ )
145
+
146
+ file_choices = []
147
+ for f in all_files:
148
+ size_str = fmt_size(f.stat().st_size)
149
+ label = f"{f.name:<50} {size_str:>8}"
150
+ file_choices.append(questionary.Choice(title=label, value=str(f)))
151
+
152
+ selected = questionary.checkbox(
153
+ "Which images to process? (Space to toggle, Enter to confirm)",
154
+ choices=[all_choice] + file_choices,
155
+ ).ask()
156
+
157
+ if not selected:
158
+ return None
159
+
160
+ if "__all__" in selected:
161
+ return all_files
162
+
163
+ return [Path(f) for f in selected]
164
+
165
+
166
+ def main():
167
+ _parse_args()
168
+
169
+ try:
170
+ show_banner()
171
+
172
+ selected = select_features()
173
+ if selected is None:
174
+ console.print("[yellow]No feature selected. Exiting.[/yellow]")
175
+ return
176
+
177
+ all_files = find_images(Path.cwd())
178
+ if not all_files:
179
+ console.print("[red]No image files found in current directory.[/red]")
180
+ console.print("[dim]Supported: .jpg .jpeg .png .webp .tiff .tif .bmp .gif .ico[/dim]")
181
+ return
182
+
183
+ files = select_files(all_files)
184
+ if not files:
185
+ console.print("[yellow]No files selected. Exiting.[/yellow]")
186
+ return
187
+
188
+ console.print(f"[green]Selected {len(files)} image(s)[/green]")
189
+
190
+ features = get_features()
191
+ any_needs_output = any(
192
+ info.get("needs_output", True)
193
+ for name, info in features.items()
194
+ if name in selected
195
+ )
196
+
197
+ if any_needs_output:
198
+ mode, output_dir = ask_output_mode()
199
+ else:
200
+ mode, output_dir = "overwrite", None
201
+
202
+ for feature_name in selected:
203
+ info = features[feature_name]
204
+ ask_args = info.get("ask_args")
205
+ feature_args = ask_args(files) if ask_args else {}
206
+ console.print(f"\n[bold]→ {info['name']}[/bold]")
207
+ process_files(
208
+ files=files,
209
+ process_func=info["run"],
210
+ feature_name=info["name"],
211
+ output_mode=mode,
212
+ output_dir=output_dir,
213
+ args=feature_args,
214
+ )
215
+
216
+ console.print("\n[bold green]✓ All done![/bold green]")
217
+
218
+ except KeyboardInterrupt:
219
+ console.print("\n[yellow]Interrupted. Exiting.[/yellow]")
220
+ sys.exit(0)
221
+ except Exception as e:
222
+ console.print(f"\n[red]Error: {e}[/red]")
223
+ sys.exit(1)
@@ -0,0 +1,13 @@
1
+ from pathlib import Path
2
+
3
+ IMAGE_EXTENSIONS = {
4
+ ".jpg", ".jpeg", ".png", ".webp",
5
+ ".tiff", ".tif", ".bmp", ".gif", ".ico",
6
+ }
7
+
8
+ BACKUP_DIR_NAME = ".imagex_backup"
9
+ DEFAULT_OUTPUT_DIR_NAME = "output"
10
+
11
+
12
+ def is_image(file: Path) -> bool:
13
+ return file.suffix.lower() in IMAGE_EXTENSIONS
@@ -0,0 +1,34 @@
1
+ import importlib
2
+ import pkgutil
3
+ from pathlib import Path
4
+
5
+ REGISTRY: dict[str, dict] = {}
6
+
7
+
8
+ def _register(module):
9
+ name = getattr(module, "NAME", None)
10
+ description = getattr(module, "DESCRIPTION", "")
11
+ run_func = getattr(module, "run", None)
12
+ ask_args_func = getattr(module, "ask_args", None)
13
+ needs_output = getattr(module, "NEEDS_OUTPUT_MODE", True)
14
+
15
+ if name and run_func:
16
+ REGISTRY[name] = {
17
+ "name": name,
18
+ "description": description,
19
+ "run": run_func,
20
+ "ask_args": ask_args_func,
21
+ "needs_output": needs_output,
22
+ "module": module.__name__,
23
+ }
24
+
25
+
26
+ _features_dir = Path(__file__).parent
27
+ for _finder, _name, _ispkg in pkgutil.iter_modules([str(_features_dir)]):
28
+ if _name != "__init__":
29
+ _module = importlib.import_module(f".{_name}", __package__)
30
+ _register(_module)
31
+
32
+
33
+ def get_features() -> dict[str, dict]:
34
+ return dict(REGISTRY)
@@ -0,0 +1,80 @@
1
+ import random
2
+ from pathlib import Path
3
+ from typing import Any, Optional
4
+
5
+ import questionary
6
+ from PIL import Image
7
+
8
+ NAME = "Add Noise"
9
+ DESCRIPTION = "Add subtle pixel noise (helps bypass AI detection)"
10
+
11
+
12
+ def ask_args(files: list[Path]) -> dict[str, Any]:
13
+ intensity_val = questionary.text(
14
+ "Noise intensity (1-100, higher = more visible):",
15
+ default="5",
16
+ validate=lambda v: v.isdigit() and 1 <= int(v) <= 100 or "Enter 1-100",
17
+ ).ask()
18
+
19
+ noise_type = questionary.select(
20
+ "Noise type:",
21
+ choices=[
22
+ "Gaussian (subtle, uniform)",
23
+ "Salt & Pepper (random pixels)",
24
+ ],
25
+ ).ask()
26
+
27
+ return {
28
+ "intensity": int(intensity_val),
29
+ "noise_type": "gaussian" if "Gaussian" in noise_type else "salt_pepper",
30
+ }
31
+
32
+
33
+ def run(file: Path, output_path: Path, args: Optional[dict[str, Any]] = None) -> bool:
34
+ if args is None:
35
+ msg = "args required for add_noise"
36
+ raise ValueError(msg)
37
+
38
+ intensity = args["intensity"]
39
+ noise_type = args.get("noise_type", "gaussian")
40
+ img = Image.open(file)
41
+
42
+ if noise_type == "gaussian":
43
+ _add_gaussian_noise(img, intensity)
44
+ else:
45
+ _add_salt_pepper(img, intensity)
46
+
47
+ img.save(str(output_path), format=img.format or "JPEG")
48
+ return True
49
+
50
+
51
+ def _add_gaussian_noise(img: Image.Image, intensity: int):
52
+ pixels = img.load()
53
+ w, h = img.size
54
+ scale = intensity / 100
55
+ noise_range = int(scale * 60)
56
+ num_pixels = int(w * h * scale * 0.8)
57
+
58
+ for _ in range(num_pixels):
59
+ x = random.randint(0, w - 1)
60
+ y = random.randint(0, h - 1)
61
+ px = list(pixels[x, y])
62
+ for c in range(min(len(px), 3)):
63
+ px[c] = max(0, min(255, px[c] + random.randint(-noise_range, noise_range)))
64
+ pixels[x, y] = tuple(px)
65
+
66
+
67
+ def _add_salt_pepper(img: Image.Image, intensity: int):
68
+ pixels = img.load()
69
+ w, h = img.size
70
+ scale = intensity / 100
71
+ num_pixels = int(w * h * scale * 0.3)
72
+
73
+ for _ in range(num_pixels):
74
+ x = random.randint(0, w - 1)
75
+ y = random.randint(0, h - 1)
76
+ px = list(pixels[x, y])
77
+ val = 255 if random.random() < 0.5 else 0
78
+ for c in range(min(len(px), 3)):
79
+ px[c] = val
80
+ pixels[x, y] = tuple(px)
@@ -0,0 +1,95 @@
1
+ from pathlib import Path
2
+ from typing import Any, Optional
3
+
4
+ import questionary
5
+ from PIL import Image
6
+ from rich.console import Console
7
+
8
+ NAME = "Compress / Optimize"
9
+ DESCRIPTION = "Reduce file size (quality slider, optimization)"
10
+
11
+ console = Console()
12
+
13
+
14
+ def ask_args(files: list[Path]) -> dict[str, Any]:
15
+ quality = questionary.text(
16
+ "Quality (1-100):",
17
+ default="80",
18
+ validate=lambda v: v.isdigit() and 1 <= int(v) <= 100 or "Enter a number 1-100",
19
+ ).ask()
20
+
21
+ return {"quality": max(1, min(100, int(quality)))}
22
+
23
+
24
+ def run(file: Path, output_path: Path, args: Optional[dict[str, Any]] = None) -> bool:
25
+ if args is None:
26
+ msg = "args required for compress (quality)"
27
+ raise ValueError(msg)
28
+
29
+ quality = args.get("quality", 80)
30
+ img = Image.open(file)
31
+ fmt = img.format
32
+ original_size = file.stat().st_size
33
+
34
+ if fmt == "JPEG":
35
+ _compress_jpeg(img, output_path, quality)
36
+ elif fmt == "PNG":
37
+ _compress_png(img, output_path, quality)
38
+ elif fmt == "WEBP":
39
+ _compress_webp(img, output_path, quality)
40
+ else:
41
+ _compress_other(img, output_path, fmt, quality)
42
+
43
+ new_size = output_path.stat().st_size
44
+ saved = original_size - new_size
45
+ pct = (1 - new_size / original_size) * 100 if original_size else 0
46
+ console.print(
47
+ f" [dim]{file.name}: {_fmt_size(original_size)} → {_fmt_size(new_size)} "
48
+ f"({'−' if saved >= 0 else '+'}{abs(pct):.0f}%)[/dim]"
49
+ )
50
+
51
+ return True
52
+
53
+
54
+ def _compress_jpeg(img: Image.Image, output_path: Path, quality: int):
55
+ if img.mode == "RGBA":
56
+ bg = Image.new("RGB", img.size, (255, 255, 255))
57
+ bg.paste(img, mask=img.split()[3])
58
+ img = bg
59
+ elif img.mode != "RGB":
60
+ img = img.convert("RGB")
61
+ img.save(str(output_path), format="JPEG", quality=quality, optimize=True)
62
+
63
+
64
+ def _compress_png(img: Image.Image, output_path: Path, quality: int):
65
+ if quality < 50:
66
+ if img.mode == "RGBA":
67
+ bg = Image.new("RGB", img.size, (255, 255, 255))
68
+ bg.paste(img, mask=img.split()[3])
69
+ img = bg
70
+ elif img.mode != "RGB":
71
+ img = img.convert("RGB")
72
+ colors = max(quality * 2, 16)
73
+ img = img.quantize(colors=colors, method=Image.Quantize.MEDIANCUT)
74
+ img.save(str(output_path), format="PNG", optimize=True)
75
+ else:
76
+ img.save(str(output_path), format="PNG", optimize=True)
77
+
78
+
79
+ def _compress_webp(img: Image.Image, output_path: Path, quality: int):
80
+ img.save(str(output_path), format="WEBP", quality=quality)
81
+
82
+
83
+ def _compress_other(img: Image.Image, output_path: Path, fmt: str, quality: int):
84
+ params = {"format": fmt}
85
+ if fmt == "GIF":
86
+ params["save_all"] = True
87
+ img.save(str(output_path), **params)
88
+
89
+
90
+ def _fmt_size(size: int) -> str:
91
+ for unit in ("B", "KB", "MB"):
92
+ if size < 1024:
93
+ return f"{size:.0f} {unit}"
94
+ size /= 1024
95
+ return f"{size:.1f} GB"