CodeSampleX

Ejemplo

pillow 12.3.0: PIL.ImageChops

Muestra verificada para pypi pillow 12.3.0: PIL.ImageChops. El contrato se ejecutó en python 3.12 · linux alpine/x64 · docker y pasó.

sha256:c7c4644c6a48efb130ce589a62c2a7756c5106b9e1f12fdc628cc18d11f8d27b

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
1
Claves de firma que lo compilaron
1
Entorno declarado python 3.12 linux 24 · alpine · musl 1.2 x64 python 3.12 python pip

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
python 3.12 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1python:3.12-alpine@sha256:d09d15e60962…
2026-08-25

Caso

HOW
Objetivo
verify PIL.ImageChops in pkg:pypi/pillow@12.3.0
Paquetes
Símbolos
  • PIL.ImageChops
Entorno
python 3.12
Creado
2026-08-25T20:11:06Z

Contrato

  1. ImageChops.difference(image1, image2) calculates absolute pixel-by-pixel difference
  2. ImageChops.add(image1, image2, scale, offset) adds pixel values with scaling and offset
  3. ImageChops.subtract(image1, image2, scale, offset) subtracts pixel values with scaling and offset
  4. ImageChops.multiply(image1, image2) and screen(image1, image2) blend images using multiplicative and inverted screen modes
  5. ImageChops.darker(image1, image2) and lighter(image1, image2) select minimum and maximum pixel values respectively
  6. ImageChops.invert(image) inverts pixel values by subtracting each channel from 255
  7. ImageChops.blend(image1, image2, alpha) interpolates linearly between two images using constant alpha
  8. ImageChops.composite(image1, image2, mask) composites two images using an alpha mask
  9. ImageChops.offset(image, xoffset, yoffset) cyclically shifts image data wrapping around boundaries
  10. ImageChops operations raise ValueError when input image color modes do not match

Archivos

  • PROMPT.md
  • csx.json
  • requirements.txt
  • spec.json
  • src/channel_ops.py
  • test/contract.py

Descargar el artefacto de código fuente (tar.gz)

Código fuente

PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify PIL.ImageChops in pkg:pypi/pillow@12.3.0
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:pypi/pillow@12.3.0
Demonstrate these symbols/APIs:
  - PIL.ImageChops
Constraints:
  - executionContext: node
Required runtime conditions:
  - ecosystem: npm
  - language: javascript
  - moduleSystem: cjs
  - packageManager: npm@10.9.8
  - runtime: node@22.23.2

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:949358c9310691ba9925bc9200e796368ae72b008fb2d939d10012dd4984b91c","contract":["ImageChops.difference(image1, image2) calculates absolute pixel-by-pixel difference","ImageChops.add(image1, image2, scale, offset) adds pixel values with scaling and offset","ImageChops.subtract(image1, image2, scale, offset) subtracts pixel values with scaling and offset","ImageChops.multiply(image1, image2) and screen(image1, image2) blend images using multiplicative and inverted screen modes","ImageChops.darker(image1, image2) and lighter(image1, image2) select minimum and maximum pixel values respectively","ImageChops.invert(image) inverts pixel values by subtracting each channel from 255","ImageChops.blend(image1, image2, alpha) interpolates linearly between two images using constant alpha","ImageChops.composite(image1, image2, mask) composites two images using an alpha mask","ImageChops.offset(image, xoffset, yoffset) cyclically shifts image data wrapping around boundaries","ImageChops operations raise ValueError when input image color modes do not match"],"goal":"verify PIL.ImageChops in pkg:pypi/pillow@12.3.0","kind":"HOW","packages":["pkg:pypi/pillow@12.3.0"],"schemaVersion":1,"symbols":["PIL.ImageChops"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","distro":"alpine","ecosystem":"pypi","language":"python","libc":"musl","libcVersion":"1.2","os":"linux","osVersionBucket":"24","packageManager":"pip","runtime":"python","runtimeVersion":"3.12","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/pillow@12.3.0"],"schemaVersion":1,"subject":"pkg:pypi/pillow@12.3.0","symbols":["PIL.ImageChops"],"verifierAdapter":"python@1"}
requirements.txt
pillow==12.3.0
spec.json
{
  "schemaVersion": 1,
  "goal": "verify PIL.ImageChops in pkg:pypi/pillow@12.3.0",
  "kind": "HOW",
  "packages": [
    "pkg:pypi/pillow@12.3.0"
  ],
  "symbols": [
    "PIL.ImageChops"
  ],
  "constraints": {
    "executionContext": "node"
  },
  "runtimeConditions": {
    "ecosystem": "npm",
    "language": "javascript",
    "moduleSystem": "cjs",
    "packageManager": "npm@10.9.8",
    "runtime": "node@22.23.2"
  }
}
src/channel_ops.py
"""Channel operations module demonstrating PIL.ImageChops functions."""

