image-optimizer-webui 1.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.
@@ -0,0 +1,180 @@
1
+ """Polling folder watcher for Watch mode.
2
+
3
+ Zero-dependency alternative to `watchdog`: rather than subscribing to
4
+ filesystem events (which adds a native dependency, needs to keep up with
5
+ per-OS backends, and must survive the binary-bundle story this app has),
6
+ we re-scan the directory tree on a timer and diff against the last
7
+ snapshot. Files that are new (or whose mtime/size changed since last seen)
8
+ are emitted to the consumer.
9
+
10
+ Design points:
11
+ - Change detection is snapshot-diff on (mtime, size), the same signal every
12
+ incremental build tool uses (make, rsync -u, the app's own skip_existing
13
+ logic). Writing a file atomically (write tmp + rename) produces exactly
14
+ one stat change, so Watch picks it up exactly once.
15
+ - Rename detection: if a path disappears and a different path appears in
16
+ the *same* poll cycle with an identical (mtime, size), that's treated as
17
+ a rename of the same content rather than an unrelated delete+create, and
18
+ the new-path event carries `renamed_from` so the caller can clean up
19
+ whatever it produced for the old name (e.g. a stale optimized output)
20
+ instead of leaving an orphan behind. A lone disappearance — nothing
21
+ reappearing with a matching stat — is never reported at all: the watcher
22
+ only emits new/changed files, so a plain delete (no matching reappearance)
23
+ can't be mistaken for something requiring cleanup. This matters because
24
+ many people delete the original after keeping the compressed output, and
25
+ that must never cascade into deleting the output too.
26
+ - The scan itself is blocking I/O and runs on a thread executor; new events
27
+ are pushed onto an asyncio.Queue so a slow consumer (lossy encoding of a
28
+ large batch) never stalls the polling loop or misses files arriving
29
+ mid-encode.
30
+ - `stop()` is cooperative: the poll loop notices _stop after its current
31
+ sleep, drains the queue, and exits.
32
+ """
33
+ from __future__ import annotations
34
+
35
+ import asyncio
36
+ from pathlib import Path
37
+ from typing import Awaitable, Callable, Optional
38
+
39
+ # Same extensions the scan flow accepts (see image_optimizer/main.py SCAN_EXTS) — case-
40
+ # folded so "photo.PNG" is caught on case-sensitive filesystems too.
41
+ IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp"}
42
+
43
+
44
+ class FolderWatcher:
45
+ def __init__(
46
+ self,
47
+ directory: Path,
48
+ recursive: bool = True,
49
+ interval: float = 2.0,
50
+ process_existing: bool = False,
51
+ on_change: Optional[Callable[[str, Path, Optional[str]], Awaitable[None]]] = None,
52
+ ):
53
+ self.directory = directory
54
+ self.recursive = recursive
55
+ self.interval = max(0.5, interval)
56
+ self.process_existing = process_existing
57
+ self.on_change = on_change
58
+ self._known: dict[str, tuple[float, int]] = {}
59
+ self._stop = False
60
+ self._queue: Optional[asyncio.Queue] = None
61
+ self._started = False
62
+ self.files_seen = 0
63
+
64
+ def _scan(self) -> list[tuple[str, Path, tuple[float, int]]]:
65
+ """One blocking directory walk. Returns (rel_path, abs_path,
66
+ (mtime, size)) for every image file under self.directory, sorted by
67
+ rel_path so events arrive in deterministic order."""
68
+ iter_method = self.directory.rglob if self.recursive else self.directory.glob
69
+ out: list[tuple[str, Path, tuple[float, int]]] = []
70
+ for p in iter_method("*"):
71
+ if not p.is_file() or p.suffix.lower() not in IMAGE_EXTS:
72
+ continue
73
+ try:
74
+ rel = str(p.relative_to(self.directory))
75
+ except ValueError:
76
+ continue
77
+ try:
78
+ s = p.stat()
79
+ except OSError:
80
+ continue # disappeared mid-walk — skip it this round
81
+ out.append((rel, p, (s.st_mtime, s.st_size)))
82
+ return sorted(out, key=lambda item: item[0])
83
+
84
+ @staticmethod
85
+ async def _enqueue(queue: asyncio.Queue, item):
86
+ await queue.put(item)
87
+
88
+ async def _once(self) -> None:
89
+ """Scan, fire on_change for every new/changed file, update snapshot.
90
+
91
+ First call (baseline): record everything as already-known so nothing
92
+ pre-existing is treated as new — unless process_existing is set, in
93
+ which case the existing files are emitted once up front.
94
+
95
+ Subsequent calls: a brand-new path whose (mtime, size) exactly
96
+ matches a path that just disappeared is treated as a rename — the
97
+ event's renamed_from carries the old relative path so the caller
98
+ can clean up what it produced for that name. Every other
99
+ disappearance (no matching reappearance in this same cycle) is
100
+ simply dropped from the snapshot and never reported — deletions on
101
+ their own are not the watcher's concern."""
102
+ items = await asyncio.to_thread(self._scan)
103
+ queue = self._queue
104
+ snapshot = {rel: stat for rel, _, stat in items}
105
+ if not self._started:
106
+ self._started = True
107
+ self._known = snapshot
108
+ if self.process_existing:
109
+ for rel, _path, _stat in items:
110
+ self.files_seen += 1
111
+ await self._enqueue(queue, (rel, _stat, None))
112
+ return
113
+
114
+ # Candidates for "renamed from": paths present last snapshot, gone
115
+ # from this one. Grouped by stat so a same-cycle reappearance with
116
+ # an identical (mtime, size) can be matched back to the old name.
117
+ disappeared_by_stat: dict[tuple[float, int], list[str]] = {}
118
+ for rel, stat in self._known.items():
119
+ if rel not in snapshot:
120
+ disappeared_by_stat.setdefault(stat, []).append(rel)
121
+
122
+ for rel, _path, stat in items:
123
+ prev = self._known.get(rel)
124
+ if prev is None:
125
+ renamed_from = None
126
+ candidates = disappeared_by_stat.get(stat)
127
+ if candidates:
128
+ # FIFO match — good enough for a same-size/same-mtime
129
+ # tie-break among multiple simultaneous renames; the
130
+ # caller only uses this to clean up an old output, not
131
+ # for anything correctness-critical.
132
+ renamed_from = candidates.pop(0)
133
+ if not candidates:
134
+ del disappeared_by_stat[stat]
135
+ self.files_seen += 1
136
+ await self._enqueue(queue, (rel, stat, renamed_from))
137
+ elif prev != stat:
138
+ self.files_seen += 1
139
+ await self._enqueue(queue, (rel, stat, None))
140
+ self._known = snapshot
141
+
142
+ async def _consume(self) -> None:
143
+ queue = self._queue
144
+ while True:
145
+ rel, stat, renamed_from = await queue.get()
146
+ try:
147
+ await self.on_change(rel, Path(self.directory) / rel, renamed_from)
148
+ finally:
149
+ queue.task_done()
150
+
151
+ async def run(self) -> None:
152
+ """Start the poll loop. Emits are delivered serially to on_change.
153
+
154
+ Normal exit (stop() called): drains the queue — already-discovered
155
+ files finish processing — then shuts the consumer down. External
156
+ cancellation (e.g. session sweeps / server shutdown calling
157
+ task.cancel()): the consumer is dropped immediately so shutdown
158
+ doesn't stall on a long encode."""
159
+ if self._stop or self._queue is not None:
160
+ return
161
+ self._queue = asyncio.Queue()
162
+ consumer = asyncio.create_task(self._consume())
163
+ try:
164
+ await self._once()
165
+ while not self._stop:
166
+ await asyncio.sleep(self.interval)
167
+ await self._once()
168
+ except asyncio.CancelledError:
169
+ consumer.cancel()
170
+ self._queue = None
171
+ raise
172
+ else:
173
+ await self._queue.join()
174
+ finally:
175
+ consumer.cancel()
176
+ self._queue = None
177
+
178
+ def stop(self) -> None:
179
+ """Ask the poll loop to shut down at its next opportunity."""
180
+ self._stop = True
@@ -0,0 +1,388 @@
1
+ Metadata-Version: 2.4
2
+ Name: image-optimizer-webui
3
+ Version: 1.1.0
4
+ Summary: Batch image compression with a local web UI (PNG/JPEG/WebP/AVIF)
5
+ Author: aREversez
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/aREversez/image-optimizer
8
+ Project-URL: Issues, https://github.com/aREversez/image-optimizer/issues
9
+ Project-URL: Changelog, https://github.com/aREversez/image-optimizer/blob/main/CHANGELOG.md
10
+ Keywords: image,optimizer,compression,png,webp,avif,webui,fastapi
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Environment :: Web Environment
13
+ Classifier: Framework :: FastAPI
14
+ Classifier: Intended Audience :: End Users/Desktop
15
+ Classifier: Operating System :: Microsoft :: Windows
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Operating System :: MacOS
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Multimedia :: Graphics :: Graphics Conversion
24
+ Requires-Python: >=3.10
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: fastapi>=0.104.0
28
+ Requires-Dist: uvicorn>=0.24.0
29
+ Requires-Dist: jinja2>=3.1.2
30
+ Requires-Dist: Pillow>=11.3.0
31
+ Requires-Dist: python-multipart>=0.0.6
32
+ Provides-Extra: dev
33
+ Requires-Dist: pytest>=7.4.0; extra == "dev"
34
+ Requires-Dist: httpx>=0.24.0; extra == "dev"
35
+ Requires-Dist: build>=1.0.0; extra == "dev"
36
+ Requires-Dist: twine>=4.0.0; extra == "dev"
37
+ Dynamic: license-file
38
+
39
+ <picture>
40
+ <source media="(prefers-color-scheme: dark)" srcset="assets/banner.png">
41
+ <img alt="Image Optimizer" src="assets/banner.png" width="100%">
42
+ </picture>
43
+
44
+ # Image Optimizer
45
+
46
+ Batch image compression with a local web UI. Uses **pngquant** (lossy PNG
47
+ quantization) and **oxipng** (lossless strip/optimization) behind a clean
48
+ interface, plus **WebP via Pillow**, **AVIF via avifenc**, and — with
49
+ **mozjpeg's cjpeg** — true lossy **JPEG** re-compression that keeps the
50
+ JPEG format. Includes a dedicated **Screenshot mode** for near-lossless
51
+ compression of UI/software screenshots.
52
+
53
+ ## Features
54
+
55
+ - **Local folder scanning** — select a directory, scan recursively (optional), and pick which files to optimize
56
+ - **File upload** — drag or browse to upload individual images (PNG, JPG, BMP, TIFF, WebP)
57
+ - **File sorting** — sort scanned files by modified/created time (newest/oldest) or size (large/small), handy for grabbing the latest screenshots or targeting the biggest files
58
+ - **Watch Mode** — monitor a folder and auto-optimize new or changed images as they appear, with live SSE-streamed logs and rename detection
59
+ - **Batch resume** — progress is persisted per output folder; an interrupted batch (crash, cancel, server restart) can be resumed where it left off
60
+ - **Pause / Resume / Cancel** mid-batch, plus per-file compression parameter overrides and single-file pre-compression preview
61
+ - **Before/after preview** — overlay and side-by-side compare views
62
+ - **Four compression modes:**
63
+ - `standard` — pngquant + oxipng, best size reduction
64
+ - `lossless` — oxipng only, no color loss
65
+ - `resize only` — scale down, no quantization
66
+ - `screenshot` — near-lossless pngquant pass tuned for UI/software screenshots (PNG-only, hardcoded dithering off)
67
+ - **Output format** — PNG (via pngquant/oxipng), WebP (via Pillow's built-in encoder, no extra binary needed), JPG (via mozjpeg's `cjpeg`, keeping JPEG rather than converting), or AVIF (via `avifenc`)
68
+ - **Keep-format JPEG optimization** — select the JPG output format on a batch of `.jpg` files and they're genuinely re-compressed lossily by mozjpeg while staying JPEG (requires `cjpeg` in `bin/`, see `bin/README.md`)
69
+ - **EXIF retention** (opt-in) — keep a curated EXIF subset (camera, date, exposure; GPS stripped for privacy)
70
+ - **Color protection** — list hex colors to preserve in the palette
71
+ - **Dithering toggle** — smoother gradients (standard mode)
72
+ - **Results sorting & filtering** — sort results by compression %, compressed size, or bytes saved; filter to show all/succeeded/failed
73
+ - **Dark mode** — manual theme toggle or auto-follow OS preference
74
+ - **Internationalization** — English and 中文 (Chinese) built-in, extensible to more languages
75
+ - **SSE progress transport** — real-time server-sent events for progress/logs with automatic polling fallback
76
+ - **Output directory** — save results to any folder (or use the built-in ZIP download), with a Reveal Output Folder button to jump straight to it in the OS file explorer
77
+ - **Skip already optimized** — re-running against the same output folder reuses existing outputs instead of recompressing unchanged files (settings-aware: changing quality/mode/format forces a real recompress)
78
+ - **Recent folder history** — quick-access chips with per-item removal and clear all
79
+ - **In-app settings** — gear icon opens a settings panel (host, port, workers, timeouts, language) persisted to `config.json`
80
+ - **Session state restoration** — page refresh restores files/results and re-attaches to a still-running batch
81
+ - **Auto-detect binaries** — finds `pngquant`/`oxipng`/`cjpeg`/`avifenc` on PATH, in `bin/`, or in the per-user cache filled by the first-run download
82
+ - **CLI mode** — `--source`/`--output` runs a batch headlessly (no browser, no server) and exits with a process exit code, for scripts and CI; shares the exact same compression pipeline and settings validation as the web UI
83
+ - **Cross-platform** — Windows, macOS, Linux (pre-built downloads for Windows, Apple Silicon Macs and Linux x86-64; the pip package fetches verified upstream binaries on first run where the publisher ships one, otherwise the tools come from PATH)
84
+
85
+ ## Quick Start
86
+
87
+ ### Option 1: pip (any OS)
88
+
89
+ ```bash
90
+ pip install image-optimizer-webui
91
+ image-optimizer serve
92
+ ```
93
+
94
+ Open http://127.0.0.1:8090. Bare `image-optimizer` does the same thing — `serve`
95
+ is accepted as a synonym because that is the convention elsewhere.
96
+
97
+ The first start downloads the encoder binaries this platform can get from
98
+ upstream (see [Encoder binaries](#encoder-binaries)), verifies each against a
99
+ pinned SHA-256, and caches it in your user data directory. The wheel itself is
100
+ pure Python and ships no third-party executables.
101
+
102
+ ### Option 2: Standalone download (no Python required)
103
+
104
+ Download the latest release from the [Releases page](https://github.com/aREversez/image-optimizer/releases):
105
+
106
+ - **Windows:** run `ImageOptimizer-windows-x64.exe`
107
+ - **macOS (Apple Silicon):** open `ImageOptimizer-macos-arm64.dmg` and follow the `README.txt` inside
108
+ - **Linux (x86-64):** `tar -xzf ImageOptimizer-linux-x64.tar.gz && ./ImageOptimizer`
109
+
110
+ The macOS and Linux builds run in a terminal; open <http://127.0.0.1:8090> in your browser once they start.
111
+
112
+ > **Windows SmartScreen:** The exe is unsigned (code signing certificates cost $200+/year for open-source projects). On first run, SmartScreen may show "Windows protected your PC" — click **More info** → **Run anyway**. This is normal for unsigned open-source software. The macOS build is unsigned too (see the `README.txt` in the disk image).
113
+
114
+ ### Option 3: From source
115
+
116
+ ```bash
117
+ git clone https://github.com/aREversez/image-optimizer.git
118
+ cd image-optimizer
119
+ pip install -r requirements.txt
120
+ python -m image_optimizer # or: image-optimizer, or start.bat
121
+ ```
122
+
123
+ Open http://127.0.0.1:8090 in your browser.
124
+
125
+ The first run will auto-detect `pngquant`/`oxipng`/`cjpeg`/`avifenc` on PATH and
126
+ in the `bin/` folder, and fetch the pinned releases that are missing. See
127
+ `bin/README.md` if a binary is unavailable.
128
+
129
+ ## Usage
130
+
131
+ 1. **Enter a folder path** — type or browse to select a directory, then click *Scan Folder* (or drag & drop / upload individual files)
132
+ 2. **Review files** — deselect any you want to skip, sort by date/size, adjust quality/width/mode (per-file overrides via each card's gear icon, or click *Preview* for a single-file dry run)
133
+ 3. **Protect colors** (optional) — add hex colors like `#2ecc71` to preserve
134
+ 4. **Start** — click *Start* and watch the live progress log (SSE-streamed)
135
+ 5. **Compare & download** — click any result's *Compare* button for before/after preview, then download the ZIP or click *Reveal Output Folder* (when an output folder is set). Sort/filter results by compression ratio or size.
136
+
137
+ Alternatively, set up **Watch Mode** (sidebar card) to auto-compress new images dropped into a folder, and use *Resume* on page load if a previous batch was interrupted.
138
+
139
+ ## CLI Mode
140
+
141
+ For scripting, batch jobs, or anything that shouldn't need a browser: pass
142
+ `--source` and the app runs headlessly (no web server, no browser) and
143
+ exits with a process exit code (`0` if everything succeeded, `1` if
144
+ anything failed — safe to check in a script or CI step).
145
+
146
+ ```
147
+ image-optimizer --source "D:\screenshots" --output "D:\screenshots-compressed"
148
+ ```
149
+
150
+ ```
151
+ image-optimizer --source ./raw --output ./compressed --quality high --max-width 1920 --mode standard --no-dithering
152
+ ```
153
+
154
+ (From a source checkout, `python -m image_optimizer` works identically.)
155
+
156
+ CLI mode runs every image through the exact same compression pipeline and
157
+ settings validation as the web UI and Watch Mode — no separate "CLI
158
+ version" of the logic to drift out of sync, so the same `--quality`/
159
+ `--mode`/etc. combination produces the same result either way.
160
+
161
+ - `--source` - directory to compress (required to trigger CLI mode)
162
+ - `--output` - output directory (required with `--source`)
163
+ - `--quality {high,medium,low}` - Standard/Screenshot mode color-quality floor (default `medium`)
164
+ - `--format {png,jpg,webp,avif}` - output format (default `png`)
165
+ - `--mode {standard,lossless,resize_only,screenshot}` - compression mode (default `standard`; `screenshot` is PNG-only)
166
+ - `--max-width <int>` - resize so the longest side is at most this many pixels (default `0` = no resize; required `> 0` with `--mode resize_only`)
167
+ - `--dithering` / `--no-dithering` - dithering for Standard-mode PNG quantization (default enabled)
168
+ - `--protect-colors "#2ecc71,#ff0000"` - hex colors to prioritize keeping exact in Standard mode's palette
169
+ - `--keep-exif` - keep a curated subset of EXIF (camera make/model, date, exposure); GPS and orientation are always stripped regardless (default: strip all EXIF)
170
+ - `--recursive` / `--no-recursive` - scan subfolders too (default `--recursive`; shared with `--dir`, see Configuration below)
171
+ - `--workers` - concurrent compression workers (shared with the web server's `--workers`, see Configuration below)
172
+ - `--cache-dir PATH` - enable the content-hash result cache (see below); default: no cache
173
+ - `--cache-max-size-mb N` - cache size cap, enforced after each run by evicting least-recently-used entries (default `1024`, `0` = unlimited)
174
+ - `--exclude GLOB` / `--include GLOB` - filter which files are processed; repeatable (see below)
175
+ - `--json` - print the final report as one JSON object on stdout (see below)
176
+
177
+ Output mirrors the source folder's directory structure. Name collisions
178
+ after a format conversion (e.g. `photo.png` and `photo.jpg` both becoming
179
+ `photo.png`) get a numbered suffix (`photo_2.png`) rather than silently
180
+ overwriting one another.
181
+
182
+ Not yet supported in CLI mode: per-file overrides (every file in the batch
183
+ gets the same settings). Without `--cache-dir`, every CLI run recompresses
184
+ everything under `--source`.
185
+
186
+ ### Result cache
187
+
188
+ `--cache-dir` keeps finished results in a content-addressed cache, so an
189
+ unchanged image with the same settings is copied from the cache instead of
190
+ being recompressed. It does not depend on `--output`: a caller that uses a
191
+ fresh temporary output directory on every run still gets hits.
192
+
193
+ ```
194
+ image-optimizer --source ./raw --output "$(mktemp -d)" --cache-dir ~/.cache/image-optimizer-cli
195
+ ```
196
+
197
+ - The key covers the input file's bytes, the pixel-affecting settings (`--quality`, `--mode`, `--max-width`, `--protect-colors`, `--dithering`/`--no-dithering`, `--keep-exif`, `--format`) and the encoders in use (the content of the pngquant/oxipng/cjpeg/avifenc binaries, plus the Pillow version). Changing `--workers`, `--recursive`, `--include` or `--exclude` does not invalidate anything, and renaming or moving a file still hits.
198
+ - Only successful results are stored, never failures. A corrupt or truncated entry is treated as a miss and overwritten.
199
+ - The cache directory must not be inside `--source` or `--output` (equal to either is rejected too; a cache dir that merely *contains* `--output` is allowed). Only files matching the cache's own naming scheme (`<64 hex>.<format>` inside a two-hex-digit subfolder) are counted or evicted, so pointing `--cache-dir` at a directory that already holds other files leaves them alone.
200
+ - After each run the cache is trimmed to `--cache-max-size-mb` (default 1024 MB, `0` = unlimited) by deleting the least recently used entries first. Entries whose source image no longer exists are never hit again, so they age out on their own.
201
+ - The compression pipeline is covered by byte-determinism tests (`tests/test_determinism.py`); the cache is only valid because the same input and settings always produce the same bytes.
202
+ - AVIF cache hits need a Pillow build that can read AVIF (Pillow >= 11.3 with libavif; the official wheels bundle it and both `pyproject.toml` and `requirements.txt` pin that floor). Without AVIF read support the run warns on stderr and AVIF entries are never served.
203
+ - Entries written during a run are protected from that same run's eviction, so a run never deletes the results it just wrote (the cache may transiently sit above the cap; on the next run they are ordinary LRU candidates and, being the newest, are evicted last). A single entry larger than `--cache-max-size-mb` can never fit under the cap and is evicted once it is no longer protected; the run warns on stderr whenever it cannot get the cache back under the cap.
204
+ - Stale temporary files from crashed writers are swept at the end of every run, independent of the size cap.
205
+
206
+ ### Filtering with --exclude / --include
207
+
208
+ ```
209
+ image-optimizer --source ./raw --output ./out --exclude "*.bak" --exclude "drafts/*"
210
+ image-optimizer --source ./raw --output ./out --include "icons/*" --exclude "*_old.png"
211
+ ```
212
+
213
+ - A pattern without `/` is matched against the file name at any depth (`*.bak` also hits `sub/dir/a.bak`). A pattern with `/` is matched against the path relative to `--source`, written with forward slashes (`drafts/*`, `icons/*.png`).
214
+ - Matching is case-insensitive on every platform, and `*` also matches `/` (`drafts/*` covers `drafts/old/a.png`).
215
+ - With `--include`, a file must match at least one include pattern. `--exclude` is applied afterwards and always wins when both match.
216
+ - Patterns match paths relative to `--source`: to filter a whole directory use `drafts/*` (a bare `drafts/` matches nothing), and `./`-prefixed or absolute patterns never match.
217
+ - Excluded files are not compressed, produce no output and never count as failures.
218
+
219
+ ### Machine-readable report (--json)
220
+
221
+ With `--json`, the final report is a single JSON object on stdout and all human-readable output (progress lines, summary, warnings) goes to stderr, so stdout can be piped straight into a parser:
222
+
223
+ ```
224
+ image-optimizer --source ./raw --output ./out --json | jq .summary
225
+ ```
226
+
227
+ ```json
228
+ {
229
+ "files": [
230
+ {"rel": "icons/a.png", "output_name": "a.png", "original_size": 20480,
231
+ "compressed_size": 5120, "status": "compressed", "error": null}
232
+ ],
233
+ "summary": {"total": 1, "compressed": 1, "cached": 0, "excluded": 0, "failed": 0,
234
+ "kept_original": 0, "original_size": 20480, "compressed_size": 5120,
235
+ "saved_percent": 75.0}
236
+ }
237
+ ```
238
+
239
+ `status` is one of `compressed`, `cached` (served from `--cache-dir`), `kept_original` (the result was not smaller, so the original's pixels were kept with metadata stripped), `excluded` or `failed`. Size totals and `saved_percent` cover the successful statuses; `total` counts every scanned file, excluded ones included. The exit code is unchanged: `1` only if a file failed. Setup errors (bad arguments, missing `--source`, an `--output` directory that cannot be created) exit `1` with a message on stderr and no JSON.
240
+
241
+ ## Configuration
242
+
243
+ Command-line flags:
244
+
245
+ ```
246
+ image-optimizer --host 127.0.0.1 --port 8090 --workers 4 --dir "D:\screenshots"
247
+ ```
248
+
249
+ - `--host` — listen address (default `127.0.0.1`, see Security below)
250
+ - `--port` — listen port (default `8090`; if taken, the next free port is used automatically)
251
+ - `--workers` — how many images to compress concurrently (default `4`).
252
+ Lower this if pngquant/oxipng are already maxing out your CPU; raise it on a
253
+ many-core machine for faster batches.
254
+ - `--thumbnail-workers` — how many images to thumbnail concurrently during a
255
+ scan (default `4`). Independent from `--workers`, so a scan's I/O-bound
256
+ thumbnailing can be tuned separately from CPU-bound compression.
257
+ - `--dir` — auto-scan this folder on startup (opens the web UI with results pre-loaded)
258
+ - `--recursive` / `--no-recursive` — when used with `--dir` or `--source`,
259
+ whether to scan subfolders too (default `--recursive`, the historical
260
+ behavior). Pass `--no-recursive` to scan only the top level.
261
+
262
+ For settings you don't want to type every time, either use the **in-app
263
+ settings panel** (gear icon in the header — changes persist to
264
+ `config.json`; host/port/workers changes require a restart) or create a
265
+ `config.json` by hand in `~/.image-optimizer/` (that's
266
+ `%USERPROFILE%\.image-optimizer\config.json` on Windows, or
267
+ `~/.image-optimizer/config.json` on macOS/Linux — the same folder on every
268
+ OS, and the same one `recent.json` already lives in). Copy
269
+ [`config.example.json`](config.example.json) there and edit it, or start
270
+ from scratch with:
271
+
272
+ ```json
273
+ {
274
+ "host": "127.0.0.1",
275
+ "port": 8090,
276
+ "concurrent_workers": 4,
277
+ "thumbnail_workers": 4,
278
+ "workspace_cleanup_delay": 10.0,
279
+ "session_idle_timeout_hours": 4
280
+ }
281
+ ```
282
+
283
+ Other flags:
284
+
285
+ - `workspace_cleanup_delay` — seconds to wait before deleting a workspace after
286
+ it's replaced by a new scan/upload (default `10.0`). Files aren't deleted
287
+ immediately so an in-flight request — e.g. a ZIP download or an image still
288
+ loading in another tab — has time to finish before they disappear out from
289
+ under it. Raise this if you routinely have slow downloads running when you
290
+ start a new scan; lower it to free disk space sooner.
291
+ - `session_idle_timeout_hours` — how long a browser session (and its scan
292
+ results, in-progress state, and temp workspace) is kept after you stop
293
+ using it before being cleaned up automatically (default `4`). Each browser
294
+ tab/session is tracked separately so multiple tabs don't interfere with
295
+ each other; this controls how long an abandoned one hangs around before
296
+ its temp files are freed. Also sets how long the session cookie itself is
297
+ valid for.
298
+
299
+ All keys are optional — only include the ones you want to change from the
300
+ default (an empty `{}` or a missing file both just mean "use every
301
+ default"). Command-line flags always override `config.json`, which
302
+ overrides the built-in defaults. Invalid values (e.g. a negative worker
303
+ count) are ignored with a startup warning rather than crashing.
304
+
305
+ ## Security
306
+
307
+ This app has no authentication and is meant to run on `127.0.0.1` only (the
308
+ default). It can read any directory you point it at and write to any path
309
+ you specify as the output folder — fine for local, single-user use, but
310
+ **don't** start it with `--host 0.0.0.0` or a LAN address unless you fully
311
+ trust everyone on that network, since there's nothing stopping them from
312
+ reading or writing files on your machine through it.
313
+
314
+ ## Requirements
315
+
316
+ - **pip install:** Python 3.10+ (dependencies are pulled in automatically)
317
+ - **Source install:** `pip install -r requirements.txt`, or `pip install -r requirements.lock`
318
+ for the exact versions this was tested against
319
+ - **PNG compression:** `pngquant` and `oxipng` (PNG-only modes; JPG/WebP output and lossless
320
+ fallbacks don't need them)
321
+ - **JPG output:** `cjpeg` from mozjpeg (keeps JPEG format instead of converting; see `bin/README.md`)
322
+ - **AVIF output:** `avifenc` from libavif (optional — without it the AVIF format simply isn't offered; see `bin/README.md`)
323
+ - **Standalone download:** Windows 10/11 64-bit, macOS on Apple Silicon, or Linux x86-64 (built on Ubuntu 24.04, so it needs a similarly recent glibc); no Python required (all four encoders bundled)
324
+
325
+ ## Encoder binaries
326
+
327
+ The wheel is pure Python: `pngquant` is GPL-3.0-or-later, and every encoder is a
328
+ platform-specific blob, so none of them are redistributed here. On startup the
329
+ app looks for each one on PATH, then in the per-user directory below; whatever
330
+ is still missing gets downloaded from the publisher, verified against a pinned
331
+ SHA-256, and installed there.
332
+
333
+ The digest is the trust anchor: a download that does not match is discarded,
334
+ never executed.
335
+
336
+ | OS | Install location |
337
+ |---|---|
338
+ | Windows | `%LOCALAPPDATA%\ImageOptimizer\bin` |
339
+ | macOS | `~/Library/Application Support/ImageOptimizer/bin` |
340
+ | Linux | `$XDG_DATA_HOME/image-optimizer/bin` (default `~/.local/share/image-optimizer/bin`) |
341
+
342
+ Fetched automatically:
343
+
344
+ - **Windows x64** — all four: pngquant 2.17.0, oxipng 10.1.1, mozjpeg 4.0.3, libavif 1.4.2
345
+ - **macOS / Linux** — oxipng only; the others have no official standalone binary, so they
346
+ come from your package manager (`brew install pngquant oxipng mozjpeg libavif`,
347
+ `apt install pngquant oxipng mozjpeg libavif-bin`)
348
+
349
+ Offline, behind a proxy, or on an air-gapped network:
350
+
351
+ - `image-optimizer --no-download`, or set `IMAGE_OPTIMIZER_NO_DOWNLOAD=1`
352
+ - the app still starts — WebP output needs no external binary at all, and the UI only
353
+ offers formats it can actually produce right now
354
+ - install manually into the directory above (PATH is searched first), and use
355
+ `--force-download` later to replace a pinned copy
356
+ - startup prints the exact URL, target path and expected SHA-256 for anything it
357
+ could not fetch
358
+
359
+ ## Project Structure
360
+
361
+ ```
362
+ image-optimizer/
363
+ ├── image_optimizer/ # Python web application (import package)
364
+ │ ├── main.py # FastAPI server & routes
365
+ │ ├── optimizer.py # pngquant/oxipng/cjpeg/avifenc orchestration
366
+ │ ├── binaries.py # first-run download + SHA-256 verification
367
+ │ ├── watcher.py # Watch Mode directory poller
368
+ │ ├── models.py # Pydantic request models
369
+ │ └── templates/ # HTML/CSS/JS frontend (single-page app with i18n)
370
+ ├── assets/ # Logo, icons, banner images
371
+ ├── bin/ # Local binary drop-in folder (dev/source runs)
372
+ ├── tests/ # pytest test suite
373
+ ├── build_exe.py # PyInstaller build script (onefile mode)
374
+ ├── pyproject.toml # pip-installable package config
375
+ ├── requirements.txt
376
+ └── start.bat
377
+ ```
378
+
379
+ ## License
380
+
381
+ MIT for this project's own code.
382
+
383
+ The pip package redistributes no third-party binaries. The executables it
384
+ downloads are unmodified upstream releases and stay under their own licenses —
385
+ pngquant (GPL-3.0-or-later), oxipng (MIT), mozjpeg's cjpeg (IJG + BSD-3-Clause),
386
+ libavif's avifenc (BSD-2-Clause) — each fetched from its own publisher, with
387
+ source links in `bin/README.md`. The Windows standalone exe bundles them, so
388
+ redistributing that exe carries their notice requirements.
@@ -0,0 +1,16 @@
1
+ image_optimizer/__init__.py,sha256=9xId_4lF6fB78Ko8-Ap5lWLW6oNRJ2gcIKWy04tAzWI,94
2
+ image_optimizer/__main__.py,sha256=KTpEa4_JVA6yRWMVGuAUZq3Y_QpZnJbmVQw4ZUxT168,45
3
+ image_optimizer/binaries.py,sha256=mCxYl1t7zySeICAD_jU_cp7YLnY87C5UUKgPubnvdYc,17433
4
+ image_optimizer/cache.py,sha256=q7QPs4YZZKKmfE_6a5JmGoI9eHE_WgnXKocFGOkNPtY,15448
5
+ image_optimizer/main.py,sha256=tecvs8Ty8S1l9BDy817MAOGWm1v_eJxMR2cODYYdaIA,180488
6
+ image_optimizer/models.py,sha256=WfssVC0RtFWwq5cHJvQg_YDqThqxwOHjgprpipg6zJI,6003
7
+ image_optimizer/optimizer.py,sha256=AknoX_H4jIadtT7IVv5j6qfz9BuHc4yE_Oa0Sz4uCY8,64670
8
+ image_optimizer/watcher.py,sha256=XkYREh4guzgZOcdUp4EXUyMQISX3OrxWiCHKTBJapD8,8022
9
+ image_optimizer/templates/favicon.ico,sha256=2IAK51qKf0cYWv6fzjbORkzaPxEkil2a4x4PO--_TuI,15086
10
+ image_optimizer/templates/index.html,sha256=uWC2TCwo43EZpb-KLBjEAW3zf76Uxry70KsqGLxTBZM,151715
11
+ image_optimizer_webui-1.1.0.dist-info/licenses/LICENSE,sha256=HZurQOlH5l07thjuE10-77FfnZrBx2POoChouSfjlDg,1072
12
+ image_optimizer_webui-1.1.0.dist-info/METADATA,sha256=LhjaCGS1Zho0RYDf8otg5xBzNvYE1TZ4K-hM_zT1JIg,23389
13
+ image_optimizer_webui-1.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
14
+ image_optimizer_webui-1.1.0.dist-info/entry_points.txt,sha256=yUB9Wi7I3DQ_fbFZRCC-wSr6F5YDj23dNwG1aAbX0ko,62
15
+ image_optimizer_webui-1.1.0.dist-info/top_level.txt,sha256=aSZWhxo-Lb3TqwjtJ-72vW5Mu2nDDgIUu8eBVnjdL1I,16
16
+ image_optimizer_webui-1.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ image-optimizer = image_optimizer.main:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Image Optimizer
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
+ image_optimizer