Skip to content

"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/

Python

fix: replace Pillow with GIMP-native Script-Fu rendering backend

harsh2c73b8091523
diff --git a/gimp/agent-harness/cli_anything/gimp/core/export.py b/gimp/agent-harness/cli_anything/gimp/core/export.py
index f137efe47..0e2dd7a13 100644
--- a/gimp/agent-harness/cli_anything/gimp/core/export.py
+++ b/gimp/agent-harness/cli_anything/gimp/core/export.py
@@ -2,12 +2,14 @@
This module handles the critical "rendering" step: flattening the layer stack
with all filters applied and exporting to various image formats.
+
+Rendering backends (tried in order):
+ 1. GIMP Script-Fu batch mode – uses the real GIMP engine (``gimp -i -b``)
+ 2. Pillow (PIL) – pure-Python fallback when GIMP is absent
"""
import os
from typing import Dict, Any, Optional, Tuple
-from PIL import Image, ImageEnhance, ImageFilter, ImageOps, ImageDraw, ImageFont
-import numpy as np
# Export presets
@@ -59,8 +61,47 @@ def render(
) -> Dict[str, Any]:
"""Render the project: flatten layers, apply filters, export.
- This is the main rendering pipeline.
+ Tries the GIMP Script-Fu backend first (native image processing via
+ ``gimp -i -b``). Falls back to Pillow when GIMP is not installed.
"""
+ # --- GIMP-native rendering (preferred) ---
+ try:
+ from cli_anything.gimp.utils.gimp_backend import is_available, render_project
+ if is_available():
+ return render_project(
+ project, output_path,
+ preset=preset, overwrite=overwrite,
+ quality=quality, format_override=format_override,
+ )
+ except Exception:
+ pass # fall through to Pillow
+
+ # --- Pillow fallback ---
+ return _render_via_pillow(
+ project, output_path,
+ preset=preset, overwrite=overwrite,
+ quality=quality, format_override=format_override,
+ )
+
+
+def _render_via_pillow(
+ project: Dict[str, Any],
+ output_path: str,
+ preset: str = "png",
+ overwrite: bool = False,
+ quality: Optional[int] = None,
+ format_override: Optional[str] = None,
+) -> Dict[str, Any]:
+ """Render the project using Pillow (fallback when GIMP is absent)."""
+ try:
+ from PIL import Image, ImageDraw, ImageFont
+ except ImportError:
+ raise RuntimeError(
+ "Neither GIMP nor Pillow is available. Install one of:\n"
+ " apt install gimp # recommended\n"
+ " pip install Pillow # fallback"
+ )
+
if os.path.exists(output_path) and not overwrite:
raise FileExistsError(f"Output file exists: {output_path}. Use --overwrite.")
@@ -69,7 +110,6 @@ def render(
bg_color = canvas.get("background", "#ffffff")
mode = canvas.get("color_mode", "RGB")
- # Determine output format
if format_override:
fmt = format_override.upper()
save_params = {}
@@ -83,10 +123,8 @@ def render(
if quality is not None:
save_params["quality"] = quality
- # Create canvas
if mode in ("RGBA", "LA"):
canvas_img = Image.new("RGBA", (cw, ch), (0, 0, 0, 0))
- # Draw background if not transparent
if bg_color.lower() != "transparent":
bg = Image.new("RGBA", (cw, ch), bg_color)
canvas_img = Image.alpha_composite(canvas_img, bg)
@@ -95,7 +133,6 @@ def render(
layers = project.get("layers", [])
- # Composite layers bottom-to-top
for layer in reversed(layers):
if not layer.get("visible", True):
continue
@@ -104,10 +141,8 @@ def render(
if layer_img is None:
continue
- # Apply filters
layer_img = _apply_filters(layer_img, layer.get("filters", []))
- # Apply scaling if marked
if "_scale_x" in layer:
new_w = max(1, round(layer_img.width * layer["_scale_x"]))
new_h = max(1, round(layer_img.height * layer["_scale_y"]))
@@ -118,23 +153,17 @@ def render(
resample = resample_map.get(layer.get("_resample", "lanczos"), Image.LANCZOS)
layer_img = layer_img.resize((new_w, new_h), resample)
- # Position on canvas
ox = layer.get("offset_x", 0)
oy = layer.get("offset_y", 0)
-
- # Apply opacity
opacity = layer.get("opacity", 1.0)
- # Apply blend mode and composite
canvas_img = _composite_layer(
canvas_img, layer_img, ox, oy, opacity,
layer.get("blend_mode", "normal")
)
- # Convert mode for export
if fmt == "JPEG":
if canvas_img.mode == "RGBA":
- # Flatten alpha onto white background for JPEG
bg = Image.new("RGB", canvas_img.size, (255, 255, 255))
bg.paste(canvas_img, mask=canvas_img.split()[3])
canvas_img = bg
@@ -143,15 +172,12 @@ def render(
elif fmt == "GIF":
canvas_img = canvas_img.convert("P", palette=Image.ADAPTIVE, colors=256)
- # Set DPI
dpi = canvas.get("dpi", 72)
save_params["dpi"] = (dpi, dpi)
- # Save
os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
canvas_img.save(output_path, format=fmt, **save_params)
- # Verify output
result = {
"output": os.path.abspath(output_path),
"format": fmt,
@@ -159,14 +185,17 @@ def render(
"file_size": os.path.getsize(output_path),
"file_size_human": _human_size(os.path.getsize(output_path)),
"preset": preset,
+ "method": "pillow",
"layers_rendered": sum(1 for l in layers if l.get("visible", True)),
}
return result
-def _load_layer(layer: Dict[str, Any], canvas_w: int, canvas_h: int) -> Optional[Image.Image]:
- """Load a layer's content as a PIL Image."""
+def _load_layer(layer, canvas_w, canvas_h):
+ """Load a layer's content as a PIL Image (Pillow fallback path)."""
+ from PIL import Image
+
layer_type = layer.get("type", "image")
if layer_type == "image":
@@ -174,7 +203,6 @@ def _load_layer(layer: Dict[str, Any], canvas_w: int, canvas_h: int) -> Optional
if source and os.path.exists(source):
img = Image.open(source).convert("RGBA")
return img
- # Blank layer with fill
fill = layer.get("fill", "transparent")
w = layer.get("width", canvas_w)
h = layer.get("height", canvas_h)
@@ -199,8 +227,10 @@ def _load_layer(layer: Dict[str, Any], canvas_w: int, canvas_h: int) -> Optional
return None
-def _render_text_layer(layer: Dict[str, Any], canvas_w: int, canvas_h: int) -> Image.Image:
- """Render a text layer to an image."""
+def _render_text_layer(layer, canvas_w, canvas_h):
+ """Render a text layer to an image (Pillow fallback path)."""
+ from PIL import Image, ImageDraw, ImageFont
+
text = layer.get("text", "")
font_size = layer.get("font_size", 24)
color = layer.get("color", "#000000")
@@ -222,8 +252,8 @@ def _render_text_layer(layer: Dict[str, Any], canvas_w: int, canvas_h: int) -> I
return img
-def _apply_filters(img: Image.Image, filters: list) -> Image.Image:
- """Apply a chain of filters to an image."""
+def _apply_filters(img, filters):
+ """Apply a chain of filters to an image (Pillow fallback path)."""
for f in filters:
name = f["name"]
params = f.get("params", {})
@@ -231,24 +261,22 @@ def _apply_filters(img: Image.Image, filters: list) -> Image.Image:
return img
-def _apply_single_filter(img: Image.Image, name: str, params: Dict) -> Image.Image:
- """Apply a single filter to an image."""
+def _apply_single_filter(img, name, params):
+ """Apply a single filter to an image (Pillow fallback path)."""
+ from PIL import Image, ImageEnhance, ImageFilter, ImageOps
from cli_anything.gimp.core.filters import FILTER_REGISTRY
if name not in FILTER_REGISTRY:
- return img # Skip unknown filters
+ return img
spec = FILTER_REGISTRY[name]
engine = spec["engine"]
- # Convert to appropriate mode for processing
- original_mode = img.mode
- needs_rgba = original_mode == "RGBA"
+ needs_rgba = img.mode == "RGBA"
if engine == "pillow_enhance":
cls_name = spec["pillow_class"]
factor = params.get("factor", 1.0)
- # ImageEnhance needs RGB, handle RGBA by separating alpha
if needs_rgba:
alpha = img.split()[3]
rgb = img.convert("RGB")
@@ -353,8 +381,10 @@ def _apply_single_filter(img: Image.Image, name: str, params: Dict) -> Image.Ima
return img
-def _apply_sepia(img: Image.Image, strength: float = 0.8) -> Image.Image:
- """Apply sepia tone effect."""
+def _apply_sepia(img, strength=0.8):
+ """Apply sepia tone effect (Pillow fallback path)."""
+ from PIL import Image as PILImage, ImageOps
+
needs_rgba = img.mode == "RGBA"
if needs_rgba:
alpha = img.split()[3]
@@ -363,9 +393,7 @@ def _apply_sepia(img: Image.Image, strength: float = 0.8) -> Image.Image:
sepia = ImageOps.colorize(gray, "#704214", "#C0A080")
if strength < 1.0:
- # Blend with original
rgb = img.convert("RGB")
- from PIL import Image as PILImage
sepia = PILImage.blend(rgb, sepia, strength)
if needs_rgba:
@@ -375,44 +403,37 @@ def _apply_sepia(img: Image.Image, strength: float = 0.8) -> Image.Image:
return sepia
-def _composite_layer(
- base: Image.Image,
- layer: Image.Image,
- offset_x: int,
- offset_y: int,
- opacity: float,
- blend_mode: str,
-) -> Image.Image:
- """Composite a layer onto the base canvas with blend mode and opacity."""
- # Ensure both are RGBA for compositing
+def _composite_layer(base, layer, offset_x, offset_y, opacity, blend_mode):
+ """Composite a layer onto the base canvas (Pillow fallback path)."""
+ from PIL import Image
+
if base.mode != "RGBA":
base = base.convert("RGBA")
if layer.mode != "RGBA":
layer = layer.convert("RGBA")
- # Apply opacity to layer
if opacity < 1.0:
alpha = layer.split()[3]
alpha = alpha.point(lambda a: int(a * opacity))
layer.putalpha(alpha)
- # Create a full-canvas-sized version of the layer at the correct offset
layer_canvas = Image.new("RGBA", base.size, (0, 0, 0, 0))
layer_canvas.paste(layer, (offset_x, offset_y))
if blend_mode == "normal":
return Image.alpha_composite(base, layer_canvas)
- # For other blend modes, we need numpy
try:
return _blend_with_mode(base, layer_canvas, blend_mode)
except ImportError:
- # Fallback to normal if numpy not available
return Image.alpha_composite(base, layer_canvas)
-def _blend_with_mode(base: Image.Image, layer: Image.Image, mode: str) -> Image.Image:
- """Apply blend mode using numpy pixel math."""
+def _blend_with_mode(base, layer, mode):
+ """Apply blend mode using numpy pixel math (Pillow fallback path)."""
+ import numpy as np
+ from PIL import Image
+
base_arr = np.array(base, dtype=np.float64)
layer_arr = np.array(layer, dtype=np.float64)
@@ -467,7 +488,8 @@ def _blend_with_mode(base: Image.Image, layer: Image.Image, mode: str) -> Image.
result = np.concatenate([result_rgb, result_alpha], axis=2)
result = np.clip(result * 255, 0, 255).astype(np.uint8)
- return Image.fromarray(result, "RGBA")
+ from PIL import Image as _Image
+ return _Image.fromarray(result, "RGBA")
def _human_size(nbytes: int) -> str:
diff --git a/gimp/agent-harness/cli_anything/gimp/core/layers.py b/gimp/agent-harness/cli_anything/gimp/core/layers.py
index 934a9f348..8a0d85f4d 100644
--- a/gimp/agent-harness/cli_anything/gimp/core/layers.py
+++ b/gimp/agent-harness/cli_anything/gimp/core/layers.py
@@ -2,6 +2,7 @@
import os
import copy
+import struct
from typing import Dict, Any, List, Optional
@@ -114,12 +115,10 @@ def add_from_file(
layer_name = name or os.path.basename(path)
- # Try to get image dimensions
- try:
- from PIL import Image
- with Image.open(path) as img:
- w, h = img.size
- except Exception:
+ dims = _read_image_dimensions(path)
+ if dims:
+ w, h = dims
+ else:
w = project["canvas"]["width"]
h = project["canvas"]["height"]
@@ -247,3 +246,134 @@ def merge_down(project: Dict[str, Any], index: int) -> None:
if index >= len(layers) - 1:
raise ValueError("Cannot merge down the bottom layer")
project["_merge_down_pending"] = index
+
+
+def _read_image_dimensions(path: str) -> Optional[tuple]:
+ """Read image width/height from file headers without external dependencies.
+
+ Supports PNG, JPEG, GIF, BMP, WEBP, and TIFF.
+ Returns (width, height) or None if the format is unrecognised.
+ """
+ try:
+ with open(path, "rb") as f:
+ header = f.read(32)
+
+ if len(header) < 8:
+ return None
+
+ # PNG: 8-byte signature, then IHDR chunk with w/h at bytes 16-24
+ if header[:8] == b"\x89PNG\r\n\x1a\n":
+ w, h = struct.unpack(">II", header[16:24])
+ return (w, h)
+
+ # GIF: signature + logical screen descriptor
+ if header[:6] in (b"GIF87a", b"GIF89a"):
+ w, h = struct.unpack("<HH", header[6:10])
+ return (w, h)
+
+ # BMP: 'BM' header, w/h as signed int32 at bytes 18-26
+ if header[:2] == b"BM" and len(header) >= 26:
+ w, h = struct.unpack("<ii", header[18:26])
+ return (w, abs(h))
+
+ # TIFF: byte-order mark then magic 42
+ if header[:4] in (b"II\x2a\x00", b"MM\x00\x2a"):
+ return _read_tiff_dimensions(path, header)
+
+ # JPEG: starts with SOI marker 0xFFD8
+ if header[:2] == b"\xff\xd8":
+ return _read_jpeg_dimensions(path)
+
+ # WEBP: RIFF container with 'WEBP' fourcc
+ if header[:4] == b"RIFF" and header[8:12] == b"WEBP":
+ return _read_webp_dimensions(path)
+
+ except (OSError, struct.error):
+ pass
+ return None
+
+
+def _read_jpeg_dimensions(path: str) -> Optional[tuple]:
+ """Scan JPEG markers for the SOF frame that carries width/height."""
+ try:
+ with open(path, "rb") as f:
+ f.read(2) # skip SOI
+ while True:
+ b = f.read(1)
+ if not b:
+ break
+ if b != b"\xff":
+ continue
+ marker = f.read(1)
+ if not marker:
+ break
+ code = marker[0]
+ if code == 0xD9: # EOI
+ break
+ # Restart markers and bare 0xFF padding carry no length
+ if code in range(0xD0, 0xD8) or code == 0x00 or code == 0x01:
+ continue
+ length_data = f.read(2)
+ if len(length_data) < 2:
+ break
+ seg_len = struct.unpack(">H", length_data)[0]
+ # SOF0-SOF3 contain the image dimensions
+ if 0xC0 <= code <= 0xC3:
+ sof_data = f.read(min(seg_len - 2, 5))
+ if len(sof_data) >= 5:
+ h, w = struct.unpack(">HH", sof_data[1:5])
+ return (w, h)
+ break
+ f.seek(seg_len - 2, 1)
+ except (OSError, struct.error):
+ pass
+ return None
+
+
+def _read_webp_dimensions(path: str) -> Optional[tuple]:
+ """Read WebP dimensions from the VP8/VP8L chunk header."""
+ try:
+ with open(path, "rb") as f:
+ data = f.read(30)
+ if len(data) < 30:
+ return None
+ chunk = data[12:16]
+ if chunk == b"VP8 ":
+ w = struct.unpack("<H", data[26:28])[0] & 0x3FFF
+ h = struct.unpack("<H", data[28:30])[0] & 0x3FFF
+ return (w, h)
+ if chunk == b"VP8L":
+ bits = struct.unpack("<I", data[21:25])[0]
+ w = (bits & 0x3FFF) + 1
+ h = ((bits >> 14) & 0x3FFF) + 1
+ return (w, h)
+ except (OSError, struct.error):
+ pass
+ return None
+
+
+def _read_tiff_dimensions(path: str, header: bytes) -> Optional[tuple]:
+ """Read TIFF dimensions from the first IFD."""
+ try:
+ big = header[:2] == b"MM"
+ fmt_h, fmt_i = (">H", ">I") if big else ("<H", "<I")
+ ifd_offset = struct.unpack(fmt_i, header[4:8])[0]
+ with open(path, "rb") as f:
+ f.seek(ifd_offset)
+ (n_entries,) = struct.unpack(fmt_h, f.read(2))
+ w = h = None
+ for _ in range(n_entries):
+ entry = f.read(12)
+ if len(entry) < 12:
+ break
+ tag = struct.unpack(fmt_h, entry[0:2])[0]
+ typ = struct.unpack(fmt_h, entry[2:4])[0]
+ if tag == 256: # ImageWidth
+ w = struct.unpack(fmt_i if typ == 4 else fmt_h, entry[8:12 if typ == 4 else 10])[0]
+ elif tag == 257: # ImageLength
+ h = struct.unpack(fmt_i if typ == 4 else fmt_h, entry[8:12 if typ == 4 else 10])[0]
+ if w and h:
+ return (w, h)
+ except (OSError, struct.error):
+ pass
+ return None
diff --git a/gimp/agent-harness/cli_anything/gimp/core/media.py b/gimp/agent-harness/cli_anything/gimp/core/media.py
index 68f0d4ba1..3ec224c6a 100644
--- a/gimp/agent-harness/cli_anything/gimp/core/media.py
+++ b/gimp/agent-harness/cli_anything/gimp/core/media.py
@@ -1,4 +1,9 @@
-"""GIMP CLI - Media file analysis module."""
+"""GIMP CLI - Media file analysis module.
+
+Uses Pillow when available for rich metadata (EXIF, histograms). Falls back
+to pure-Python header parsing for basic dimensions / format detection when
+Pillow is not installed.
+"""
import os
import json
@@ -7,44 +12,53 @@ from typing import Dict, Any, Optional
def probe_image(path: str) -> Dict[str, Any]:
- """Analyze an image file and return metadata."""
+ """Analyze an image file and return metadata.
+
+ Tries Pillow for rich metadata; degrades gracefully to pure-Python
+ header parsing when Pillow is absent.
+ """
if not os.path.exists(path):
raise FileNotFoundError(f"Image file not found: {path}")
- from PIL import Image
-
- info = {
+ info: Dict[str, Any] = {
"path": os.path.abspath(path),
"filename": os.path.basename(path),
"file_size": os.path.getsize(path),
"file_size_human": _human_size(os.path.getsize(path)),
}
+ try:
+ from PIL import Image
+ return _probe_via_pillow(path, info, Image)
+ except ImportError:
+ pass
+
+ return _probe_basic(path, info)
+
+
+def _probe_via_pillow(path: str, info: Dict[str, Any], Image) -> Dict[str, Any]:
+ """Full metadata probe using Pillow."""
try:
with Image.open(path) as img:
info["width"] = img.width
info["height"] = img.height
info["mode"] = img.mode
info["format"] = img.format
- info["format_description"] = img.format_description if hasattr(img, 'format_description') else img.format
+ info["format_description"] = img.format_description if hasattr(img, "format_description") else img.format
info["megapixels"] = f"{img.width * img.height / 1_000_000:.2f}"
- # DPI info
dpi = img.info.get("dpi")
if dpi:
info["dpi"] = {"x": round(dpi[0]), "y": round(dpi[1])}
- # Animation info (GIF, APNG)
info["is_animated"] = getattr(img, "is_animated", False)
if info["is_animated"]:
info["n_frames"] = getattr(img, "n_frames", 1)
- # Color palette
if img.mode == "P":
palette = img.getpalette()
info["palette_colors"] = len(palette) // 3 if palette else 0
- # EXIF data (basic)
exif = img.getexif()
if exif:
exif_data = {}
@@ -60,11 +74,9 @@ def probe_image(path: str) -> Dict[str, Any]:
if exif_data:
info["exif"] = exif_data
- # Image bands/channels
info["channels"] = len(img.getbands())
info["bands"] = list(img.getbands())
- # Bits per pixel estimation
bits_per_channel = {"1": 1, "L": 8, "P": 8, "RGB": 8, "RGBA": 8,
"CMYK": 8, "I": 32, "F": 32, "LA": 8}
bpc = bits_per_channel.get(img.mode, 8)
@@ -76,6 +88,25 @@ def probe_image(path: str) -> Dict[str, Any]:
return info
+def _probe_basic(path: str, info: Dict[str, Any]) -> Dict[str, Any]:
+ """Lightweight probe using pure-Python header parsing (no Pillow)."""
+ from cli_anything.gimp.core.layers import _read_image_dimensions
+
+ dims = _read_image_dimensions(path)
+ if dims:
+ info["width"], info["height"] = dims
+ info["megapixels"] = f"{dims[0] * dims[1] / 1_000_000:.2f}"
+
+ ext = os.path.splitext(path)[1].lower()
+ fmt_map = {
+ ".png": "PNG", ".jpg": "JPEG", ".jpeg": "JPEG",
+ ".gif": "GIF", ".bmp": "BMP", ".webp": "WEBP",
+ ".tiff": "TIFF", ".tif": "TIFF",
+ }
+ info["format"] = fmt_map.get(ext, ext.lstrip(".").upper())
+ return info
+
+
def list_media_in_project(project: Dict[str, Any]) -> list:
"""List all media files referenced in the project."""
media = []
@@ -106,11 +137,17 @@ def check_media(project: Dict[str, Any]) -> Dict[str, Any]:
def get_image_histogram(path: str) -> Dict[str, Any]:
- """Get histogram data for an image."""
+ """Get histogram data for an image. Requires Pillow."""
if not os.path.exists(path):
raise FileNotFoundError(f"Image file not found: {path}")
- from PIL import Image
+ try:
+ from PIL import Image
+ except ImportError:
+ raise RuntimeError(
+ "Histogram analysis requires Pillow. Install it with:\n"
+ " pip install Pillow"
+ )
with Image.open(path) as img:
if img.mode not in ("RGB", "RGBA", "L"):
diff --git a/gimp/agent-harness/cli_anything/gimp/utils/gimp_backend.py b/gimp/agent-harness/cli_anything/gimp/utils/gimp_backend.py
index af60c061f..6a1ba4f3c 100644
--- a/gimp/agent-harness/cli_anything/gimp/utils/gimp_backend.py
+++ b/gimp/agent-harness/cli_anything/gimp/utils/gimp_backend.py
@@ -9,7 +9,7 @@ Requires: gimp (system package)
import os
import shutil
import subprocess
-from typing import Optional
+from typing import Dict, Any, Optional, List
def _script_fu_escape(value: str) -> str:
@@ -219,3 +219,327 @@ def apply_filter_and_export(
"method": "gimp-batch",
"file_size": os.path.getsize(abs_output),
}
+
+
+# ---------------------------------------------------------------------------
+# GIMP availability check
+# ---------------------------------------------------------------------------
+
+def is_available() -> bool:
+ """Return True if GIMP is installed and reachable on $PATH."""
+ try:
+ find_gimp()
+ return True
+ except RuntimeError:
+ return False
+
+
+# ---------------------------------------------------------------------------
+# Blend-mode & filter maps (CLI name → GIMP 2.10+ Script-Fu constant/call)
+# ---------------------------------------------------------------------------
+
+GIMP_BLEND_MODES: Dict[str, str] = {
+ "normal": "LAYER-MODE-NORMAL",
+ "multiply": "LAYER-MODE-MULTIPLY",
+ "screen": "LAYER-MODE-SCREEN",
+ "overlay": "LAYER-MODE-OVERLAY",
+ "soft_light": "LAYER-MODE-SOFTLIGHT",
+ "hard_light": "LAYER-MODE-HARDLIGHT",
+ "difference": "LAYER-MODE-DIFFERENCE",
+ "darken": "LAYER-MODE-DARKEN-ONLY",
+ "lighten": "LAYER-MODE-LIGHTEN-ONLY",
+ "color_dodge": "LAYER-MODE-DODGE",
+ "color_burn": "LAYER-MODE-BURN",
+ "addition": "LAYER-MODE-ADDITION",
+ "subtract": "LAYER-MODE-SUBTRACT",
+ "grain_merge": "LAYER-MODE-GRAIN-MERGE",
+ "grain_extract": "LAYER-MODE-GRAIN-EXTRACT",
+}
+
+# Export-preset → Script-Fu save call. Placeholders: {img}, {drw}, {path}
+_EXPORT_COMMANDS: Dict[str, str] = {
+ "PNG": '(file-png-save RUN-NONINTERACTIVE {img} {drw} "{path}" "{path}" 0 {compress} 1 1 1 1 1)',
+ "JPEG": '(file-jpeg-save RUN-NONINTERACTIVE {img} {drw} "{path}" "{path}" {quality} 0.0 0 0 "" 0 1 0 2)',
+ "BMP": '(file-bmp-save RUN-NONINTERACTIVE {img} {drw} "{path}" "{path}" 0)',
+ "TIFF": '(file-tiff-save RUN-NONINTERACTIVE {img} {drw} "{path}" "{path}" 1)',
+ "GIF": '(file-gif-save RUN-NONINTERACTIVE {img} {drw} "{path}" "{path}" 0 0 0 0)',
+}
+
+
+def _filter_to_script_fu(name: str, params: Dict[str, Any],
+ img_var: str, drw_var: str) -> Optional[str]:
+ """Convert a CLI filter name + params into a Script-Fu expression.
+
+ Returns None when there is no GIMP-native equivalent for *name*.
+ """
+ p = params or {}
+ i, d = img_var, drw_var
+
+ if name == "brightness":
+ val = int((p.get("factor", 1.0) - 1.0) * 127)
+ return f"(gimp-brightness-contrast {d} {val} 0)"
+ if name == "contrast":
+ val = int((p.get("factor", 1.0) - 1.0) * 127)
+ return f"(gimp-brightness-contrast {d} 0 {val})"
+ if name == "saturation":
+ val = int((p.get("factor", 1.0) - 1.0) * 100)
+ return f"(gimp-drawable-hue-saturation {d} HUE-RANGE-ALL 0 0 {val} 0)"
+ if name == "sharpness":
+ amt = max(0.0, p.get("factor", 1.0) - 1.0)
+ return f"(plug-in-unsharp-mask RUN-NONINTERACTIVE {i} {d} 3.0 {amt:.2f} 0)"
+ if name == "gaussian_blur":
+ r = p.get("radius", 2.0)
+ return f"(plug-in-gauss RUN-NONINTERACTIVE {i} {d} {r} {r} 0)"
+ if name == "box_blur":
+ r = p.get("radius", 2.0)
+ return f"(plug-in-gauss RUN-NONINTERACTIVE {i} {d} {r} {r} 1)"
+ if name == "unsharp_mask":
+ r = p.get("radius", 2.0)
+ pct = p.get("percent", 150) / 100.0
+ t = p.get("threshold", 3)
+ return f"(plug-in-unsharp-mask RUN-NONINTERACTIVE {i} {d} {r} {pct:.2f} {t})"
+ if name == "smooth":
+ return f"(plug-in-gauss RUN-NONINTERACTIVE {i} {d} 3 3 0)"
+ if name == "invert":
+ return f"(gimp-drawable-invert {d} FALSE)"
+ if name == "grayscale":
+ return f"(gimp-drawable-desaturate {d} DESATURATE-AVERAGE)"
+ if name == "posterize":
+ bits = p.get("bits", 4)
+ return f"(gimp-drawable-posterize {d} {bits})"
+ if name == "equalize":
+ return f"(gimp-drawable-equalize {d} FALSE)"
+ if name == "autocontrast":
+ return f"(gimp-drawable-levels {d} HISTOGRAM-VALUE 0.0 1.0 FALSE 1.0 0.0 1.0 FALSE)"
+ if name == "find_edges":
+ return f"(plug-in-edge RUN-NONINTERACTIVE {i} {d} 1 0 0)"
+ if name == "emboss":
+ return f"(plug-in-emboss RUN-NONINTERACTIVE {i} {d} 315.0 45.0 7 TRUE)"
+ if name == "contour":
+ return f"(plug-in-edge RUN-NONINTERACTIVE {i} {d} 1 0 0)"
+ if name == "detail":
+ return f"(plug-in-unsharp-mask RUN-NONINTERACTIVE {i} {d} 3.0 0.3 0)"
+ if name == "sepia":
+ return f"(gimp-drawable-desaturate {d} DESATURATE-AVERAGE) (gimp-drawable-colorize-hsl {d} 35 40 0)"
+ if name == "solarize":
+ t = p.get("threshold", 128) / 255.0
+ return f"(gimp-drawable-threshold {d} HISTOGRAM-VALUE {t:.3f} 1.0)"
+ if name == "rotate":
+ angle = p.get("angle", 0.0) * 0.017453292519943295 # deg→rad
+ return f"(gimp-item-transform-rotate-default {d} {angle:.6f} TRUE 0 0)"
+ if name == "flip_h":
+ return f"(gimp-item-transform-flip-simple {d} ORIENTATION-HORIZONTAL TRUE 0)"
+ if name == "flip_v":
+ return f"(gimp-item-transform-flip-simple {d} ORIENTATION-VERTICAL TRUE 0)"
+ if name == "resize":
+ w = p.get("width", 100)
+ h = p.get("height", 100)
+ return f"(gimp-layer-scale {d} {w} {h} TRUE)"
+ if name == "crop":
+ l, t_, r, b = p.get("left", 0), p.get("top", 0), p.get("right", 0), p.get("bottom", 0)
+ new_w, new_h = r - l, b - t_
+ if new_w > 0 and new_h > 0:
+ return (f"(gimp-layer-resize {d} {new_w} {new_h} {-l} {-t_})"
+ f" (gimp-layer-flatten-image {i})")
+ return None
+
+ return None
+
+
+def _hex_to_rgb(color: str) -> str:
+ """'#rrggbb' → 'r g b' (space-separated decimal) for Script-Fu palettes."""
+ c = color.lstrip("#")
+ if len(c) == 6:
+ return f"{int(c[0:2], 16)} {int(c[2:4], 16)} {int(c[4:6], 16)}"
+ return "255 255 255"
+
+
+_NAMED_COLORS = {
+ "white": "255 255 255", "black": "0 0 0",
+ "red": "255 0 0", "green": "0 255 0", "blue": "0 0 255",
+}
+
+
+# ---------------------------------------------------------------------------
+# Full-project rendering via GIMP Script-Fu
+# ---------------------------------------------------------------------------
+
+def render_project(
+ project: Dict[str, Any],
+ output_path: str,
+ preset: str = "png",
+ overwrite: bool = False,
+ quality: Optional[int] = None,
+ format_override: Optional[str] = None,
+ timeout: int = 300,
+) -> Dict[str, Any]:
+ """Render a complete GIMP CLI project using GIMP's Script-Fu batch mode.
+
+ Builds a single Script-Fu expression that creates the canvas, inserts all
+ visible layers with their blend modes / opacities / filters, flattens the
+ image, and exports to the requested format.
+ """
+ from cli_anything.gimp.core.export import EXPORT_PRESETS
+
+ if os.path.exists(output_path) and not overwrite:
+ raise FileExistsError(f"Output file exists: {output_path}. Use --overwrite.")
+
+ abs_output = os.path.abspath(output_path).replace("\\", "/")
+ safe_output = _script_fu_escape(abs_output)
+ os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
+
+ canvas = project["canvas"]
+ cw, ch = canvas["width"], canvas["height"]
+ bg_color = canvas.get("background", "#ffffff")
+
+ if format_override:
+ fmt = format_override.upper()
+ elif preset in EXPORT_PRESETS:
+ fmt = EXPORT_PRESETS[preset]["format"]
+ else:
+ raise ValueError(f"Unknown preset: {preset}")
+
+ # --- build Script-Fu ---
+ s = []
+ s.append(f"(let* ((image (car (gimp-image-new {cw} {ch} RGB))))")
+
+ # Background layer
+ if bg_color.lower() != "transparent":
+ rgb = _NAMED_COLORS.get(bg_color.lower(), _hex_to_rgb(bg_color))
+ s.append(f"(let* ((bg (car (gimp-layer-new image {cw} {ch} RGB-IMAGE \"Background\" 100 LAYER-MODE-NORMAL))))")
+ s.append(f"(gimp-image-insert-layer image bg 0 -1)")
+ s.append(f"(gimp-palette-set-foreground '({rgb}))")
+ s.append(f"(gimp-edit-fill bg FILL-FOREGROUND))")
+
+ # Composite layers bottom → top
+ layers = project.get("layers", [])
+ for idx, layer in enumerate(reversed(layers)):
+ if not layer.get("visible", True):
+ continue
+ _build_layer_script(s, layer, idx, cw, ch)
+
+ # Flatten
+ s.append("(gimp-image-flatten image)")
+
+ # Export
+ _build_export_cmd(s, safe_output, fmt, preset, quality)
+
+ # Cleanup
+ s.append("(gimp-image-delete image))") # closes outer let*
+
+ script = " ".join(s)
+ result = batch_script_fu(script, timeout=timeout)
+
+ if not os.path.exists(abs_output):
+ raise RuntimeError(
+ f"GIMP rendering produced no output file.\n"
+ f" Expected: {abs_output}\n"
+ f" stderr: {result['stderr'][-500:]}\n"
+ f" stdout: {result['stdout'][-500:]}"
+ )
+
+ file_size = os.path.getsize(abs_output)
+ return {
+ "output": abs_output,
+ "format": fmt,
+ "size": f"{cw}x{ch}",
+ "file_size": file_size,
+ "file_size_human": _human_size(file_size),
+ "preset": preset,
+ "method": "gimp-batch",
+ "layers_rendered": sum(1 for l in layers if l.get("visible", True)),
+ }
+
+
+def _build_layer_script(
+ s: List[str], layer: Dict[str, Any], idx: int,
+ canvas_w: int, canvas_h: int,
+) -> None:
+ """Append Script-Fu expressions for a single layer."""
+ var = f"l{idx}"
+ ltype = layer.get("type", "image")
+ opacity = int(layer.get("opacity", 1.0) * 100)
+ blend = GIMP_BLEND_MODES.get(layer.get("blend_mode", "normal"), "LAYER-MODE-NORMAL")
+ w = layer.get("width", canvas_w)
+ h = layer.get("height", canvas_h)
+
+ if ltype == "image" and layer.get("source") and os.path.exists(layer["source"]):
+ src = _script_fu_escape(os.path.abspath(layer["source"]).replace("\\", "/"))
+ s.append(f'(let* (({var} (car (gimp-file-load-layer RUN-NONINTERACTIVE image "{src}"))))')
+ elif ltype == "text":
+ text = _script_fu_escape(layer.get("text", ""))
+ font_size = layer.get("font_size", 24)
+ font = _script_fu_escape(layer.get("font", "Sans"))
+ s.append(
+ f'(let* (({var} (car (gimp-text-fontname image -1 0 0 "{text}" 0 TRUE {font_size} UNIT-PIXEL "{font}"))))'
+ )
+ else:
+ fill = layer.get("fill", "transparent")
+ img_type = "RGBA-IMAGE" if fill == "transparent" else "RGB-IMAGE"
+ name_safe = _script_fu_escape(layer.get("name", f"Layer {idx}"))
+ s.append(f'(let* (({var} (car (gimp-layer-new image {w} {h} {img_type} "{name_safe}" {opacity} {blend}))))')
+ s.append(f"(gimp-image-insert-layer image {var} 0 -1)")
+ if fill != "transparent":
+ rgb = _NAMED_COLORS.get(fill, _hex_to_rgb(fill))
+ s.append(f"(gimp-palette-set-foreground '({rgb}))")
+ s.append(f"(gimp-edit-fill {var} FILL-FOREGROUND)")
+
+ # For file/text layers, insert into image and configure
+ if ltype == "image" and layer.get("source") and os.path.exists(layer["source"]):
+ s.append(f"(gimp-image-insert-layer image {var} 0 -1)")
+ # Text layers are auto-inserted by gimp-text-fontname
+
+ # Offsets
+ ox, oy = layer.get("offset_x", 0), layer.get("offset_y", 0)
+ if ox or oy:
+ s.append(f"(gimp-layer-set-offsets {var} {ox} {oy})")
+
+ # Opacity & blend mode (set explicitly for file/text layers)
+ if ltype in ("image", "text"):
+ s.append(f"(gimp-layer-set-opacity {var} {opacity})")
+ s.append(f"(gimp-layer-set-mode {var} {blend})")
+
+ # Filters
+ for filt in layer.get("filters", []):
+ sf = _filter_to_script_fu(filt["name"], filt.get("params", {}), "image", var)
+ if sf:
+ s.append(sf)
+
+ s.append(")") # close this layer's let*
+
+
+def _build_export_cmd(
+ s: List[str], safe_path: str, fmt: str,
+ preset: str, quality: Optional[int],
+) -> None:
+ """Append the Script-Fu export call."""
+ from cli_anything.gimp.core.export import EXPORT_PRESETS
+
+ s.append("(let* ((drawable (car (gimp-image-get-active-drawable image))))")
+
+ if fmt == "JPEG":
+ q = (quality or EXPORT_PRESETS.get(preset, {}).get("params", {}).get("quality", 85)) / 100.0
+ s.append(f'(file-jpeg-save RUN-NONINTERACTIVE image drawable "{safe_path}" "{safe_path}" {q:.2f} 0.0 0 0 "" 0 1 0 2)')
+ elif fmt == "PNG":
+ comp = EXPORT_PRESETS.get(preset, {}).get("params", {}).get("compress_level", 6)
+ s.append(f'(file-png-save RUN-NONINTERACTIVE image drawable "{safe_path}" "{safe_path}" 0 {comp} 1 1 1 1 1)')
+ elif fmt == "BMP":
+ s.append(f'(file-bmp-save RUN-NONINTERACTIVE image drawable "{safe_path}" "{safe_path}" 0)')
+ elif fmt == "TIFF":
+ s.append(f'(file-tiff-save RUN-NONINTERACTIVE image drawable "{safe_path}" "{safe_path}" 1)')
+ elif fmt == "GIF":
+ s.append(f"(gimp-image-convert-indexed image CONVERT-DITHER-TYPE-NO-DITHER CONVERT-PALETTE-TYPE-GENERATE 256 FALSE FALSE \"\")")
+ s.append(f"(set! drawable (car (gimp-image-get-active-drawable image)))")
+ s.append(f'(file-gif-save RUN-NONINTERACTIVE image drawable "{safe_path}" "{safe_path}" 0 0 0 0)')
+ else:
+ s.append(f'(gimp-file-overwrite RUN-NONINTERACTIVE image drawable "{safe_path}" "{safe_path}")')
+
+ s.append(")") # close export let*
+
+
+def _human_size(nbytes: int) -> str:
+ for unit in ("B", "KB", "MB", "GB"):
+ if nbytes < 1024:
+ return f"{nbytes:.1f} {unit}"
+ nbytes /= 1024
+ return f"{nbytes:.1f} TB"
diff --git a/gimp/agent-harness/setup.py b/gimp/agent-harness/setup.py
index 510462981..5b78437d7 100644
--- a/gimp/agent-harness/setup.py
+++ b/gimp/agent-harness/setup.py
@@ -16,7 +16,7 @@ setup(
version="1.0.0",
author="cli-anything contributors",
author_email="",
- description="CLI harness for GIMP - Raster image processing via gimp -i -b (batch mode). Requires: gimp (apt install gimp)",
+ description="CLI harness for GIMP - Raster image processing via gimp -i -b (batch mode). Recommended: gimp (apt install gimp)",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/HKUDS/CLI-Anything",
@@ -35,13 +35,17 @@ setup(
python_requires=">=3.10",
install_requires=[
"click>=8.0.0",
- "Pillow>=10.0.0",
"prompt-toolkit>=3.0.0",
],
extras_require={
+ "pillow": [
+ "Pillow>=10.0.0",
+ ],
"dev": [
"pytest>=7.0.0",
"pytest-cov>=4.0.0",
+ "Pillow>=10.0.0",
+ "numpy>=1.24.0",
],
},
entry_points={