"""CPU contract checks for exact canvas geometry, stitching and shared state.""" import contextlib import importlib.util import math from pathlib import Path import sys import types import unittest from unittest.mock import Mock, patch from PIL import Image spec = importlib.util.spec_from_file_location("outpaint_under_test", Path(__file__).with_name("outpaint_backend.py")) outpaint = importlib.util.module_from_spec(spec) spec.loader.exec_module(outpaint) def request(**kwargs): return dict(input_image_1=Image.new("RGB", (120, 80), (211, 44, 19)), target_megapixels=0.5, randomize_seed=False, seed=17, **kwargs) def prepared(**kwargs): with patch.dict(sys.modules, {"huggingface_hub": types.SimpleNamespace( hf_hub_download=Mock(return_value="cached-outpaint"))}): return outpaint.prepare(request(**kwargs)) class PromptTests(unittest.TestCase): def test_instruction_is_exact_first_and_idempotent(self): for text in (None, "", " ", "Scene: A forest.", outpaint.OUTPAINT_PROMPT + " Scene: A forest.", "Scene: A forest. " + outpaint.OUTPAINT_PROMPT.upper()): result = outpaint.prompt_with_trigger(text) self.assertTrue(result.startswith(outpaint.OUTPAINT_PROMPT)) self.assertEqual(result.count(outpaint.OUTPAINT_PROMPT), 1) self.assertEqual(outpaint.prompt_with_trigger(result), result) self.assertEqual(outpaint.prompt_with_trigger("Scene: A forest."), outpaint.OUTPAINT_PROMPT + " Scene: A forest.") def test_duplicate_instruction_is_removed_but_custom_body_kept(self): text = outpaint.OUTPAINT_PROMPT + " Scene: A lake. " + outpaint.OUTPAINT_PROMPT self.assertEqual(outpaint.prompt_with_trigger(text), outpaint.OUTPAINT_PROMPT + " Scene: A lake.") class GeometryTests(unittest.TestCase): def test_default_canvas_is_flat_gray_outside_the_source(self): data = request() canvas, picture, box, resolution = outpaint.build_canvas(data) x, y, width, height = box self.assertEqual(outpaint.request_canvas(data), canvas.size) self.assertEqual(outpaint.preview(data)[1], canvas.size) self.assertGreater(resolution, 0) self.assertEqual(canvas.getpixel((0, 0)), outpaint.GRAY) self.assertEqual(canvas.getpixel((canvas.width - 1, canvas.height - 1)), outpaint.GRAY) self.assertEqual(canvas.crop((x, y, x + width, y + height)).tobytes(), picture.tobytes()) self.assertEqual(picture.getpixel((0, 0)), (211, 44, 19)) self.assertEqual(data["input_image_1"].size, (120, 80)) def test_native_reference_resize_reproduces_every_canvas_exactly(self): # Independent application of the pinned pipeline's resize equations. for size in ((512, 512), (300, 800), (800, 300), (999, 637), (2048, 1536)): for mp in (0.5, 0.75, 1, 1.5, 2): for pads in ((25, 25, 25, 25), (0, 100, 0, 0), (35, 5, 0, 20), (0, 0, 50, 100)): data = request() data.update(input_image_1=Image.new("RGB", size), target_megapixels=mp) data.update({"outpaint_" + side: value for side, value in zip(outpaint.SIDES, pads)}) width, height = outpaint.request_canvas(data) resolution = round(math.sqrt(mp * 1024**2)) native_w = math.sqrt(resolution**2 * width / height) native_h = native_w / (width / height) self.assertEqual((round(native_w / 32) * 32, round(native_h / 32) * 32), (width, height)) self.assertEqual(width % 32 + height % 32, 0) self.assertLess(abs(width * height / (mp * 1024**2) - 1), 0.08) def test_one_sided_expansion_leaves_other_edges_flush(self): for side in outpaint.SIDES: data = request() data.update({"outpaint_" + item: 50 if item == side else 0 for item in outpaint.SIDES}) canvas, _, (x, y, width, height), _ = outpaint.build_canvas(data) self.assertEqual(x > 0, side == "left") self.assertEqual(y > 0, side == "top") self.assertEqual(x + width < canvas.width, side == "right") self.assertEqual(y + height < canvas.height, side == "bottom") def test_asymmetric_percentages_preserve_relative_placement(self): canvas, _, (x, y, width, height), _ = outpaint.build_canvas(request( outpaint_left=75, outpaint_right=25, outpaint_top=0, outpaint_bottom=50)) self.assertLessEqual(abs(x / (canvas.width - width) - 0.75), 1 / (canvas.width - width)) self.assertEqual(y, 0) self.assertLessEqual(abs((canvas.height - height) / height - 0.5), 2 / height) def test_exif_orientation_is_applied_before_geometry(self): image = Image.new("RGB", (120, 80)) image.getexif()[274] = 6 data = request() data["input_image_1"] = image self.assertEqual(outpaint._source(data).size, (80, 120)) width, height = outpaint.request_canvas(data) self.assertLess(width, height) def test_old_common_canvas_and_extra_inputs_do_not_change_outpaint(self): data = request() expected = outpaint.request_canvas(data) data.update(width=8192, height=256, input_image_2=Image.new("RGB", (80, 800)), extra_images=[Image.new("RGB", (100, 100))]) self.assertEqual(outpaint.request_canvas(data), expected) class CompositeTests(unittest.TestCase): def setUp(self): self.result = Image.new("RGB", (100, 100), (0, 0, 200)) self.source = Image.new("RGB", (60, 60), (200, 0, 0)) def test_zero_feather_preserves_every_source_pixel(self): output = outpaint.composite_original(self.result, self.source, (20, 20, 60, 60), 0) self.assertEqual(output.crop((20, 20, 80, 80)).tobytes(), self.source.tobytes()) self.assertEqual(output.getpixel((19, 30)), (0, 0, 200)) self.assertEqual(self.result.getpixel((50, 50)), (0, 0, 200)) def test_feather_blends_only_inside_expanded_boundaries(self): output = outpaint.composite_original(self.result, self.source, (20, 20, 60, 60), 10) self.assertEqual(output.getpixel((20, 50)), (0, 0, 200)) self.assertEqual(output.getpixel((25, 50)), (100, 0, 100)) self.assertEqual(output.getpixel((30, 50)), (200, 0, 0)) self.assertEqual(output.getpixel((50, 79)), (0, 0, 200)) self.assertEqual(output.getpixel((50, 74)), (100, 0, 100)) self.assertEqual(output.getpixel((50, 69)), (200, 0, 0)) self.assertEqual(output.getpixel((90, 90)), (0, 0, 200)) def test_edges_flush_with_canvas_are_never_feathered(self): source = Image.new("RGB", (60, 100), (200, 0, 0)) output = outpaint.composite_original(self.result, source, (0, 0, 60, 100), 10) for pixel in ((0, 0), (0, 99), (49, 0), (49, 99)): self.assertEqual(output.getpixel(pixel), (200, 0, 0)) self.assertEqual(output.getpixel((59, 0)), (0, 0, 200)) def test_mismatched_or_outside_placement_is_rejected(self): for box in ((-1, 0, 60, 60), (50, 50, 60, 60), (20, 20, 59, 60)): with self.assertRaisesRegex(ValueError, "placement"): outpaint.composite_original(self.result, self.source, box) class PrepareTests(unittest.TestCase): def test_prepare_downloads_pinned_adapter_and_keeps_source(self): download = Mock(return_value="cached-outpaint") data = request(prompt="Scene: A lake.") with patch.dict(sys.modules, {"huggingface_hub": types.SimpleNamespace(hf_hub_download=download)}): result = outpaint.prepare(data, "private-token") download.assert_called_once_with(repo_id=outpaint.OUTPAINT_REPO, filename=outpaint.OUTPAINT_FILE, revision=outpaint.OUTPAINT_REVISION, token="private-token") self.assertEqual(result["_outpaint_path"], "cached-outpaint") self.assertEqual(result["input_image_1"].size, (120, 80)) self.assertEqual((result["width"], result["height"]), result["_outpaint_canvas"].size) self.assertEqual(result["seed"], 17) self.assertFalse(result["randomize_seed"]) self.assertEqual(result["prompt"], outpaint.OUTPAINT_PROMPT + " Scene: A lake.") self.assertNotIn("_outpaint_path", data) def test_random_seed_is_chosen_once_before_gpu(self): data = request() data["randomize_seed"] = True with patch.dict(sys.modules, {"huggingface_hub": types.SimpleNamespace(hf_hub_download=Mock())}), \ patch.object(outpaint.random, "randint", return_value=123) as random_seed: result = outpaint.prepare(data) random_seed.assert_called_once_with(0, outpaint.MAX_SEED) self.assertEqual(result["seed"], 123) self.assertFalse(result["randomize_seed"]) def test_invalid_inputs_never_download(self): invalid = [ {"input_image_1": None}, {"outpaint_left": -1}, {"outpaint_right": 101}, {"outpaint_top": float("nan")}, {"outpaint_bottom": float("inf")}, {"outpaint_left": 0, "outpaint_right": 0, "outpaint_top": 0, "outpaint_bottom": 0}, {"target_megapixels": 0}, {"target_megapixels": 2.1}, {"target_megapixels": "bad"}, {"outpaint_feather": -1}, {"outpaint_feather": 257}, {"outpaint_feather": 3.5}, {"outpaint_mode": "unknown"}, {"steps": 25}, {"steps": 6.5}, {"outpaint_mode": outpaint.MODE_BASE, "steps": 51}, {"seed": -1}, {"seed": float("nan")}, {"seed": 2**31}, {"seed": 0.5}, {"input_image_1": Image.new("RGB", (10000, 1))}, ] download = Mock() for values in invalid: data = request() data.update(values) with self.subTest(values=values), patch.dict(sys.modules, { "huggingface_hub": types.SimpleNamespace(hf_hub_download=download)}), \ self.assertRaises(ValueError): outpaint.prepare(data) download.assert_not_called() def test_estimate_increases_for_larger_output_steps_and_optional_adapters(self): small = request() larger = dict(small, target_megapixels=2) base = dict(small, outpaint_mode=outpaint.MODE_BASE, steps=25) optional = dict(base, user_lora_1_ref="person/custom", user_lora_1_scale=0.8) self.assertGreater(outpaint.estimate_seconds(larger), outpaint.estimate_seconds(small)) self.assertGreater(outpaint.estimate_seconds(base), outpaint.estimate_seconds(small)) self.assertGreater(outpaint.estimate_seconds(optional), outpaint.estimate_seconds(base)) class AdapterTests(unittest.TestCase): def test_pinned_adapter_conversion_and_load_happen_once(self): state = dict.fromkeys(range(384), "tensor") converted = dict.fromkeys(range(448), "converted") loader, converter = Mock(return_value=state), Mock(return_value=converted) pipe = types.SimpleNamespace(transformer=object(), load_lora_weights=Mock()) with patch.dict(sys.modules, {"safetensors.torch": types.SimpleNamespace(load_file=loader), "bfs_backend": types.SimpleNamespace(convert_bfs_state_dict=converter)}): outpaint.ensure_outpaint(pipe, "cached-outpaint") outpaint.ensure_outpaint(pipe, "cached-outpaint") loader.assert_called_once_with("cached-outpaint", device="cpu") converter.assert_called_once_with(state, pipe.transformer) pipe.load_lora_weights.assert_called_once_with(converted, adapter_name=outpaint.OUTPAINT_ADAPTER) def test_partial_adapter_is_never_applied(self): pipe = types.SimpleNamespace(transformer=object(), load_lora_weights=Mock()) for raw_count, converted_count in ((383, 448), (384, 446)): with patch.dict(sys.modules, { "safetensors.torch": types.SimpleNamespace(load_file=Mock(return_value=dict.fromkeys(range(raw_count)))), "bfs_backend": types.SimpleNamespace(convert_bfs_state_dict=Mock(return_value=dict.fromkeys(range(converted_count)))), }), self.assertRaises(ValueError): outpaint.ensure_outpaint(pipe, "cached-outpaint") pipe.load_lora_weights.assert_not_called() self.assertFalse(getattr(pipe, "_shared_outpaint_v2_loaded", False)) class FakePipe: def __init__(self, fail=False): self.scheduler = object() self.vae = types.SimpleNamespace(disable_tiling=Mock()) self.set_adapters = Mock() self.fail = fail def __call__(self, **kwargs): self.kwargs = kwargs self.called_scheduler = self.scheduler if self.fail: raise RuntimeError("simulated inference failure") return types.SimpleNamespace(images="latents") class GenerateTests(unittest.TestCase): def setUp(self): self.data = prepared() self.config = {"shift_terminal": 0.02, "shift": 1.0} self.scheduler_factory = Mock(side_effect=lambda config, **kwargs: {**config, **kwargs}) generator = types.SimpleNamespace(manual_seed=Mock(return_value="seeded-generator")) self.decoder = Mock(return_value=Image.new("RGB", self.data["_outpaint_canvas"].size, "blue")) self.modules = { "torch": types.SimpleNamespace(inference_mode=contextlib.nullcontext, Generator=Mock(return_value=generator)), "diffusers": types.SimpleNamespace(FlowMatchEulerDiscreteScheduler=types.SimpleNamespace(from_config=self.scheduler_factory)), "bfs_backend": types.SimpleNamespace(decode_latents=self.decoder), } def generate(self, pipe, **kwargs): with patch.dict(sys.modules, self.modules), patch.object(outpaint, "ensure_outpaint"): return outpaint.generate(pipe, self.data, turbo_adapter="turbo", base_scheduler_config=self.config, **kwargs) def test_turbo_uses_exact_single_reference_and_optional_loras(self): pipe = FakePipe() original = pipe.scheduler result = self.generate(pipe, user_adapters=["my1", "my2", "my3"], user_weights=[0.2, 0.3, 0.4]) self.assertEqual(pipe.kwargs["image"], [self.data["_outpaint_canvas"]]) self.assertEqual((pipe.kwargs["width"], pipe.kwargs["height"]), self.data["_outpaint_canvas"].size) self.assertEqual(pipe.kwargs["output_resolution"], self.data["_outpaint_resolution"]) self.assertEqual(pipe.kwargs["sigmas"], [1.0, 0.9375, 0.875, 0.75, 0.5, 0.25]) self.assertEqual(pipe.kwargs["num_inference_steps"], 6) self.assertEqual(pipe.kwargs["true_cfg_scale"], 1.0) self.assertEqual(pipe.kwargs["output_type"], "latent") self.assertNotIn("mask_image", pipe.kwargs) self.assertIsNone(pipe.kwargs["negative_prompt"]) self.assertEqual(pipe.called_scheduler["shift_terminal"], None) self.assertIs(pipe.scheduler, original) self.assertEqual(pipe.set_adapters.call_args_list[0].args[0], [outpaint.OUTPAINT_ADAPTER, "turbo", "my1", "my2", "my3"]) self.assertEqual(pipe.set_adapters.call_args_list[0].kwargs["adapter_weights"], [1, 1, 0.2, 0.3, 0.4]) pipe.set_adapters.assert_called_with(["turbo"], adapter_weights=[1.0]) x, y, width, height = self.data["_outpaint_box"] self.assertEqual(result.getpixel((x + width // 2, y + height // 2)), (211, 44, 19)) def test_cfg_two_preserves_negative_prompt_and_accounts_for_extra_guidance_work(self): pipe = FakePipe() # The default canvas fits one guidance pass in this budget, but not two. self.generate(pipe, kv_budget_gb=1.5) self.assertTrue(pipe.kwargs["use_kv_cache"]) self.data = prepared(guidance_scale=2, negative_prompt_text=" visible seams ") self.assertEqual(self.data["guidance_scale"], 2) self.assertEqual(self.data["negative_prompt_text"], "visible seams") self.generate(pipe, kv_budget_gb=1.5) self.assertEqual(pipe.kwargs["true_cfg_scale"], 2) self.assertEqual(pipe.kwargs["negative_prompt"], "visible seams") self.assertFalse(pipe.kwargs["use_kv_cache"]) guided = dict(self.data, outpaint_mode=outpaint.MODE_BASE, steps=25) single_pass = dict(guided, guidance_scale=1, negative_prompt_text="") self.assertGreater(outpaint.estimate_seconds(guided), outpaint.estimate_seconds(single_pass)) def test_base_excludes_turbo_uses_baseline_scheduler_and_25_steps(self): self.data.update(outpaint_mode=outpaint.MODE_BASE, steps=25) pipe = FakePipe() self.generate(pipe) self.assertIsNone(pipe.kwargs["sigmas"]) self.assertEqual(pipe.kwargs["num_inference_steps"], 25) self.assertEqual(pipe.called_scheduler["shift_terminal"], 0.02) self.assertEqual(pipe.set_adapters.call_args_list[0].args[0], [outpaint.OUTPAINT_ADAPTER]) pipe.set_adapters.assert_called_with(["turbo"], adapter_weights=[1.0]) self.assertEqual(self.config, {"shift_terminal": 0.02, "shift": 1.0}) def test_inference_failure_restores_scheduler_and_turbo_adapters(self): self.data.update(outpaint_mode=outpaint.MODE_BASE, steps=25) pipe = FakePipe(fail=True) original = pipe.scheduler with self.assertRaisesRegex(RuntimeError, "simulated inference failure"): self.generate(pipe) self.assertIs(pipe.scheduler, original) pipe.set_adapters.assert_called_with(["turbo"], adapter_weights=[1.0]) def test_adapter_and_decode_failures_restore_state(self): for stage in ("load", "decode"): pipe = FakePipe() original = pipe.scheduler self.decoder.side_effect = RuntimeError("decode failed") if stage == "decode" else None with patch.dict(sys.modules, self.modules), patch.object(outpaint, "ensure_outpaint", side_effect=RuntimeError("load failed") if stage == "load" else None), self.assertRaises(RuntimeError): outpaint.generate(pipe, self.data, turbo_adapter="turbo", base_scheduler_config=self.config) self.assertIs(pipe.scheduler, original) pipe.set_adapters.assert_called_with(["turbo"], adapter_weights=[1.0]) def test_unexpected_generated_dimensions_are_not_silently_resized(self): pipe = FakePipe() original = pipe.scheduler self.decoder.return_value = Image.new("RGB", (64, 64)) with self.assertRaisesRegex(ValueError, "unexpected canvas size"): self.generate(pipe) self.assertIs(pipe.scheduler, original) pipe.set_adapters.assert_called_with(["turbo"], adapter_weights=[1.0]) def test_cache_and_decode_controls_are_honored(self): pipe = FakePipe() self.data["vae_tiling"] = False self.generate(pipe, kv_budget_gb=0) self.assertFalse(pipe.kwargs["use_kv_cache"]) self.assertFalse(self.decoder.call_args.args[-1]) self.generate(pipe, kv_budget_gb=30) self.assertTrue(pipe.kwargs["use_kv_cache"]) def test_invalid_optional_adapter_state_is_rejected_before_mutation(self): for names, weights in ((["turbo"], [1]), ([outpaint.OUTPAINT_ADAPTER], [1]), (["custom"], []), (["custom"], [float("nan")])): pipe = FakePipe() with self.assertRaises(ValueError): self.generate(pipe, user_adapters=names, user_weights=weights) pipe.set_adapters.assert_not_called() def test_unprepared_or_misaligned_canvas_is_rejected(self): for change in ({"_outpaint_canvas": None}, {"_outpaint_resolution": 1}): original = self.data.copy() self.data.update(change) pipe = FakePipe() with self.assertRaises(ValueError): self.generate(pipe) pipe.set_adapters.assert_not_called() self.data = original if __name__ == "__main__": unittest.main()