from PIL import Image, ImageChops


def calculate_difference(image1: Image.Image, image2: Image.Image) -> Image.Image:
    """Calculate the absolute pixel-by-pixel difference between two images.

    Args:
        image1: First PIL Image.
        image2: Second PIL Image.

    Returns:
        New PIL Image containing absolute differences.
    """
    return ImageChops.difference(image1, image2)


def add_images(
    image1: Image.Image,
    image2: Image.Image,
    scale: float = 1.0,
    offset: int = 0,
) -> Image.Image:
    """Add two images with scale and offset.

    Args:
        image1: First PIL Image.
        image2: Second PIL Image.
        scale: Divisor applied after addition.
        offset: Value added after division.

    Returns:
        New PIL Image with added pixel values.
    """
    return ImageChops.add(image1, image2, scale=scale, offset=offset)


def subtract_images(
    image1: Image.Image,
    image2: Image.Image,
    scale: float = 1.0,
    offset: int = 0,
) -> Image.Image:
    """Subtract image2 from image1 with scale and offset.

    Args:
        image1: First PIL Image.
        image2: Second PIL Image to subtract.
        scale: Divisor applied after subtraction.
        offset: Value added after division.

    Returns:
        New PIL Image with subtracted pixel values.
    """
    return ImageChops.subtract(image1, image2, scale=scale, offset=offset)


def blend_images(image1: Image.Image, image2: Image.Image, alpha: float) -> Image.Image:
    """Blend two images using constant alpha interpolation.

    Args:
        image1: First PIL Image.
        image2: Second PIL Image.
        alpha: Blend weight (0.0 to 1.0).

    Returns:
        New blended PIL Image.
    """
    return ImageChops.blend(image1, image2, alpha)


def composite_images(
    image1: Image.Image, image2: Image.Image, mask: Image.Image
) -> Image.Image:
    """Composite two images using a transparency mask.

    Args:
        image1: Foreground PIL Image.
        image2: Background PIL Image.
        mask: Mask PIL Image (mode '1', 'L', or 'RGBA').

    Returns:
        New composited PIL Image.
    """
    return ImageChops.composite(image1, image2, mask)


def shift_image(
    image: Image.Image, xoffset: int, yoffset: int = 0
) -> Image.Image:
    """Offset image data cyclically across canvas boundaries.

    Args:
        image: Source PIL Image.
        xoffset: Horizontal offset in pixels.
        yoffset: Vertical offset in pixels.

    Returns:
        New offset PIL Image.
    """
    return ImageChops.offset(image, xoffset, yoffset)
test/contract.py
"""Contract verification test for PIL.ImageChops in pkg:pypi/pillow@12.3.0."""

import os
import sys

# Ensure repository root is on sys.path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from PIL import Image, ImageChops
from src.channel_ops import (
    add_images,
    blend_images,
    calculate_difference,
    composite_images,
    shift_image,
    subtract_images,
)


def test_difference():
    # Direct library call
    im1 = Image.new("RGB", (4, 4), color=(120, 180, 240))
    im2 = Image.new("RGB", (4, 4), color=(40, 80, 120))
    diff = ImageChops.difference(im1, im2)
    assert diff.getpixel((0, 0)) == (80, 100, 120)

    # Helper wrapper call
    diff_helper = calculate_difference(im1, im2)
    assert diff_helper.getpixel((0, 0)) == (80, 100, 120)


