-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimage_optimizer_cli.py
More file actions
185 lines (162 loc) · 7.07 KB
/
image_optimizer_cli.py
File metadata and controls
185 lines (162 loc) · 7.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
"""Terminal (Rich) edition — run via: python image_optimizer.py --cli"""
import argparse
import sys
from pathlib import Path
from rich.console import Console
from rich.live import Live
from rich.panel import Panel
from rich.progress import BarColumn, DownloadColumn, Progress, TransferSpeedColumn
from rich.prompt import Confirm, IntPrompt, Prompt
from rich.table import Table
from optimizer_core import (
OUTPUT_MODES,
RESIZE_OPTIONS,
DependencyManager,
ImageOptimizer,
format_bytes,
)
console = Console()
RESIZE_PRESETS = {str(i): dim for i, (_, dim) in enumerate(RESIZE_OPTIONS)}
class CliApp(ImageOptimizer):
def __init__(self, skip_confirm: bool = False):
super().__init__()
self.skip_confirm = skip_confirm
def show_header(self):
console.clear()
console.print(
Panel.fit(
"[bold white]IMAGE OPTIMIZER — CLI Edition[/]",
border_style="cyan",
padding=(0, 5),
)
)
def run_onboarding(self):
self.show_header()
if self.magick_path:
return
console.print("[yellow]ImageMagick is required.[/]")
if Confirm.ask("Download portable ImageMagick to %TEMP%?"):
try:
self.magick_path = DependencyManager.install_portable(
on_status=lambda m: console.print(f"[blue]{m}[/]")
)
except Exception as exc:
console.print(f"[red]Download failed: {exc}[/]")
sys.exit(1)
else:
sys.exit(1)
def _settings_table(self, target_path: str) -> Table:
table = Table(show_header=False, box=None)
table.add_row("1", "Target Format", f"[green]{self.config['format']}[/]")
table.add_row("2", "Quality", f"[green]{self.config['quality']}%[/]")
dim = "Original" if self.config["max_dim"] == 0 else f"{self.config['max_dim']}px"
table.add_row("3", "Max Dimension", f"[green]{dim}[/]")
table.add_row("4", "Strip Metadata", f"[green]{'Yes' if self.config['strip'] else 'No'}[/]")
table.add_row("5", "Output Mode", f"[green]{self.config['output_mode']}[/]")
table.add_row("6", "Subfolders", f"[green]{'Yes' if self.config['recursive'] else 'No'}[/]")
table.add_row("", "Path", f"[cyan]{target_path}[/]")
return table
def interactive_menu(self, target_path: str):
while True:
self.show_header()
console.print(self._settings_table(target_path))
choice = Prompt.ask("Choice (1-6, S=start, Q=quit)", default="s").lower()
if choice == "q":
sys.exit(0)
if choice == "s":
if self.skip_confirm or Confirm.ask("START PROCESSING?"):
return
continue
if choice == "1":
self.config["format"] = Prompt.ask(
"Format",
choices=["ORIGINAL", "WEBP", "JPEG", "PNG", "AVIF"],
default=self.config["format"],
).upper()
elif choice == "2":
q = IntPrompt.ask("Quality", default=self.config["quality"])
self.config["quality"] = max(10, min(100, q))
elif choice == "3":
console.print("Presets: " + ", ".join(f"{i}={n}" for i, (n, _) in enumerate(RESIZE_OPTIONS)))
self.config["max_dim"] = RESIZE_PRESETS.get(
Prompt.ask("Preset", default="0"), 0
)
elif choice == "4":
self.config["strip"] = Confirm.ask("Strip metadata?", default=self.config["strip"])
elif choice == "5":
pick = Prompt.ask("Mode", choices=["1", "2", "3"], default="1")
self.config["output_mode"] = OUTPUT_MODES[int(pick) - 1]
elif choice == "6":
self.config["recursive"] = Confirm.ask("Subfolders?", default=self.config["recursive"])
def start(self, target_path: str):
target = Path(target_path).resolve()
if not target.exists():
console.print(f"[red]Path not found: {target_path}[/]")
return
self.run_onboarding()
if not self.skip_confirm:
self.interactive_menu(str(target))
files = self.collect_files(target)
if not files:
console.print("[yellow]No images found.[/]")
return
table = Table(title="Processing", expand=True)
for col in ("Status", "File", "Old", "New", "Saved"):
table.add_column(col)
with Live(table, refresh_per_second=8):
def on_progress(idx, total, path, status, old_sz, new_sz, saving, _err, stats=None):
save_col = f"{saving}%" if saving is not None else "---"
new_col = format_bytes(new_sz) if new_sz else "---"
color = "green" if status == "Done" else "red"
table.add_row(
f"[{color}]{status}[/]",
path.name[:28],
format_bytes(old_sz),
new_col,
save_col,
)
table.caption = f"{idx}/{total}"
stats = self.process_batch(target, on_progress=on_progress)
console.print(
Panel(
f"Done: {stats['done']} Failed: {stats['fail']} Saved: {format_bytes(stats['saved'])}",
title="Summary",
border_style="green",
)
)
if not self.skip_confirm:
input("Press Enter to exit...")
def parse_args():
p = argparse.ArgumentParser(description="Image Optimizer CLI")
p.add_argument("path", nargs="?")
p.add_argument("-q", "--quality", type=int, default=80)
p.add_argument("-f", "--format", choices=["ORIGINAL", "WEBP", "JPEG", "PNG", "AVIF"], default="ORIGINAL")
p.add_argument("--max-dim", type=int, default=0, choices=[0, 1280, 1920, 2048, 3840])
p.add_argument("-r", "--recursive", action="store_true")
p.add_argument("-m", "--mode", choices=["copy", "overwrite", "backup"], default="copy")
p.add_argument("--strip", dest="strip", action="store_true", default=True)
p.add_argument("--no-strip", dest="strip", action="store_false")
p.add_argument("-y", "--yes", action="store_true")
p.add_argument("--dry-run", action="store_true")
p.add_argument("--no-cache", action="store_true")
p.add_argument("--no-resume", action="store_true")
return p.parse_args()
def main():
args = parse_args()
mode_map = {"copy": "Save as Copy", "overwrite": "Overwrite", "backup": "Backup Original"}
app = CliApp(skip_confirm=args.yes)
app.config.update(
format=args.format,
quality=max(10, min(100, args.quality)),
max_dim=args.max_dim,
strip=args.strip,
recursive=args.recursive,
output_mode=mode_map[args.mode],
dry_run=args.dry_run,
cache_enabled=not args.no_cache,
resume_enabled=not args.no_resume,
)
path = args.path or Prompt.ask("Path to file or folder")
app.start(path.strip('"'))
if __name__ == "__main__":
main()