#!/usr/bin/env python3 """Convert aligned RGBA layer PNGs into an Adobe Photoshop PSD v1 file. Designed for Ming-Image-0.2-Design-Layer ComfyUI outputs so Photoshop, CLIP STUDIO PAINT, and Live2D Cubism Editor open every part as an aligned, named, visible RGBA layer. Requires only Pillow and NumPy. """ from __future__ import annotations import argparse from dataclasses import dataclass import glob import json from pathlib import Path import re import struct import sys import numpy as np from PIL import Image @dataclass(frozen=True) class LayerSpec: """Single RGBA layer ready for PSD serialization.""" name: str image: np.ndarray # uint8 array of shape (H, W, 4) visible: bool = True opacity: int = 255 def _natural_key(path: Path) -> list[int | str]: parts = re.split(r"(\d+)", path.name) return [int(p) if p.isdigit() else p.lower() for p in parts] def _packbits_encode_row(row: bytes) -> bytes: """Encode one scanline with standard PackBits RLE (no 0x80 no-op byte).""" n = len(row) if n == 0: return b"" out = bytearray() literals = bytearray() i = 0 def flush_literals() -> None: while literals: chunk = literals[:128] del literals[:128] out.append(len(chunk) - 1) out.extend(chunk) while i < n: run_val = row[i] run_len = 1 while i + run_len < n and run_len < 128 and row[i + run_len] == run_val: run_len += 1 # Emit an RLE packet when >=3 repeats or when 2 repeats aren't mid-literal. if run_len >= 3 or (run_len == 2 and not literals): flush_literals() out.append((257 - run_len) & 0xFF) out.append(run_val) i += run_len else: literals.append(run_val) i += 1 flush_literals() return bytes(out) def _flip_last_row_parity(row: bytes, encoded: bytes) -> bytes: """Return a valid PackBits encoding of row with opposite length parity. Only called when width >= 2 because single-byte rows always encode to 2 bytes. """ target_parity = (len(encoded) & 1) ^ 1 candidates = [ _packbits_encode_row(row[:-1]) + bytes([0, row[-1]]), bytes([0, row[0]]) + _packbits_encode_row(row[1:]), ] for cand in candidates: if (len(cand) & 1) == target_parity and len(cand) <= 32767: return cand # Build literal 128-byte chunks; splitting any chunk of size >=2 flips parity. chunks = [row[i : min(i + 128, len(row))] for i in range(0, len(row), 128)] lit = b"".join(bytes([len(c) - 1]) + c for c in chunks) if (len(lit) & 1) == target_parity: return lit split_idx = next(idx for idx, c in enumerate(chunks) if len(c) >= 2) c = chunks[split_idx] replacement = [c[:1], c[1:]] chunks = chunks[:split_idx] + replacement + chunks[split_idx + 1 :] return b"".join(bytes([len(ch) - 1]) + ch for ch in chunks) def _encode_channel_rle(channel_2d: np.ndarray) -> bytes: """Encode a (H, W) uint8 plane into an even-length PSD PackBits channel block.""" h, w = channel_2d.shape if h == 0 or w == 0: return struct.pack(">H", 0) raw_bytes = np.ascontiguousarray(channel_2d, dtype=np.uint8).tobytes() rows = [_packbits_encode_row(raw_bytes[y * w : (y + 1) * w]) for y in range(h)] total_payload = sum(len(r) for r in rows) if (total_payload & 1) != 0 and w >= 2: last_raw = raw_bytes[(h - 1) * w : h * w] rows[-1] = _flip_last_row_parity(last_raw, rows[-1]) counts = b"".join(struct.pack(">H", len(r)) for r in rows) return struct.pack(">H", 1) + counts + b"".join(rows) def _tight_bbox(alpha: np.ndarray, crop: bool) -> tuple[int, int, int, int]: h, w = alpha.shape if not crop: return (0, 0, h, w) ys, xs = np.nonzero(alpha > 0) if ys.size == 0: return (0, 0, 0, 0) return (int(ys.min()), int(xs.min()), int(ys.max()) + 1, int(xs.max()) + 1) def _encode_pascal_name(name: str) -> bytes: # PSD legacy layer name is Latin-1 Pascal string (<=255 bytes), padded to 4B. ascii_bytes = name.encode("latin-1", "replace")[:255] raw = bytes([len(ascii_bytes)]) + ascii_bytes pad = (-len(raw)) & 3 return raw + (b"\x00" * pad) def _encode_additional_layer_info(name: str, layer_id: int) -> bytes: utf16 = name.encode("utf-16-be") luni_body = struct.pack(">I", len(name)) + utf16 if len(luni_body) & 3: luni_body += b"\x00" * (4 - (len(luni_body) & 3)) luni_block = b"8BIM" + b"luni" + struct.pack(">I", len(luni_body)) + luni_body lyid_block = b"8BIM" + b"lyid" + struct.pack(">II", 4, layer_id) return luni_block + lyid_block def _composite_rgb_preview(layers_bottom_to_top: list[LayerSpec], width: int, height: int) -> np.ndarray: """Alpha-composite layers bottom-to-top onto opaque white RGB canvas.""" canvas = np.full((height, width, 3), 255.0, dtype=np.float32) for layer in layers_bottom_to_top: if not layer.visible or layer.opacity == 0: continue rgba = layer.image.astype(np.float32) src_rgb = rgba[:, :, :3] src_a = (rgba[:, :, 3:4] / 255.0) * (layer.opacity / 255.0) canvas = src_rgb * src_a + canvas * (1.0 - src_a) return np.clip(np.rint(canvas), 0, 255).astype(np.uint8) def _encode_merged_image_data(rgb: np.ndarray) -> bytes: """Encode merged opaque RGB preview as PackBits RLE Image Data section.""" h, w, _ = rgb.shape counts: list[bytes] = [] payload: list[bytes] = [] for c in range(3): plane = np.ascontiguousarray(rgb[:, :, c], dtype=np.uint8).tobytes() for y in range(h): encoded = _packbits_encode_row(plane[y * w : (y + 1) * w]) counts.append(struct.pack(">H", len(encoded))) payload.append(encoded) return struct.pack(">H", 1) + b"".join(counts) + b"".join(payload) def write_psd( layers_bottom_to_top: list[LayerSpec], output_path: Path, dpi: int = 72, crop: bool = True, ) -> dict[str, object]: """Serialize aligned RGBA layers into an Adobe Photoshop PSD v1 file.""" if not layers_bottom_to_top: raise ValueError("At least one layer is required to write a PSD.") height, width, channels = layers_bottom_to_top[0].image.shape if channels != 4: raise ValueError(f"Expected 4-channel RGBA array, got shape {layers_bottom_to_top[0].image.shape}") for layer in layers_bottom_to_top: if layer.image.shape != (height, width, 4): raise ValueError( f"Layer {layer.name!r} has shape {layer.image.shape}, expected {(height, width, 4)}" ) header = ( b"8BPS" + struct.pack(">H", 1) + (b"\x00" * 6) + struct.pack(">HIIHH", 3, height, width, 8, 3) ) color_mode_data = struct.pack(">I", 0) dpi_fixed = int(round(dpi * 65536)) res_block = ( b"8BIM" + struct.pack(">H", 1005) + b"\x00\x00" + struct.pack(">I", 16) + struct.pack(">iHHiHH", dpi_fixed, 1, 1, dpi_fixed, 1, 1) ) image_resources = struct.pack(">I", len(res_block)) + res_block records_buf = bytearray() channel_data_buf = bytearray() bboxes: dict[str, tuple[int, int, int, int]] = {} channel_ids = (0, 1, 2, -1) for idx, layer in enumerate(layers_bottom_to_top, start=1): top, left, bottom, right = _tight_bbox(layer.image[:, :, 3], crop=crop) bboxes[layer.name] = (left, top, right, bottom) is_empty = top >= bottom or left >= right records_buf.extend(struct.pack(">iiiiH", top, left, bottom, right, len(channel_ids))) for ch_id in channel_ids: if is_empty: ch_bytes = struct.pack(">H", 0) else: src_idx = 3 if ch_id == -1 else ch_id plane = layer.image[top:bottom, left:right, src_idx] ch_bytes = _encode_channel_rle(plane) records_buf.extend(struct.pack(">hI", ch_id, len(ch_bytes))) channel_data_buf.extend(ch_bytes) # Blend flags bit 1 (0x02) means hidden in Adobe PSD specification. flags = 0x00 if layer.visible else 0x02 records_buf.extend( b"8BIM" + b"norm" + struct.pack(">BBBB", layer.opacity, 0, flags, 0) ) extra = bytearray() extra.extend(struct.pack(">I", 0)) # Layer mask data length extra.extend(struct.pack(">I", 0)) # Layer blending ranges length extra.extend(_encode_pascal_name(layer.name)) extra.extend(_encode_additional_layer_info(layer.name, idx)) records_buf.extend(struct.pack(">I", len(extra))) records_buf.extend(extra) layer_info = bytearray() layer_info.extend(struct.pack(">h", len(layers_bottom_to_top))) layer_info.extend(records_buf) layer_info.extend(channel_data_buf) if len(layer_info) & 1: layer_info.append(0) layer_and_mask_body = ( struct.pack(">I", len(layer_info)) + bytes(layer_info) + struct.pack(">I", 0) # Global layer mask info ) layer_and_mask_section = struct.pack(">I", len(layer_and_mask_body)) + layer_and_mask_body merged_rgb = _composite_rgb_preview(layers_bottom_to_top, width, height) image_data_section = _encode_merged_image_data(merged_rgb) output_path.parent.mkdir(parents=True, exist_ok=True) with open(output_path, "wb") as fh: fh.write(header) fh.write(color_mode_data) fh.write(image_resources) fh.write(layer_and_mask_section) fh.write(image_data_section) return { "width": width, "height": height, "layer_count": len(layers_bottom_to_top), "bytes": output_path.stat().st_size, "bboxes": bboxes, } def _resolve_inputs(raw_inputs: list[str]) -> list[Path]: resolved: list[Path] = [] for item in raw_inputs: p = Path(item) if p.is_dir(): files = sorted((f for f in p.iterdir() if f.suffix.lower() == ".png"), key=_natural_key) resolved.extend(files) elif p.exists(): resolved.append(p) else: matches = sorted((Path(m) for m in glob.glob(item)), key=_natural_key) resolved.extend(matches) seen: set[Path] = set() unique: list[Path] = [] for p in resolved: rp = p.resolve() if rp not in seen: seen.add(rp) unique.append(p) return unique def _default_layer_name(path: Path, index: int) -> str: stem = path.stem m = re.match(r"^(\d+)[_-](.+)$", stem) if m: num = int(m.group(1)) words = [w.capitalize() for w in re.split(r"[_-]+", m.group(2)) if w] return f"L{num:02d}_{'_'.join(words)}" if words else f"L{num:02d}" clean = re.sub(r"[^A-Za-z0-9_-]+", "_", stem).strip("_") return clean or f"L{index:02d}" def _names_from_report(report_path: Path) -> list[str]: data = json.loads(report_path.read_text(encoding="utf-8")) names: list[str] = [] for entry in data.get("layers", []): if int(entry.get("frame_idx", -1)) == 0: continue label = str(entry.get("label", "")) prompt_head = str(entry.get("prompt_head", "")) prefix = f"L{int(entry['frame_idx']):02d}_" english = label.split("/")[-1].strip() if "/" in label else prompt_head.strip() slug = re.sub(r"[^A-Za-z0-9]+", "_", english).strip("_") names.append(f"{prefix}{slug}" if slug else f"L{int(entry['frame_idx']):02d}") return names def _packbits_decode_row(data: bytes, expected_len: int) -> bytes: out = bytearray() i = 0 n = len(data) while i < n and len(out) < expected_len: hdr = data[i] i += 1 if hdr < 128: count = hdr + 1 out.extend(data[i : i + count]) i += count elif hdr > 128: count = 257 - hdr out.extend([data[i]] * count) i += 1 if len(out) != expected_len: raise AssertionError(f"Decoded PackBits scanline length {len(out)} != {expected_len}") return bytes(out) def _read_luni_and_lyid(extra: bytes) -> tuple[str | None, int | None]: pos = 0 mask_len = struct.unpack_from(">I", extra, pos)[0] pos += 4 + mask_len blend_len = struct.unpack_from(">I", extra, pos)[0] pos += 4 + blend_len pascal_len = extra[pos] pos += ((1 + pascal_len) + 3) & ~3 luni_name: str | None = None lyid_val: int | None = None while pos + 12 <= len(extra): sig, key, size = struct.unpack_from(">4s4sI", extra, pos) pos += 12 if sig not in (b"8BIM", b"8B64"): break block = extra[pos : pos + size] if key == b"luni" and len(block) >= 4: char_count = struct.unpack_from(">I", block, 0)[0] luni_name = block[4 : 4 + char_count * 2].decode("utf-16-be") elif key == b"lyid" and len(block) >= 4: lyid_val = struct.unpack_from(">I", block, 0)[0] pos += (size + 3) & ~3 return luni_name, lyid_val def _verify_psd( psd_path: Path, expected_bottom_to_top: list[LayerSpec], expected_bboxes: dict[str, tuple[int, int, int, int]], ) -> None: height, width, _ = expected_bottom_to_top[0].image.shape expected_preview = _composite_rgb_preview(expected_bottom_to_top, width, height) # 1. Verify merged preview and layer directory via Pillow. with Image.open(psd_path) as im: if im.size != (width, height): raise AssertionError(f"Merged canvas mismatch: got {im.size}, expected {(width, height)}") if im.mode != "RGB": raise AssertionError(f"Merged mode mismatch: got {im.mode!r}, expected 'RGB'") preview_arr = np.asarray(im, dtype=np.int16) preview_diff = int(np.max(np.abs(preview_arr - expected_preview.astype(np.int16)))) if preview_diff != 0: raise AssertionError(f"Merged RGB preview diff={preview_diff}") if im.n_frames != len(expected_bottom_to_top): raise AssertionError( f"Layer count mismatch: got {im.n_frames}, expected {len(expected_bottom_to_top)}" ) for idx, spec in enumerate(expected_bottom_to_top): layer_name, layer_mode, layer_bbox, _ = im.layers[idx] if layer_mode != "RGBA": raise AssertionError(f"Layer {idx} mode mismatch: {layer_mode!r}") exp_bbox = expected_bboxes[spec.name] if layer_bbox != exp_bbox: raise AssertionError( f"Layer {spec.name!r} bbox mismatch: got {layer_bbox}, expected {exp_bbox}" ) if layer_name != spec.name[:255]: raise AssertionError( f"Layer {idx} PIL name mismatch: got {layer_name!r}, expected {spec.name[:255]!r}" ) # 2. Verify raw binary structure, Unicode names, and PackBits pixel parity. data = psd_path.read_bytes() if data[:4] != b"8BPS": raise AssertionError("Missing 8BPS signature") pos = 26 pos += 4 + struct.unpack_from(">I", data, pos)[0] # Color mode data pos += 4 + struct.unpack_from(">I", data, pos)[0] # Image resources pos += 4 # Layer & mask section length pos += 4 # Layer info length layer_count = struct.unpack_from(">h", data, pos)[0] pos += 2 if layer_count != len(expected_bottom_to_top): raise AssertionError(f"Binary layer_count={layer_count}, expected {len(expected_bottom_to_top)}") parsed_records: list[tuple[tuple[int, int, int, int], list[tuple[int, int]]]] = [] for idx, spec in enumerate(expected_bottom_to_top, start=1): top, left, bottom, right, nc = struct.unpack_from(">iiiiH", data, pos) pos += 18 if (left, top, right, bottom) != expected_bboxes[spec.name]: raise AssertionError(f"Binary bbox mismatch on {spec.name}") ch_meta: list[tuple[int, int]] = [] for _ in range(nc): cid, clen = struct.unpack_from(">hI", data, pos) pos += 6 ch_meta.append((cid, clen)) sig, blend_key, opacity, clipping, flags, _ = struct.unpack_from(">4s4sBBBB", data, pos) pos += 12 if sig != b"8BIM" or blend_key != b"norm" or clipping != 0: raise AssertionError(f"Invalid blend record on {spec.name}") expected_flag = 0x00 if spec.visible else 0x02 if opacity != spec.opacity or flags != expected_flag: raise AssertionError(f"Opacity/flags mismatch on {spec.name}") extra_len = struct.unpack_from(">I", data, pos)[0] pos += 4 luni_name, lyid_val = _read_luni_and_lyid(data[pos : pos + extra_len]) if luni_name != spec.name or lyid_val != idx: raise AssertionError( f"luni/lyid mismatch on {spec.name}: luni={luni_name!r}, lyid={lyid_val}" ) pos += extra_len parsed_records.append(((left, top, right, bottom), ch_meta)) for spec, ((left, top, right, bottom), ch_meta) in zip(expected_bottom_to_top, parsed_records): bw, bh = right - left, bottom - top decoded_planes: dict[int, np.ndarray] = {} for cid, clen in ch_meta: ch_end = pos + clen comp = struct.unpack_from(">H", data, pos)[0] p = pos + 2 if bw > 0 and bh > 0: if comp != 1: raise AssertionError(f"Expected PackBits compression=1 on {spec.name}, got {comp}") row_lens = struct.unpack_from(f">{bh}H", data, p) p += bh * 2 rows = bytearray() for rlen in row_lens: rows.extend(_packbits_decode_row(data[p : p + rlen], bw)) p += rlen decoded_planes[cid] = np.frombuffer(rows, dtype=np.uint8).reshape((bh, bw)) pos = ch_end if bw > 0 and bh > 0: rebuilt = np.stack( [decoded_planes[0], decoded_planes[1], decoded_planes[2], decoded_planes[-1]], axis=-1, ) src_crop = spec.image[top:bottom, left:right] max_diff = int(np.max(np.abs(rebuilt.astype(np.int16) - src_crop.astype(np.int16)))) if max_diff != 0: raise AssertionError(f"Layer {spec.name!r} binary PackBits pixel diff={max_diff}") # 3. Optional cross-check via psd-tools if installed in current Python. try: from psd_tools import PSDImage # type: ignore[import-not-found] except ImportError: return psd = PSDImage.open(psd_path) if len(psd) != len(expected_bottom_to_top): raise AssertionError(f"psd-tools layer count {len(psd)} != {len(expected_bottom_to_top)}") for spec, layer in zip(expected_bottom_to_top, psd): got = np.asarray(layer.topil(), dtype=np.int16) left, top, right, bottom = expected_bboxes[spec.name] if left < right and top < bottom: src_crop = spec.image[top:bottom, left:right].astype(np.int16) if int(np.max(np.abs(got - src_crop))) != 0: raise AssertionError(f"psd-tools pixel mismatch on {spec.name}") def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser( description="Pack aligned Ming-Image RGBA PNG layers into a Photoshop/CLIP STUDIO/Live2D PSD." ) parser.add_argument( "inputs", nargs="+", help="Input PNG files, directory, or glob patterns in layer order.", ) parser.add_argument("-o", "--output", required=True, type=Path, help="Output .psd path.") parser.add_argument( "--skip-composite", action="store_true", help="Skip the first input image (Ming-Image frame 00 composite).", ) parser.add_argument( "--order", choices=("top-to-bottom", "bottom-to-top"), default="top-to-bottom", help="Order of input PNGs. Ming-Image outputs Layer 1..N top-to-bottom (default).", ) parser.add_argument( "--names", type=str, default=None, help="Comma-separated layer names matching the input order.", ) parser.add_argument( "--report", type=Path, default=None, help="Optional decomposition_report.json to derive layer names.", ) parser.add_argument( "--alpha-threshold", type=int, default=4, help=( "Zero out pixels with alpha below this 0-255 threshold before tight cropping " "(default: 4, removes invisible VAE floor while keeping anti-aliasing; 0 keeps raw pixels)." ), ) parser.add_argument( "--no-crop", action="store_true", help="Keep full canvas bounds instead of tight non-transparent bounding boxes.", ) parser.add_argument("--dpi", type=int, default=72, help="Document DPI metadata (default: 72).") parser.add_argument( "--verify", action="store_true", help="Re-open output PSD with Pillow + strict binary decoder (and psd-tools if installed) to assert lossless parity.", ) args = parser.parse_args(argv) if not 0 <= args.alpha_threshold <= 255: parser.error("--alpha-threshold must be between 0 and 255.") paths = _resolve_inputs(args.inputs) if args.skip_composite: if len(paths) < 2: parser.error("--skip-composite requires at least 2 input images.") paths = paths[1:] if not paths: parser.error("No PNG files resolved from inputs.") if args.names: layer_names = [n.strip() for n in args.names.split(",") if n.strip()] if len(layer_names) != len(paths): parser.error(f"--names count ({len(layer_names)}) does not match input files ({len(paths)}).") elif args.report: layer_names = _names_from_report(args.report) if len(layer_names) != len(paths): parser.error(f"--report layer count ({len(layer_names)}) does not match inputs ({len(paths)}).") else: layer_names = [_default_layer_name(p, i + 1) for i, p in enumerate(paths)] specs: list[LayerSpec] = [] for name, path in zip(layer_names, paths): with Image.open(path) as im: rgba = np.asarray(im.convert("RGBA"), dtype=np.uint8) if args.alpha_threshold > 0: rgba = rgba.copy() rgba[rgba[:, :, 3] < args.alpha_threshold] = 0 specs.append(LayerSpec(name=name, image=rgba)) layers_bottom_to_top = list(reversed(specs)) if args.order == "top-to-bottom" else specs info = write_psd( layers_bottom_to_top=layers_bottom_to_top, output_path=args.output, dpi=args.dpi, crop=not args.no_crop, ) if args.verify: _verify_psd( args.output, layers_bottom_to_top, info["bboxes"], # type: ignore[arg-type] ) print( f"[layers_to_psd] Wrote {args.output} ({info['bytes']:,} bytes, " f"{info['width']}x{info['height']}, {info['layer_count']} RGBA layers" + (", verified OK" if args.verify else "") + ")" ) return 0 if __name__ == "__main__": sys.exit(main())