def test_add_and_subtract():
    im1 = Image.new("RGB", (4, 4), color=(120, 180, 240))
    im2 = Image.new("RGB", (4, 4), color=(40, 80, 120))

    # Add with scale and offset: (120+40)/2 + 10 = 90
    added = add_images(im1, im2, scale=2.0, offset=10)
    assert added.getpixel((0, 0)) == (90, 140, 190)

    # Add with clipping at 255: 180 + 100 = 280 -> 255
    im_bright = Image.new("RGB", (4, 4), color=(100, 100, 100))
    added_clip = ImageChops.add(im1, im_bright, scale=1.0, offset=0)
    assert added_clip.getpixel((0, 0)) == (220, 255, 255)

    # Subtract with scale and offset
    sub = subtract_images(im1, im2, scale=1.0, offset=0)
    assert sub.getpixel((0, 0)) == (80, 100, 120)

    # Direct ImageChops subtract
    sub_direct = ImageChops.subtract(im1, im2, scale=2.0, offset=5)
    # (120-40)/2 + 5 = 45, (180-80)/2 + 5 = 55, (240-120)/2 + 5 = 65
    assert sub_direct.getpixel((0, 0)) == (45, 55, 65)


def test_multiply_and_screen():
    im1 = Image.new("RGB", (4, 4), color=(120, 180, 240))
    im2 = Image.new("RGB", (4, 4), color=(40, 80, 120))

    mult = ImageChops.multiply(im1, im2)
    assert mult.getpixel((0, 0)) == (
        120 * 40 // 255,
        180 * 80 // 255,
        240 * 120 // 255,
    )

    screen = ImageChops.screen(im1, im2)
    assert screen.getpixel((0, 0)) == (
        255 - ((255 - 120) * (255 - 40) // 255),
        255 - ((255 - 180) * (255 - 80) // 255),
        255 - ((255 - 240) * (255 - 120) // 255),
    )


def test_darker_lighter_invert():
    im1 = Image.new("RGB", (4, 4), color=(120, 180, 240))
    im2 = Image.new("RGB", (4, 4), color=(40, 80, 120))

    dark = ImageChops.darker(im1, im2)
    assert dark.getpixel((0, 0)) == (40, 80, 120)

    light = ImageChops.lighter(im1, im2)
    assert light.getpixel((0, 0)) == (120, 180, 240)

    inv = ImageChops.invert(im1)
    assert inv.getpixel((0, 0)) == (255 - 120, 255 - 180, 255 - 240)


def test_blend_and_composite():
    im1 = Image.new("RGB", (4, 4), color=(120, 180, 240))
    im2 = Image.new("RGB", (4, 4), color=(40, 80, 120))

    # Blend with alpha=0.5
    blended = blend_images(im1, im2, 0.5)
    assert blended.getpixel((0, 0)) == (80, 130, 180)

    # Composite with 50% mask (value 128)
    mask = Image.new("L", (4, 4), color=128)
    comp = composite_images(im1, im2, mask)
    assert comp.getpixel((0, 0)) == (
        round(120 * (128 / 255) + 40 * (1 - 128 / 255)),
        round(180 * (128 / 255) + 80 * (1 - 128 / 255)),
        round(240 * (128 / 255) + 120 * (1 - 128 / 255)),
    )


def test_offset():
    im = Image.new("RGB", (4, 4), color=(0, 0, 0))
    im.putpixel((0, 0), (255, 255, 255))

    shifted = shift_image(im, 2, 1)
    assert shifted.getpixel((2, 1)) == (255, 255, 255)
    assert shifted.getpixel((0, 0)) == (0, 0, 0)


def test_mode_mismatch_error():
    im_rgb = Image.new("RGB", (4, 4), color=(100, 100, 100))
    im_gray = Image.new("L", (4, 4), color=100)

    try:
        ImageChops.difference(im_rgb, im_gray)
        assert False, "Expected ValueError on image mode mismatch"
    except ValueError:
        pass


def main():
    test_difference()
    test_add_and_subtract()
    test_multiply_and_screen()
    test_darker_lighter_invert()
    test_blend_and_composite()
    test_offset()
    test_mode_mismatch_error()
    print("Contract tests for PIL.ImageChops in pkg:pypi/pillow@12.3.0 passed successfully.")
    return 0


if __name__ == "__main__":
    sys.exit(main())

Seeder de origen

anónimo