imagex 0.1.0__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.
- imagex/__init__.py +1 -0
- imagex/__main__.py +3 -0
- imagex/cli.py +223 -0
- imagex/config.py +13 -0
- imagex/features/__init__.py +34 -0
- imagex/features/add_noise.py +80 -0
- imagex/features/compress.py +95 -0
- imagex/features/convert.py +96 -0
- imagex/features/remove_metadata.py +48 -0
- imagex/features/rename_batch.py +64 -0
- imagex/features/resize.py +90 -0
- imagex/features/watermark.py +248 -0
- imagex/utils/__init__.py +0 -0
- imagex/utils/file_ops.py +42 -0
- imagex/utils/progress.py +49 -0
- imagex-0.1.0.dist-info/METADATA +78 -0
- imagex-0.1.0.dist-info/RECORD +21 -0
- imagex-0.1.0.dist-info/WHEEL +5 -0
- imagex-0.1.0.dist-info/entry_points.txt +2 -0
- imagex-0.1.0.dist-info/licenses/LICENSE +21 -0
- imagex-0.1.0.dist-info/top_level.txt +1 -0
imagex/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.1"
|
imagex/__main__.py
ADDED
imagex/cli.py
ADDED
|
@@ -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)
|
imagex/config.py
ADDED
|
@@ -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"
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import Any, Optional
|
|
3
|
+
|
|
4
|
+
import questionary
|
|
5
|
+
from PIL import Image
|
|
6
|
+
|
|
7
|
+
NAME = "Convert Format"
|
|
8
|
+
DESCRIPTION = "Convert images between formats"
|
|
9
|
+
|
|
10
|
+
OUTPUT_FORMATS = {
|
|
11
|
+
"JPEG": ".jpg",
|
|
12
|
+
"PNG": ".png",
|
|
13
|
+
"WEBP": ".webp",
|
|
14
|
+
"TIFF": ".tiff",
|
|
15
|
+
"BMP": ".bmp",
|
|
16
|
+
"GIF": ".gif",
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
HEIF_AVAILABLE = False
|
|
20
|
+
try:
|
|
21
|
+
import pillow_heif # noqa: F401
|
|
22
|
+
|
|
23
|
+
pillow_heif.register_heif_opener()
|
|
24
|
+
HEIF_AVAILABLE = True
|
|
25
|
+
OUTPUT_FORMATS["HEIC"] = ".heic"
|
|
26
|
+
except ImportError:
|
|
27
|
+
pass
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def ask_args(files: list[Path]) -> dict[str, Any]:
|
|
31
|
+
choices = list(OUTPUT_FORMATS.keys())
|
|
32
|
+
target = questionary.select(
|
|
33
|
+
"Convert to which format?",
|
|
34
|
+
choices=choices,
|
|
35
|
+
).ask()
|
|
36
|
+
|
|
37
|
+
return {
|
|
38
|
+
"target_format": target,
|
|
39
|
+
"target_ext": OUTPUT_FORMATS[target],
|
|
40
|
+
}
|
|
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 convert (target_format)"
|
|
46
|
+
raise ValueError(msg)
|
|
47
|
+
|
|
48
|
+
target_fmt = args["target_format"]
|
|
49
|
+
|
|
50
|
+
img = Image.open(file)
|
|
51
|
+
actual_output = output_path.with_suffix(args["target_ext"])
|
|
52
|
+
|
|
53
|
+
if target_fmt == "JPEG":
|
|
54
|
+
_save_as_jpeg(img, actual_output)
|
|
55
|
+
elif target_fmt == "PNG":
|
|
56
|
+
_save_as_png(img, actual_output)
|
|
57
|
+
elif target_fmt == "WEBP":
|
|
58
|
+
_save_as_webp(img, actual_output)
|
|
59
|
+
elif target_fmt == "TIFF":
|
|
60
|
+
img.save(str(actual_output), format="TIFF")
|
|
61
|
+
elif target_fmt == "BMP":
|
|
62
|
+
img.save(str(actual_output), format="BMP")
|
|
63
|
+
elif target_fmt == "GIF":
|
|
64
|
+
img.save(str(actual_output), format="GIF")
|
|
65
|
+
elif target_fmt == "HEIC":
|
|
66
|
+
_save_as_heic(img, actual_output)
|
|
67
|
+
|
|
68
|
+
return True
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _save_as_jpeg(img: Image.Image, output_path: Path):
|
|
72
|
+
if img.mode == "RGBA":
|
|
73
|
+
bg = Image.new("RGB", img.size, (255, 255, 255))
|
|
74
|
+
bg.paste(img, mask=img.split()[3])
|
|
75
|
+
img = bg
|
|
76
|
+
elif img.mode != "RGB":
|
|
77
|
+
img = img.convert("RGB")
|
|
78
|
+
img.save(str(output_path), format="JPEG")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _save_as_png(img: Image.Image, output_path: Path):
|
|
82
|
+
img.save(str(output_path), format="PNG")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _save_as_webp(img: Image.Image, output_path: Path):
|
|
86
|
+
img.save(str(output_path), format="WEBP")
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _save_as_heic(img: Image.Image, output_path: Path):
|
|
90
|
+
if not HEIF_AVAILABLE:
|
|
91
|
+
msg = (
|
|
92
|
+
"HEIC support requires pillow-heif.\n"
|
|
93
|
+
"Install with: pip install pillow-heif"
|
|
94
|
+
)
|
|
95
|
+
raise ImportError(msg)
|
|
96
|
+
img.save(str(output_path), format="HEIF")
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import Any, Optional
|
|
3
|
+
|
|
4
|
+
from PIL import Image
|
|
5
|
+
|
|
6
|
+
NAME = "Remove Metadata"
|
|
7
|
+
DESCRIPTION = "Strip EXIF/XMP/IPTC data from images"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def run(file: Path, output_path: Path, args: Optional[dict[str, Any]] = None) -> bool:
|
|
11
|
+
img = Image.open(file)
|
|
12
|
+
fmt = img.format
|
|
13
|
+
|
|
14
|
+
if fmt == "JPEG":
|
|
15
|
+
_clean_jpeg(img, output_path)
|
|
16
|
+
elif fmt == "PNG":
|
|
17
|
+
_clean_png(img, output_path)
|
|
18
|
+
elif fmt == "WEBP":
|
|
19
|
+
_clean_webp(img, output_path)
|
|
20
|
+
elif fmt == "TIFF" or fmt == "TIF":
|
|
21
|
+
_clean_tiff(img, output_path)
|
|
22
|
+
else:
|
|
23
|
+
_save_clean(img, output_path, fmt)
|
|
24
|
+
|
|
25
|
+
return True
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _clean_jpeg(img: Image.Image, output_path: Path):
|
|
29
|
+
img.save(str(output_path), format="JPEG", exif=b"")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _clean_png(img: Image.Image, output_path: Path):
|
|
33
|
+
img.save(str(output_path), format="PNG")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _clean_webp(img: Image.Image, output_path: Path):
|
|
37
|
+
img.save(str(output_path), format="WEBP")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _clean_tiff(img: Image.Image, output_path: Path):
|
|
41
|
+
img.save(str(output_path), format="TIFF")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _save_clean(img: Image.Image, output_path: Path, fmt: str):
|
|
45
|
+
params = {}
|
|
46
|
+
if fmt == "GIF":
|
|
47
|
+
params["save_all"] = True
|
|
48
|
+
img.save(str(output_path), format=fmt, **params)
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import shutil
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Any, Optional
|
|
4
|
+
|
|
5
|
+
import questionary
|
|
6
|
+
from rich.console import Console
|
|
7
|
+
|
|
8
|
+
NAME = "Rename Batch"
|
|
9
|
+
DESCRIPTION = "Rename multiple files with a pattern"
|
|
10
|
+
NEEDS_OUTPUT_MODE = False
|
|
11
|
+
|
|
12
|
+
console = Console()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def ask_args(files: list[Path]) -> dict[str, Any]:
|
|
16
|
+
sorted_files = sorted(files)
|
|
17
|
+
|
|
18
|
+
pattern = questionary.text(
|
|
19
|
+
"Pattern (use %n for number, %o for original name):",
|
|
20
|
+
default="img_%n",
|
|
21
|
+
).ask()
|
|
22
|
+
|
|
23
|
+
start_str = questionary.text("Starting number:", default="1").ask()
|
|
24
|
+
|
|
25
|
+
digits_str = questionary.text("Digit padding (e.g. 3 = 001):", default="3").ask()
|
|
26
|
+
|
|
27
|
+
start = int(start_str)
|
|
28
|
+
digits = int(digits_str)
|
|
29
|
+
|
|
30
|
+
rename_map = {}
|
|
31
|
+
for i, f in enumerate(sorted_files):
|
|
32
|
+
new_stem = pattern.replace("%n", str(start + i).zfill(digits))
|
|
33
|
+
new_stem = new_stem.replace("%o", f.stem)
|
|
34
|
+
new_name = new_stem + f.suffix
|
|
35
|
+
rename_map[str(f)] = new_name
|
|
36
|
+
|
|
37
|
+
console.print("\n[bold]Preview:[/bold]")
|
|
38
|
+
for f in sorted_files:
|
|
39
|
+
console.print(f" {f.name} → [green]{rename_map[str(f)]}[/green]")
|
|
40
|
+
|
|
41
|
+
confirm = questionary.confirm("Proceed with rename?").ask()
|
|
42
|
+
if not confirm:
|
|
43
|
+
msg = "Cancelled by user"
|
|
44
|
+
raise RuntimeError(msg)
|
|
45
|
+
|
|
46
|
+
return {
|
|
47
|
+
"rename_map": rename_map,
|
|
48
|
+
"sorted_files": [str(f) for f in sorted_files],
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def run(file: Path, output_path: Path, args: Optional[dict[str, Any]] = None) -> bool:
|
|
53
|
+
if args is None:
|
|
54
|
+
msg = "args required for rename (rename_map)"
|
|
55
|
+
raise ValueError(msg)
|
|
56
|
+
|
|
57
|
+
new_name = args["rename_map"][str(file)]
|
|
58
|
+
new_path = file.parent / new_name
|
|
59
|
+
|
|
60
|
+
if file.name != new_name:
|
|
61
|
+
shutil.move(str(file), str(new_path))
|
|
62
|
+
console.print(f" [dim]{file.name} → {new_name}[/dim]")
|
|
63
|
+
|
|
64
|
+
return True
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import Any, Optional
|
|
3
|
+
|
|
4
|
+
import questionary
|
|
5
|
+
from PIL import Image
|
|
6
|
+
|
|
7
|
+
NAME = "Resize"
|
|
8
|
+
DESCRIPTION = "Scale images (dimensions, percentage, or fit within bounds)"
|
|
9
|
+
|
|
10
|
+
METHODS = {
|
|
11
|
+
"Percentage": "percentage",
|
|
12
|
+
"Exact dimensions": "exact",
|
|
13
|
+
"Fit within (maintain ratio)": "fit",
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def ask_args(files: list[Path]) -> dict[str, Any]:
|
|
18
|
+
method_label = questionary.select(
|
|
19
|
+
"Resize method:",
|
|
20
|
+
choices=list(METHODS.keys()),
|
|
21
|
+
).ask()
|
|
22
|
+
|
|
23
|
+
method = METHODS[method_label]
|
|
24
|
+
|
|
25
|
+
if method == "percentage":
|
|
26
|
+
pct = questionary.text(
|
|
27
|
+
"Percentage of original (e.g. 50 for half size):",
|
|
28
|
+
default="50",
|
|
29
|
+
validate=lambda v: v.isdigit() and int(v) > 0 or "Enter a positive number",
|
|
30
|
+
).ask()
|
|
31
|
+
return {"method": "percentage", "value": int(pct)}
|
|
32
|
+
|
|
33
|
+
if method == "exact":
|
|
34
|
+
w = questionary.text(
|
|
35
|
+
"Width (px):",
|
|
36
|
+
validate=lambda v: v.isdigit() and int(v) > 0 or "Enter a positive number",
|
|
37
|
+
).ask()
|
|
38
|
+
h = questionary.text(
|
|
39
|
+
"Height (px):",
|
|
40
|
+
validate=lambda v: v.isdigit() and int(v) > 0 or "Enter a positive number",
|
|
41
|
+
).ask()
|
|
42
|
+
return {"method": "exact", "width": int(w), "height": int(h)}
|
|
43
|
+
|
|
44
|
+
if method == "fit":
|
|
45
|
+
mw = questionary.text(
|
|
46
|
+
"Max width (px):",
|
|
47
|
+
validate=lambda v: v.isdigit() and int(v) > 0 or "Enter a positive number",
|
|
48
|
+
).ask()
|
|
49
|
+
mh = questionary.text(
|
|
50
|
+
"Max height (px):",
|
|
51
|
+
validate=lambda v: v.isdigit() and int(v) > 0 or "Enter a positive number",
|
|
52
|
+
).ask()
|
|
53
|
+
return {"method": "fit", "max_width": int(mw), "max_height": int(mh)}
|
|
54
|
+
|
|
55
|
+
msg = f"Unknown method: {method}"
|
|
56
|
+
raise ValueError(msg)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def run(file: Path, output_path: Path, args: Optional[dict[str, Any]] = None) -> bool:
|
|
60
|
+
if args is None:
|
|
61
|
+
msg = "args required for resize"
|
|
62
|
+
raise ValueError(msg)
|
|
63
|
+
|
|
64
|
+
img = Image.open(file)
|
|
65
|
+
method = args["method"]
|
|
66
|
+
|
|
67
|
+
if method == "percentage":
|
|
68
|
+
pct = args["value"] / 100
|
|
69
|
+
new_w = max(1, int(img.width * pct))
|
|
70
|
+
new_h = max(1, int(img.height * pct))
|
|
71
|
+
elif method == "exact":
|
|
72
|
+
new_w = args["width"]
|
|
73
|
+
new_h = args["height"]
|
|
74
|
+
elif method == "fit":
|
|
75
|
+
new_w, new_h = _fit_within(img.width, img.height, args["max_width"], args["max_height"])
|
|
76
|
+
else:
|
|
77
|
+
msg = f"Unknown method: {method}"
|
|
78
|
+
raise ValueError(msg)
|
|
79
|
+
|
|
80
|
+
resized = img.resize((new_w, new_h), Image.LANCZOS)
|
|
81
|
+
resized.save(str(output_path), format=img.format or "JPEG")
|
|
82
|
+
|
|
83
|
+
return True
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _fit_within(orig_w: int, orig_h: int, max_w: int, max_h: int) -> tuple[int, int]:
|
|
87
|
+
ratio = min(max_w / orig_w, max_h / orig_h)
|
|
88
|
+
if ratio >= 1:
|
|
89
|
+
return orig_w, orig_h
|
|
90
|
+
return max(1, int(orig_w * ratio)), max(1, int(orig_h * ratio))
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import Any, Optional
|
|
3
|
+
|
|
4
|
+
import questionary
|
|
5
|
+
from PIL import Image, ImageDraw, ImageFilter, ImageFont
|
|
6
|
+
|
|
7
|
+
from imagex.config import is_image
|
|
8
|
+
|
|
9
|
+
NAME = "Watermark"
|
|
10
|
+
DESCRIPTION = "Add or remove watermarks from images"
|
|
11
|
+
|
|
12
|
+
FONT_PATHS = [
|
|
13
|
+
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
|
14
|
+
"/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
|
|
15
|
+
"/System/Library/Fonts/Helvetica.ttc",
|
|
16
|
+
"C:\\Windows\\Fonts\\Arial.ttf",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
POSITIONS = [
|
|
20
|
+
"Top-Left",
|
|
21
|
+
"Top-Right",
|
|
22
|
+
"Bottom-Left",
|
|
23
|
+
"Bottom-Right",
|
|
24
|
+
"Center",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
REMOVE_SIZES = ["Small (10%)", "Medium (20%)", "Large (30%)"]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def ask_args(files: list[Path]) -> dict[str, Any]:
|
|
31
|
+
action = questionary.select(
|
|
32
|
+
"Watermark action:",
|
|
33
|
+
choices=["Add watermark", "Remove watermark"],
|
|
34
|
+
).ask()
|
|
35
|
+
|
|
36
|
+
if action == "Add watermark":
|
|
37
|
+
return _ask_add(files)
|
|
38
|
+
|
|
39
|
+
return _ask_remove(files)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _ask_add(files: list[Path]) -> dict[str, Any]:
|
|
43
|
+
wm_type = questionary.select(
|
|
44
|
+
"Watermark type:",
|
|
45
|
+
choices=["Text", "Image (logo)"],
|
|
46
|
+
).ask()
|
|
47
|
+
|
|
48
|
+
position = questionary.select(
|
|
49
|
+
"Position:",
|
|
50
|
+
choices=POSITIONS,
|
|
51
|
+
).ask()
|
|
52
|
+
|
|
53
|
+
opacity_str = questionary.text(
|
|
54
|
+
"Opacity (1-100):",
|
|
55
|
+
default="50",
|
|
56
|
+
validate=lambda v: v.isdigit() and 1 <= int(v) <= 100 or "Enter 1-100",
|
|
57
|
+
).ask()
|
|
58
|
+
|
|
59
|
+
args = {
|
|
60
|
+
"action": "add",
|
|
61
|
+
"type": "text" if wm_type == "Text" else "image",
|
|
62
|
+
"position": position,
|
|
63
|
+
"opacity": max(0, min(255, int(int(opacity_str) * 2.55))),
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if args["type"] == "text":
|
|
67
|
+
text = questionary.text("Text content:", default="©").ask()
|
|
68
|
+
size_str = questionary.text(
|
|
69
|
+
"Font size (px):",
|
|
70
|
+
default="36",
|
|
71
|
+
validate=lambda v: v.isdigit() and int(v) > 0 or "Enter a number",
|
|
72
|
+
).ask()
|
|
73
|
+
color = questionary.text("Color (name or hex):", default="white").ask()
|
|
74
|
+
|
|
75
|
+
args["text"] = text
|
|
76
|
+
args["font_size"] = int(size_str)
|
|
77
|
+
args["color"] = color
|
|
78
|
+
else:
|
|
79
|
+
logo_input = questionary.text("Logo file path:").ask()
|
|
80
|
+
logo_path = Path(logo_input.strip())
|
|
81
|
+
|
|
82
|
+
if not logo_path.exists():
|
|
83
|
+
msg = f"Logo file not found: {logo_path}"
|
|
84
|
+
raise FileNotFoundError(msg)
|
|
85
|
+
if not is_image(logo_path):
|
|
86
|
+
msg = f"Not an image file: {logo_path}"
|
|
87
|
+
raise ValueError(msg)
|
|
88
|
+
|
|
89
|
+
scale_str = questionary.text(
|
|
90
|
+
"Logo scale (% of image width):",
|
|
91
|
+
default="10",
|
|
92
|
+
validate=lambda v: v.isdigit() and int(v) > 0 or "Enter a number",
|
|
93
|
+
).ask()
|
|
94
|
+
|
|
95
|
+
args["logo_path"] = str(logo_path)
|
|
96
|
+
args["scale"] = int(scale_str)
|
|
97
|
+
|
|
98
|
+
return args
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _ask_remove(files: list[Path]) -> dict[str, Any]:
|
|
102
|
+
position = questionary.select(
|
|
103
|
+
"Watermark position:",
|
|
104
|
+
choices=POSITIONS,
|
|
105
|
+
).ask()
|
|
106
|
+
|
|
107
|
+
size_choice = questionary.select(
|
|
108
|
+
"Watermark size:",
|
|
109
|
+
choices=REMOVE_SIZES,
|
|
110
|
+
).ask()
|
|
111
|
+
|
|
112
|
+
size_map = {"Small (10%)": 0.1, "Medium (20%)": 0.2, "Large (30%)": 0.3}
|
|
113
|
+
|
|
114
|
+
return {
|
|
115
|
+
"action": "remove",
|
|
116
|
+
"position": position,
|
|
117
|
+
"size_ratio": size_map[size_choice],
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def run(file: Path, output_path: Path, args: Optional[dict[str, Any]] = None) -> bool:
|
|
122
|
+
if args is None:
|
|
123
|
+
msg = "args required for watermark"
|
|
124
|
+
raise ValueError(msg)
|
|
125
|
+
|
|
126
|
+
img = Image.open(file).convert("RGBA")
|
|
127
|
+
action = args["action"]
|
|
128
|
+
|
|
129
|
+
if action == "add":
|
|
130
|
+
_run_add(img, args)
|
|
131
|
+
elif action == "remove":
|
|
132
|
+
_run_remove(img, args)
|
|
133
|
+
else:
|
|
134
|
+
msg = f"Unknown action: {action}"
|
|
135
|
+
raise ValueError(msg)
|
|
136
|
+
|
|
137
|
+
out = img.convert("RGB") if img.mode == "RGBA" else img
|
|
138
|
+
out.save(str(output_path))
|
|
139
|
+
return True
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _run_add(img: Image.Image, args: dict[str, Any]):
|
|
143
|
+
wm_type = args["type"]
|
|
144
|
+
position = args["position"]
|
|
145
|
+
opacity = args["opacity"]
|
|
146
|
+
w, h = img.size
|
|
147
|
+
margin = max(20, int(min(w, h) * 0.03))
|
|
148
|
+
|
|
149
|
+
if wm_type == "text":
|
|
150
|
+
overlay = _make_text_overlay(w, h, args)
|
|
151
|
+
else:
|
|
152
|
+
overlay = _make_image_overlay(w, h, args)
|
|
153
|
+
|
|
154
|
+
if opacity < 255:
|
|
155
|
+
overlay.putalpha(overlay.split()[3].point(lambda a: int(a * opacity / 255)))
|
|
156
|
+
|
|
157
|
+
paste_x, paste_y = _calc_position(w, h, overlay.width, overlay.height, position, margin)
|
|
158
|
+
img.paste(overlay, (paste_x, paste_y), overlay)
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _run_remove(img: Image.Image, args: dict[str, Any]):
|
|
162
|
+
position = args["position"]
|
|
163
|
+
ratio = args["size_ratio"]
|
|
164
|
+
w, h = img.size
|
|
165
|
+
|
|
166
|
+
rw = max(10, int(w * ratio))
|
|
167
|
+
rh = max(10, int(h * ratio))
|
|
168
|
+
margin = max(5, int(min(w, h) * 0.01))
|
|
169
|
+
|
|
170
|
+
rx, ry = _calc_position(w, h, rw, rh, position, margin)
|
|
171
|
+
|
|
172
|
+
_fill_region(img, rx, ry, rw, rh)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _calc_position(
|
|
176
|
+
img_w: int, obj_w: int, img_h: int, obj_h: int, position: str, margin: int
|
|
177
|
+
) -> tuple[int, int]:
|
|
178
|
+
positions = {
|
|
179
|
+
"Top-Left": (margin, margin),
|
|
180
|
+
"Top-Right": (img_w - obj_w - margin, margin),
|
|
181
|
+
"Bottom-Left": (margin, img_h - obj_h - margin),
|
|
182
|
+
"Bottom-Right": (img_w - obj_w - margin, img_h - obj_h - margin),
|
|
183
|
+
"Center": ((img_w - obj_w) // 2, (img_h - obj_h) // 2),
|
|
184
|
+
}
|
|
185
|
+
return positions.get(position, (margin, margin))
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _make_text_overlay(img_w: int, img_h: int, args: dict[str, Any]) -> Image.Image:
|
|
189
|
+
text = args["text"]
|
|
190
|
+
font_size = args["font_size"]
|
|
191
|
+
color = args["color"]
|
|
192
|
+
|
|
193
|
+
font = None
|
|
194
|
+
for fp in FONT_PATHS:
|
|
195
|
+
try:
|
|
196
|
+
font = ImageFont.truetype(fp, font_size)
|
|
197
|
+
break
|
|
198
|
+
except (OSError, IOError):
|
|
199
|
+
continue
|
|
200
|
+
|
|
201
|
+
overlay = Image.new("RGBA", (img_w, img_h), (0, 0, 0, 0))
|
|
202
|
+
draw = ImageDraw.Draw(overlay)
|
|
203
|
+
|
|
204
|
+
bbox = draw.textbbox((0, 0), text, font=font)
|
|
205
|
+
tw, th = bbox[2] - bbox[0], bbox[3] - bbox[1]
|
|
206
|
+
|
|
207
|
+
text_overlay = Image.new("RGBA", (tw + 20, th + 20), (0, 0, 0, 0))
|
|
208
|
+
tdraw = ImageDraw.Draw(text_overlay)
|
|
209
|
+
tdraw.text((10 - bbox[0], 10 - bbox[1]), text, fill=color, font=font)
|
|
210
|
+
|
|
211
|
+
return text_overlay
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _make_image_overlay(img_w: int, img_h: int, args: dict[str, Any]) -> Image.Image:
|
|
215
|
+
logo = Image.open(args["logo_path"]).convert("RGBA")
|
|
216
|
+
scale = args["scale"] / 100
|
|
217
|
+
new_w = max(10, int(img_w * scale))
|
|
218
|
+
new_h = int(logo.height * (new_w / logo.width))
|
|
219
|
+
return logo.resize((new_w, new_h), Image.LANCZOS)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _fill_region(img: Image.Image, rx: int, ry: int, rw: int, rh: int):
|
|
223
|
+
samples = []
|
|
224
|
+
border = max(2, int(min(rw, rh) * 0.05))
|
|
225
|
+
left = max(0, rx - border)
|
|
226
|
+
right = min(img.width, rx + rw + border)
|
|
227
|
+
top = max(0, ry - border)
|
|
228
|
+
bottom = min(img.height, ry + rh + border)
|
|
229
|
+
|
|
230
|
+
for x in range(left, right):
|
|
231
|
+
for y in (top, bottom - 1):
|
|
232
|
+
if 0 <= y < img.height:
|
|
233
|
+
samples.append(img.getpixel((x, y)))
|
|
234
|
+
for y in range(top, bottom):
|
|
235
|
+
for x in (left, right - 1):
|
|
236
|
+
if 0 <= x < img.width:
|
|
237
|
+
samples.append(img.getpixel((x, y)))
|
|
238
|
+
|
|
239
|
+
avg_color = tuple(
|
|
240
|
+
int(sum(c[i] for c in samples) / len(samples)) for i in range(4)
|
|
241
|
+
) if samples else (128, 128, 128, 255)
|
|
242
|
+
|
|
243
|
+
fill = Image.new("RGBA", (rw, rh), avg_color)
|
|
244
|
+
img.paste(fill, (rx, ry))
|
|
245
|
+
|
|
246
|
+
region = img.crop((rx, ry, rx + rw, ry + rh))
|
|
247
|
+
blurred = region.filter(ImageFilter.GaussianBlur(radius=max(2, min(rw, rh) // 10)))
|
|
248
|
+
img.paste(blurred, (rx, ry))
|
imagex/utils/__init__.py
ADDED
|
File without changes
|
imagex/utils/file_ops.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import shutil
|
|
2
|
+
from datetime import datetime
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Optional
|
|
5
|
+
|
|
6
|
+
from imagex.config import BACKUP_DIR_NAME, is_image
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def find_images(directory: Path) -> list[Path]:
|
|
10
|
+
files = []
|
|
11
|
+
for f in sorted(directory.iterdir()):
|
|
12
|
+
if f.is_file() and is_image(f):
|
|
13
|
+
files.append(f)
|
|
14
|
+
return files
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def backup_file(file: Path) -> Optional[Path]:
|
|
18
|
+
backup_root = file.parent / BACKUP_DIR_NAME
|
|
19
|
+
timestamp = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
|
20
|
+
backup_dir = backup_root / timestamp
|
|
21
|
+
backup_dir.mkdir(parents=True, exist_ok=True)
|
|
22
|
+
dest = backup_dir / file.name
|
|
23
|
+
shutil.copy2(file, dest)
|
|
24
|
+
return dest
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def get_output_path(
|
|
28
|
+
file: Path,
|
|
29
|
+
mode: str,
|
|
30
|
+
output_dir: Optional[Path] = None,
|
|
31
|
+
) -> Path:
|
|
32
|
+
if mode == "overwrite":
|
|
33
|
+
return file
|
|
34
|
+
elif mode == "output":
|
|
35
|
+
return (file.parent / "output" / file.name).resolve()
|
|
36
|
+
elif mode == "custom":
|
|
37
|
+
if output_dir is None:
|
|
38
|
+
msg = "output_dir required for custom mode"
|
|
39
|
+
raise ValueError(msg)
|
|
40
|
+
return output_dir / file.name
|
|
41
|
+
msg = f"Unknown output mode: {mode}"
|
|
42
|
+
raise ValueError(msg)
|
imagex/utils/progress.py
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from typing import Any, Callable, Optional
|
|
3
|
+
|
|
4
|
+
from rich.progress import (
|
|
5
|
+
BarColumn,
|
|
6
|
+
Progress,
|
|
7
|
+
TextColumn,
|
|
8
|
+
TimeRemainingColumn,
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
from imagex.utils.file_ops import backup_file, get_output_path
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def process_files(
|
|
15
|
+
files: list[Path],
|
|
16
|
+
process_func: Callable[[Path, Path, dict[str, Any]], bool],
|
|
17
|
+
feature_name: str,
|
|
18
|
+
output_mode: str,
|
|
19
|
+
output_dir: Optional[Path] = None,
|
|
20
|
+
args: Optional[dict[str, Any]] = None,
|
|
21
|
+
):
|
|
22
|
+
if args is None:
|
|
23
|
+
args = {}
|
|
24
|
+
|
|
25
|
+
with Progress(
|
|
26
|
+
TextColumn(f"[bold blue]{feature_name}[/bold blue]"),
|
|
27
|
+
BarColumn(),
|
|
28
|
+
TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
|
|
29
|
+
TextColumn("• {task.completed}/{task.total}"),
|
|
30
|
+
TimeRemainingColumn(),
|
|
31
|
+
) as progress:
|
|
32
|
+
task = progress.add_task("Processing...", total=len(files))
|
|
33
|
+
|
|
34
|
+
for file in files:
|
|
35
|
+
try:
|
|
36
|
+
output_path = get_output_path(file, output_mode, output_dir)
|
|
37
|
+
|
|
38
|
+
if output_mode == "overwrite":
|
|
39
|
+
backup_file(file)
|
|
40
|
+
|
|
41
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
42
|
+
process_func(file, output_path, args)
|
|
43
|
+
|
|
44
|
+
except Exception as e:
|
|
45
|
+
progress.console.print(
|
|
46
|
+
f"[red]✗ {file.name}: {e}[/red]"
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
progress.advance(task)
|
|
@@ -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
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
imagex/__init__.py,sha256=rnObPjuBcEStqSO0S6gsdS_ot8ITOQjVj_-P1LUUYpg,22
|
|
2
|
+
imagex/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
|
|
3
|
+
imagex/cli.py,sha256=GrXl_QhAx4Kx2XsTLX8WHoB66TwSDlpKqryPe2ksQPw,6978
|
|
4
|
+
imagex/config.py,sha256=DN67otXTTH2wS5X7QYTFdFoeaWRNk9JaXqt6q2RJcto,290
|
|
5
|
+
imagex/features/__init__.py,sha256=M0NHVdKZiijADjzKZiwrDwtaVWvHyMTbKyqM-PmA6rw,951
|
|
6
|
+
imagex/features/add_noise.py,sha256=M1c1mv61v5qvUPi6p0vcAjfFnGq5ExSsABpjIE-VbpI,2268
|
|
7
|
+
imagex/features/compress.py,sha256=fDMVhfVbF2qJsTzY5NOy-8uw41_egXa03Fn_ep9gIEg,2945
|
|
8
|
+
imagex/features/convert.py,sha256=s7hYe7uQ8J5fn9qnhqN1osWeV4w8_vuh4-5VYUBtAM0,2498
|
|
9
|
+
imagex/features/remove_metadata.py,sha256=Y-34esRUaYDVR6CYZ0KiOVs077DVS5OJZEEFbEcdRfs,1234
|
|
10
|
+
imagex/features/rename_batch.py,sha256=AfpXyRSMC476oKQk0da78rk4QR55JeJBowrlkmulDRA,1795
|
|
11
|
+
imagex/features/resize.py,sha256=WMEYv1NCfBvND9g5YCdWDksIpKX6gCitlz7Qe0B7T8M,2835
|
|
12
|
+
imagex/features/watermark.py,sha256=zwBGRdzVvGTvevDBrexsjD5L0ziGVeYPdyqY1l2lxsc,7258
|
|
13
|
+
imagex/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
14
|
+
imagex/utils/file_ops.py,sha256=JAYcppgU1p_dBoi_as3mzpPchnOEpejo7riSBsU4reQ,1164
|
|
15
|
+
imagex/utils/progress.py,sha256=HqNDba-CuOVeSZch0dRIb9u-CUXX7v3PBmtc4P-MUoQ,1375
|
|
16
|
+
imagex-0.1.0.dist-info/licenses/LICENSE,sha256=MBapErI6Fowrcdbtzn8ttQz2ywvxLpcd70FDmlnE5e4,1069
|
|
17
|
+
imagex-0.1.0.dist-info/METADATA,sha256=Qbb7VOjk_0E1g1_AzwWwweWT4wAfwUr_dgia5UKz-PE,2615
|
|
18
|
+
imagex-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
19
|
+
imagex-0.1.0.dist-info/entry_points.txt,sha256=Wu0Vacajmuk6OX1Feo2mSsaaICiLjabZifc3EAFJ2aM,43
|
|
20
|
+
imagex-0.1.0.dist-info/top_level.txt,sha256=brNRF_KDuY8Xrn4f0dyG8mgLPoMPrve8GrzLeelF15M,7
|
|
21
|
+
imagex-0.1.0.dist-info/RECORD,,
|
|
@@ -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.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
imagex
|