# SPDX-License-Identifier: Apache-2.0 """Host tests of the image front end on images with transparency (no device, no weights): the official processor (transformers 5.24.1 ``Gemma4ImageProcessor``, ``do_convert_rgb``) composites transparency onto WHITE. The hashes below are of the official ``pixel_values`` (rounded to uint8) for the deterministic images of ``transparent_images.py`` and the shipped ``samples/transparent.png`` at 280 soft tokens (computed on the CPU with the official code; the alpha-dropping conversion this replaces differed by up to 1.0 per pixel, and the sample's embedding by cosine 0.964).""" import hashlib import io import pathlib import numpy as np import pytest OFFICIAL = {"rgba": "be79a243da1a2ae6", "la": "8e4fb3aab3e55ff3", "p_transparent": "61a6116a22589c87", "rgba_array": "acab8d9069d43f0a", "sample_png": "1c0e85bf41009e91"} SAMPLES = pathlib.Path(__file__).resolve().parent.parent / "samples" def _hash(pix): return hashlib.sha256(np.round(np.asarray(pix, np.float64) * 255).astype(np.uint8).tobytes()).hexdigest()[:16] @pytest.mark.parametrize("name", ["rgba", "la", "p_transparent", "rgba_array"]) def test_official_pixels(name): from tt_embgemma.preprocess.image import preprocess_image from tt_embgemma.tests.transparent_images import images assert _hash(preprocess_image(images()[name], 280).pixels) == OFFICIAL[name] def test_shipped_sample_pil_and_server_decoder(): from PIL import Image from tt_embgemma import media as MD from tt_embgemma.preprocess.image import preprocess_image data = (SAMPLES / "transparent.png").read_bytes() im = Image.open(io.BytesIO(data)) im.load() assert im.mode == "RGBA" assert _hash(preprocess_image(im, 280).pixels) == OFFICIAL["sample_png"] assert _hash(preprocess_image(MD.decode_image(data), 280).pixels) == OFFICIAL["sample_png"] def test_white_background_and_opaque_pixels(): from PIL import Image from tt_embgemma.preprocess.image import composite_rgba_array, to_rgb_pil, to_uint8_chw a = np.zeros((8, 8, 4), np.uint8) a[..., :3] = 13 a[2:4, 2:4] = (10, 200, 30, 255) for img in (Image.fromarray(a, "RGBA"), a): chw = to_uint8_chw(img) assert (chw[:, 0, 0] == 255).all() and tuple(chw[:, 2, 2]) == (10, 200, 30) rgb = np.asarray(to_rgb_pil(Image.fromarray(a[..., :3], "RGB"))) assert np.array_equal(rgb, a[..., :3]) # RGB images pass unchanged f = composite_rgba_array(a.astype(np.float32) / 255) # float arrays in [0, 1] assert f.dtype == np.float32 and np.allclose(f[0, 0], 1.0) and np.allclose(f[2, 2], np.array([10, 200, 30]) / 255) def test_video_frames_with_alpha(): from tt_embgemma.preprocess.image import preprocess_image from tt_embgemma.preprocess.video import preprocess_video from tt_embgemma.tests.transparent_images import rgba_array a = rgba_array() fr = preprocess_video(np.stack([a, a]), 1.0, None, 1.0, 32, 70) assert np.array_equal(fr[0].pixels, preprocess_image(a, 70).pixels)