Three-month batch sync from internal repo (~80 commits) covering Tracks F.5a, F.7e, F.8, F.17, F.18, F.X. WordPress media pipeline - Pillow-based optimization, AI image generation (OpenAI / Stability / Replicate / Google Nano Banana / OpenRouter), chunked + resumable uploads, bulk delete/reassign, idempotent retries. Capability discovery (F.7e) - Per-site credential probe + adapters for WordPress / WooCommerce / Gitea, tier-fit unions granted ∪ roles, capability badge UI with HTMX partial re-check, install hint in every companion-unreachable error. Companion plugin overhaul - Renamed wordpress-plugin/airano-mcp-seo-bridge → wordpress-plugin/airano-mcp-bridge. - Eight new endpoints: /capabilities, /bulk-meta, /export, /cache-purge, /transient-flush, /site-health, /audit-hook, /upload-and-attach. - wp.org Plugin Check pass: i18n, WP_Filesystem, scheme allowlist on audit-hook URL. Other - Gitea ergonomics (F.17): batch files, tree, search, compare, releases, fork. - Opportunistic bcrypt upgrade for legacy SHA-256 admin keys (F.8). - n8n refactor: structured errors, capability probe, missing tools backfilled. - Idempotency-Key dedup for AI media upload retries; WP client fast-fails on unreachable sites. Docs - README + CLAUDE.md drop the fixed "633 tools" claim. The total grows with each release; per-plugin approximations + dashboard-surfaced counts replace it. - Tools/Tests badges removed in favour of "Plugins: 10". Deployment - PyPI mirror chain, optional BUILD_HTTP_PROXY, Alpine→Yandex apk mirror, Debian-slim Plan-B Dockerfile, mirror.gcr.io variant. CI - Black + Ruff clean on Python 3.12; pytest tests/ green. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
197 lines
7.0 KiB
Python
197 lines
7.0 KiB
Python
"""F.5a.2 / F.5a.8.1: Image optimization pipeline using Pillow.
|
|
|
|
Defaults for web publishing: JPEG quality 85, PNG→JPEG threshold via opacity check,
|
|
max long edge 2560 px, EXIF strip, animated GIF preserved untouched.
|
|
|
|
F.5a.8.1 adds an optional format conversion stage: when ``convert_to`` is
|
|
``"webp"`` or ``"avif"`` (or the env var ``WP_MEDIA_CONVERT_TO`` is set),
|
|
raster inputs are re-encoded in that modern format regardless of source
|
|
type. Transparency is preserved; animated GIFs are still left untouched.
|
|
|
|
Returns the (possibly reduced) bytes and the (possibly updated) MIME type.
|
|
Non-raster types (pdf, svg, video, audio) pass through unchanged.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import io
|
|
import logging
|
|
import os
|
|
|
|
_logger = logging.getLogger("mcphub.wordpress.media.optimize")
|
|
|
|
try:
|
|
from PIL import Image, ImageOps # type: ignore
|
|
except Exception: # pragma: no cover
|
|
Image = None # type: ignore
|
|
ImageOps = None # type: ignore
|
|
|
|
_DEFAULT_MAX_EDGE = int(os.environ.get("WP_MEDIA_MAX_EDGE", "2560"))
|
|
_DEFAULT_JPEG_QUALITY = int(os.environ.get("WP_MEDIA_JPEG_QUALITY", "85"))
|
|
# F.5a.8.1: optional output format override.
|
|
# "" → no conversion (current default, keeps source format)
|
|
# "webp" → convert raster images to image/webp
|
|
# "avif" → convert raster images to image/avif (requires Pillow≥9.2 with AVIF)
|
|
_DEFAULT_CONVERT_TO = os.environ.get("WP_MEDIA_CONVERT_TO", "").strip().lower()
|
|
|
|
_RASTER_MIMES = {"image/jpeg", "image/png", "image/webp", "image/bmp", "image/tiff"}
|
|
|
|
# Format map for the convert_to override. Values are (Pillow format, output MIME).
|
|
_CONVERT_TO_FORMATS: dict[str, tuple[str, str]] = {
|
|
"webp": ("WEBP", "image/webp"),
|
|
"avif": ("AVIF", "image/avif"),
|
|
}
|
|
|
|
|
|
def _avif_supported() -> bool:
|
|
"""Return True if the running Pillow actually decodes/encodes AVIF.
|
|
|
|
We check at call time rather than import time so environments that
|
|
upgrade Pillow without restarting still see support as it becomes
|
|
available.
|
|
"""
|
|
if Image is None:
|
|
return False
|
|
# Pillow registers the extension lazily; probing for a writer is more
|
|
# reliable than checking the features module (which doesn't list AVIF
|
|
# on every version).
|
|
try:
|
|
return "AVIF" in Image.registered_extensions().values()
|
|
except Exception: # pragma: no cover - defensive
|
|
return False
|
|
|
|
|
|
def optimize(
|
|
data: bytes,
|
|
mime_hint: str | None,
|
|
*,
|
|
max_edge: int = _DEFAULT_MAX_EDGE,
|
|
jpeg_quality: int = _DEFAULT_JPEG_QUALITY,
|
|
strip_exif: bool = True,
|
|
convert_to: str | None = None,
|
|
) -> tuple[bytes, str | None]:
|
|
"""Resize/recompress raster images.
|
|
|
|
Args:
|
|
data: raw image bytes.
|
|
mime_hint: best-guess MIME from sniff/client; non-raster types are
|
|
passed through unchanged.
|
|
max_edge: long-edge pixel limit (default ``WP_MEDIA_MAX_EDGE`` or 2560).
|
|
jpeg_quality: q parameter for JPEG / WebP / AVIF encoders.
|
|
strip_exif: when True, apply ``ImageOps.exif_transpose`` to bake in
|
|
rotation then drop the metadata.
|
|
convert_to: force output format regardless of source. ``"webp"`` or
|
|
``"avif"``; ``None`` or ``""`` falls back to
|
|
``WP_MEDIA_CONVERT_TO`` then to source-format heuristics. When
|
|
AVIF is requested but Pillow lacks AVIF support, falls back to
|
|
WebP rather than silently writing the source bytes.
|
|
|
|
Returns:
|
|
``(new_bytes, new_mime_or_original)``. If optimization produced
|
|
larger output without resizing, the original bytes are returned.
|
|
"""
|
|
if Image is None:
|
|
return data, mime_hint
|
|
|
|
if mime_hint and mime_hint not in _RASTER_MIMES:
|
|
return data, mime_hint
|
|
|
|
try:
|
|
img = Image.open(io.BytesIO(data))
|
|
except Exception:
|
|
return data, mime_hint
|
|
|
|
# Preserve animated GIFs untouched (single-frame re-encode would break them)
|
|
if getattr(img, "is_animated", False):
|
|
return data, mime_hint
|
|
|
|
fmt = (img.format or "").upper() # capture BEFORE exif_transpose strips .format
|
|
|
|
try:
|
|
img = ImageOps.exif_transpose(img) if strip_exif else img
|
|
except Exception:
|
|
pass
|
|
|
|
w, h = img.size
|
|
long_edge = max(w, h)
|
|
|
|
resized = False
|
|
if long_edge > max_edge:
|
|
scale = max_edge / long_edge
|
|
new_size = (max(1, int(w * scale)), max(1, int(h * scale)))
|
|
img = img.resize(new_size, Image.LANCZOS)
|
|
resized = True
|
|
|
|
# F.5a.8.1: explicit convert_to wins over the env default.
|
|
requested_convert = (convert_to or _DEFAULT_CONVERT_TO or "").strip().lower()
|
|
if requested_convert == "avif" and not _avif_supported():
|
|
_logger.info("AVIF requested but Pillow lacks AVIF support; falling back to WebP.")
|
|
requested_convert = "webp"
|
|
|
|
has_alpha = img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info)
|
|
|
|
if requested_convert in _CONVERT_TO_FORMATS:
|
|
out_fmt, out_mime = _CONVERT_TO_FORMATS[requested_convert]
|
|
# Both WebP and AVIF support alpha; convert palette images to RGBA/RGB
|
|
# so the encoder has a consistent colour model.
|
|
if img.mode == "P":
|
|
img = img.convert("RGBA" if has_alpha else "RGB")
|
|
elif img.mode == "LA":
|
|
img = img.convert("RGBA")
|
|
elif img.mode == "L":
|
|
img = img.convert("RGB")
|
|
elif fmt == "PNG" and not has_alpha:
|
|
# Opaque PNG → JPEG is typically smaller
|
|
out_fmt = "JPEG"
|
|
out_mime = "image/jpeg"
|
|
if img.mode != "RGB":
|
|
img = img.convert("RGB")
|
|
elif fmt == "JPEG":
|
|
out_fmt = "JPEG"
|
|
out_mime = "image/jpeg"
|
|
if img.mode != "RGB":
|
|
img = img.convert("RGB")
|
|
elif fmt == "WEBP":
|
|
out_fmt = "WEBP"
|
|
out_mime = "image/webp"
|
|
elif fmt == "PNG":
|
|
out_fmt = "PNG"
|
|
out_mime = "image/png"
|
|
else:
|
|
# BMP/TIFF etc — convert to JPEG for web delivery
|
|
out_fmt = "JPEG"
|
|
out_mime = "image/jpeg"
|
|
if img.mode != "RGB":
|
|
img = img.convert("RGB")
|
|
|
|
buf = io.BytesIO()
|
|
save_kwargs: dict = {"optimize": True}
|
|
if out_fmt == "JPEG":
|
|
save_kwargs.update({"quality": jpeg_quality, "progressive": True})
|
|
elif out_fmt == "WEBP":
|
|
save_kwargs.update({"quality": jpeg_quality, "method": 6})
|
|
elif out_fmt == "AVIF":
|
|
save_kwargs.update({"quality": jpeg_quality})
|
|
img.save(buf, format=out_fmt, **save_kwargs)
|
|
new_bytes = buf.getvalue()
|
|
|
|
# Explicit format conversion is honoured even if the converted bytes
|
|
# are larger than the source (the caller asked for a format switch on
|
|
# purpose — e.g. to serve WebP regardless). The size guard only applies
|
|
# to the implicit recompression path.
|
|
if not requested_convert and not resized and len(new_bytes) >= len(data):
|
|
return data, mime_hint
|
|
|
|
_logger.debug(
|
|
"optimized %s %dx%d %dB -> %s %dB (resized=%s, convert=%s)",
|
|
fmt,
|
|
w,
|
|
h,
|
|
len(data),
|
|
out_fmt,
|
|
len(new_bytes),
|
|
resized,
|
|
requested_convert or "-",
|
|
)
|
|
return new_bytes, out_mime
|