"""CPU contract checks for Detail Enhancer preparation and shared-pipeline use.""" import contextlib import importlib.util import math from pathlib import Path import sys import tempfile import types import unittest from unittest.mock import Mock, patch from PIL import Image spec = importlib.util.spec_from_file_location("detail_under_test", Path(__file__).with_name("detail_backend.py")) detail = importlib.util.module_from_spec(spec) spec.loader.exec_module(detail) def request(**changes): data = dict(input_image_1=Image.new("RGB", (512, 384), (211, 44, 19)), target_megapixels=1.0, randomize_seed=False, seed=17) data.update(changes) return data def prepared(**changes): with patch.dict(sys.modules, {"huggingface_hub": types.SimpleNamespace( hf_hub_download=Mock(return_value="cached-detail"))}): return detail.prepare(request(**changes)) class PromptTests(unittest.TestCase): def test_trigger_is_retained_and_addition_is_idempotent(self): for text in (None, "", " ", "Preserve the original brushwork.", "Enhance this image with fine details.", "Please ENHANCE THIS IMAGE softly."): with self.subTest(text=text): result = detail.prompt_with_trigger(text) self.assertIn(detail.DETAIL_TRIGGER.lower(), result.lower()) self.assertEqual(detail.prompt_with_trigger(result), result) custom = "Preserve the original brushwork." self.assertEqual(detail.prompt_with_trigger(custom), detail.DETAIL_TRIGGER + ". " + custom) original = "Please ENHANCE THIS IMAGE softly." self.assertEqual(detail.prompt_with_trigger(original), original) def test_author_recipe_and_every_preset_keep_the_trigger(self): self.assertEqual(detail.prompt_with_trigger(None), detail.DETAIL_PROMPT) self.assertIn("preserving the original composition, lighting, and atmosphere", detail.DETAIL_PROMPT) for prompt in detail.DETAIL_PRESETS.values(): self.assertEqual(detail.prompt_with_trigger(prompt), prompt) class SourceAndGeometryTests(unittest.TestCase): def test_image_one_is_required(self): for value in (None, {}, {"path": "missing-detail-source.png"}, object()): with self.subTest(value=value), self.assertRaisesRegex(ValueError, "Image 1"): detail.source_image(request(input_image_1=value)) def test_exif_orientation_and_white_alpha_are_applied_without_mutation(self): image = Image.new("RGBA", (120, 80), (255, 0, 0, 0)) image.putpixel((0, 0), (255, 0, 0, 128)) image.getexif()[274] = 6 original_pixels = image.tobytes() result = detail.source_image(request(input_image_1=image)) self.assertEqual(result.mode, "RGB") self.assertEqual(result.size, (80, 120)) self.assertEqual(result.getpixel((0, 0)), (255, 255, 255)) self.assertEqual(result.getpixel((79, 0)), (255, 127, 127)) self.assertEqual(image.size, (120, 80)) self.assertEqual(image.mode, "RGBA") self.assertEqual(image.getexif()[274], 6) self.assertEqual(image.tobytes(), original_pixels) def test_path_and_upload_dictionary_are_supported(self): with tempfile.TemporaryDirectory() as directory: path = Path(directory) / "source.png" Image.new("RGBA", (80, 120), (10, 20, 30, 0)).save(path) for value in (str(path), {"path": str(path)}, {"name": str(path)}): with self.subTest(value=value): result = detail.source_image(request(input_image_1=value)) self.assertEqual(result.size, (80, 120)) self.assertEqual(result.getpixel((0, 0)), (255, 255, 255)) def test_output_dimensions_follow_original_aspect_and_upstream_32_rounding(self): # Independently reproduce the upstream resize equations away from caps. for size in ((512, 512), (1024, 768), (768, 1024), (999, 637), (2048, 1536)): for megapixels in (.5, .75, 1, 1.5, 2): with self.subTest(size=size, megapixels=megapixels): source = Image.new("RGB", size) width, height = detail.request_canvas(request(input_image_1=source, target_megapixels=megapixels)) factor = min(4.0, math.sqrt(megapixels * 1024**2 / (size[0] * size[1]))) self.assertEqual((width, height), (max(32, round(size[0] * factor / 32) * 32), max(32, round(size[1] * factor / 32) * 32))) self.assertEqual(width % 32 + height % 32, 0) self.assertLessEqual(abs(width / height / (size[0] / size[1]) - 1), .05) def test_four_megapixel_budget_and_four_times_scale_allow_only_upstream_rounding(self): for size in ((101, 101), (120, 80), (257, 193), (1024, 768), (999, 637), (2048, 1536)): with self.subTest(size=size): width, height = detail.request_canvas(request(input_image_1=Image.new("RGB", size), target_megapixels=4)) scale = min(4.0, math.sqrt(4 * 1024**2 / (size[0] * size[1]))) ideal_width, ideal_height = size[0] * scale, size[1] * scale self.assertEqual((width, height), (round(ideal_width / 32) * 32, round(ideal_height / 32) * 32)) self.assertLessEqual(width * height, 4 * 1024**2 + 16 * (ideal_width + ideal_height) + 256) self.assertLessEqual(width, size[0] * 4 + 16) self.assertLessEqual(height, size[1] * 4 + 16) self.assertEqual(width % 32 + height % 32, 0) def test_common_canvas_and_other_images_cannot_override_source_geometry(self): data = request() expected = detail.request_canvas(data) data.update(width=8192, height=256, input_image_2=Image.new("RGB", (20, 200)), input_images_extra=[Image.new("RGB", (120, 20))]) self.assertEqual(detail.request_canvas(data), expected) def test_reference_area_is_1024_squared_with_upstream_rounding(self): for width, height in ((512, 512), (120, 80), (300, 800), (999, 637)): with self.subTest(size=(width, height)): ref_width, ref_height = detail.reference_size(width, height) ratio = width / height self.assertEqual((ref_width, ref_height), (round(math.sqrt(1024**2 * ratio) / 32) * 32, round(math.sqrt(1024**2 / ratio) / 32) * 32)) self.assertLess(abs(ref_width * ref_height / 1024**2 - 1), .05) class PrepareTests(unittest.TestCase): def test_prepare_downloads_pinned_adapter_and_keeps_original_source_pixels(self): download = Mock(return_value="cached-detail") source = Image.new("RGB", (512, 384), (211, 44, 19)) data = request(input_image_1=source, prompt="Keep the painterly strokes.", input_image_2=Image.new("RGB", (32, 32)), input_images_extra=[source]) original = data.copy() with patch.dict(sys.modules, {"huggingface_hub": types.SimpleNamespace(hf_hub_download=download)}): result = detail.prepare(data, "private-token") download.assert_called_once_with(repo_id=detail.DETAIL_REPO, filename=detail.DETAIL_FILE, revision=detail.DETAIL_REVISION, token="private-token") self.assertRegex(detail.DETAIL_REVISION, r"^[0-9a-f]{40}$") self.assertEqual(result["_detail_path"], "cached-detail") self.assertEqual(result["input_image_1"].size, source.size) self.assertEqual(result["input_image_1"].tobytes(), source.tobytes()) self.assertIsNot(result["input_image_1"], source) self.assertEqual(result["_detail_reference"].size, detail.reference_size(*source.size)) self.assertIsNone(result["input_image_2"]) self.assertIsNone(result["input_images_extra"]) self.assertEqual(data, original) self.assertNotIn("_detail_reference", data) def test_turbo_six_steps_is_default_and_original_base_keeps_25_steps(self): turbo = prepared() self.assertFalse(detail.is_base(turbo)) self.assertEqual(turbo["steps"], 6) base = prepared(detail_mode=detail.MODE_BASE) self.assertTrue(detail.is_base(base)) self.assertEqual(base["steps"], 25) def test_random_seed_is_chosen_once_and_not_changed_when_reprepared(self): with patch.dict(sys.modules, {"huggingface_hub": types.SimpleNamespace(hf_hub_download=Mock())}), \ patch.object(detail.random, "randint", return_value=123) as choose_seed: result = detail.prepare(request(randomize_seed=True)) again = detail.prepare(result) choose_seed.assert_called_once_with(0, detail.MAX_SEED) self.assertEqual(result["seed"], 123) self.assertEqual(again["seed"], 123) self.assertFalse(result["randomize_seed"]) self.assertFalse(again["randomize_seed"]) def test_invalid_inputs_are_rejected_before_download(self): invalid = [ {"input_image_1": None}, {"detail_mode": "unknown"}, {"target_megapixels": 0}, {"target_megapixels": 4.1}, {"target_megapixels": "bad"}, {"detail_strength": -.1}, {"detail_strength": 1.6}, {"detail_strength": float("nan")}, {"steps": 3}, {"steps": 9}, {"steps": 6.5}, {"steps": float("inf")}, {"detail_mode": detail.MODE_BASE, "steps": 7}, {"detail_mode": detail.MODE_BASE, "steps": 51}, {"guidance_scale": 0}, {"guidance_scale": 10.1}, {"guidance_scale": float("nan")}, {"seed": -1}, {"seed": 2**31}, {"seed": .5}, {"seed": float("inf")}, {"input_image_1": Image.new("RGB", (10000, 1))}, ] download = Mock() for changes in invalid: with self.subTest(changes=changes), patch.dict(sys.modules, { "huggingface_hub": types.SimpleNamespace(hf_hub_download=download)}), \ self.assertRaises(ValueError): detail.prepare(request(**changes)) download.assert_not_called() def test_duration_estimate_accounts_for_canvas_steps_and_optional_adapters(self): small = request() base = dict(small, detail_mode=detail.MODE_BASE, steps=25) self.assertGreater(detail.estimate_seconds(dict(small, target_megapixels=4)), detail.estimate_seconds(small)) self.assertGreater(detail.estimate_seconds(base), detail.estimate_seconds(small)) self.assertGreater(detail.estimate_seconds(dict(base, user_lora_1_ref="person/custom", user_lora_1_scale=.8)), detail.estimate_seconds(base)) self.assertEqual(detail.estimate_seconds(dict(base, user_lora_1_ref="person/custom", user_lora_1_scale=0)), detail.estimate_seconds(base)) class AdapterTests(unittest.TestCase): def test_complete_384_tensor_adapter_converts_to_448_and_loads_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)}): detail.ensure_detail(pipe, "cached-detail") detail.ensure_detail(pipe, "cached-detail") loader.assert_called_once_with("cached-detail", device="cpu") converter.assert_called_once_with(state, pipe.transformer) pipe.load_lora_weights.assert_called_once_with(converted, adapter_name=detail.DETAIL_ADAPTER) self.assertTrue(pipe._shared_detail_v1_loaded) def test_incomplete_or_unexpected_adapter_counts_never_load(self): for raw_count, converted_count in ((383, 448), (385, 448), (384, 446), (384, 450)): pipe = types.SimpleNamespace(transformer=object(), load_lora_weights=Mock()) converter = Mock(return_value=dict.fromkeys(range(converted_count))) with self.subTest(raw_count=raw_count, converted_count=converted_count), 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=converter), }), self.assertRaises(ValueError): detail.ensure_detail(pipe, "cached-detail") pipe.load_lora_weights.assert_not_called() self.assertFalse(getattr(pipe, "_shared_detail_v1_loaded", False)) if raw_count != 384: converter.assert_not_called() def test_conversion_failure_names_detail_and_does_not_mark_loaded(self): pipe = types.SimpleNamespace(transformer=object(), load_lora_weights=Mock()) with patch.dict(sys.modules, { "safetensors.torch": types.SimpleNamespace(load_file=Mock(return_value=dict.fromkeys(range(384)))), "bfs_backend": types.SimpleNamespace(convert_bfs_state_dict=Mock(side_effect=ValueError("Missing BFS LoRA pair"))), }), self.assertRaisesRegex(ValueError, "Missing Detail Enhancer LoRA pair"): detail.ensure_detail(pipe, "cached-detail") pipe.load_lora_weights.assert_not_called() self.assertFalse(getattr(pipe, "_shared_detail_v1_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": .02, "shift": 1.0} self.scheduler_factory = Mock(side_effect=lambda config, **kwargs: {**config, **kwargs}) self.generator = types.SimpleNamespace(manual_seed=Mock(return_value="seeded-generator")) self.decoder = Mock(return_value=Image.new("RGB", (self.data["width"], self.data["height"]), "blue")) self.sigmas = Mock(return_value=[1.0, .9375, .875, .75, .5, .25]) self.download = Mock(side_effect=AssertionError("No downloads inside GPU generation")) self.external = Mock(side_effect=AssertionError("No external inference or new pipeline")) self.modules = { "torch": types.SimpleNamespace(inference_mode=contextlib.nullcontext, Generator=Mock(return_value=self.generator)), "diffusers": types.SimpleNamespace(FlowMatchEulerDiscreteScheduler=types.SimpleNamespace(from_config=self.scheduler_factory), DiffusionPipeline=self.external, QwenImagePipeline=self.external), "bfs_backend": types.SimpleNamespace(decode_latents=self.decoder, turbo_sigmas=self.sigmas), "huggingface_hub": types.SimpleNamespace(hf_hub_download=self.download, InferenceClient=self.external), } def generate(self, pipe, **kwargs): with patch.dict(sys.modules, self.modules), patch.object(detail, "ensure_detail"): return detail.generate(pipe, self.data, turbo_adapter="turbo", base_scheduler_config=self.config, **kwargs) def test_default_turbo_reuses_pipe_with_single_reference_cfg_one_and_three_optional_adapters(self): pipe = FakePipe() original_scheduler = pipe.scheduler result = self.generate(pipe, user_adapters=["my1", "my2", "my3"], user_weights=[.2, .3, .4]) self.assertEqual(pipe.kwargs["image"], [self.data["_detail_reference"]]) self.assertEqual((pipe.kwargs["width"], pipe.kwargs["height"]), (self.data["width"], self.data["height"])) self.assertEqual(pipe.kwargs["output_resolution"], 1024) self.assertEqual(pipe.kwargs["num_inference_steps"], 6) self.assertEqual(pipe.kwargs["sigmas"], self.sigmas.return_value) self.sigmas.assert_called_once_with(6) self.assertEqual(pipe.kwargs["true_cfg_scale"], 1.0) self.assertEqual(pipe.kwargs["output_type"], "latent") self.assertEqual(pipe.kwargs["generator"], "seeded-generator") self.generator.manual_seed.assert_called_once_with(17) self.modules["torch"].Generator.assert_called_once_with(device="cuda") 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_scheduler) self.assertEqual(pipe.set_adapters.call_args_list[0].args[0], [detail.DETAIL_ADAPTER, "turbo", "my1", "my2", "my3"]) self.assertEqual(pipe.set_adapters.call_args_list[0].kwargs["adapter_weights"], [1, 1, .2, .3, .4]) pipe.set_adapters.assert_called_with(["turbo"], adapter_weights=[1.0]) self.assertEqual(result.size, (self.data["width"], self.data["height"])) self.assertEqual(result.mode, "RGB") self.assertEqual(result.getpixel((0, 0)), (0, 0, 255)) self.download.assert_not_called() self.external.assert_not_called() def test_cfg_two_preserves_negative_prompt_and_accounts_for_extra_guidance_work(self): pipe = FakePipe() # The default reference fits one guidance pass in this budget, but not two. self.generate(pipe, kv_budget_gb=3) self.assertTrue(pipe.kwargs["use_kv_cache"]) self.data = prepared(guidance_scale=2, negative_prompt_text=" blurry detail ") self.assertEqual(self.data["guidance_scale"], 2) self.assertEqual(self.data["negative_prompt_text"], "blurry detail") self.generate(pipe, kv_budget_gb=3) self.assertEqual(pipe.kwargs["true_cfg_scale"], 2) self.assertEqual(pipe.kwargs["negative_prompt"], "blurry detail") self.assertFalse(pipe.kwargs["use_kv_cache"]) guided = dict(self.data, detail_mode=detail.MODE_BASE, steps=25) single_pass = dict(guided, guidance_scale=1, negative_prompt_text="") self.assertGreater(detail.estimate_seconds(guided), detail.estimate_seconds(single_pass)) def test_duplicate_optional_adapters_merge_weights_and_preserve_required_strength(self): self.data["detail_strength"] = .75 pipe = FakePipe() self.generate(pipe, user_adapters=["same", "other", "same"], user_weights=[.2, .4, .3]) call = pipe.set_adapters.call_args_list[0] self.assertEqual(call.args[0], [detail.DETAIL_ADAPTER, "turbo", "same", "other"]) self.assertEqual(call.kwargs["adapter_weights"], [.75, 1.0, .5, .4]) def test_base_excludes_turbo_and_custom_sigmas_and_preserves_base_scheduler(self): self.data.update(detail_mode=detail.MODE_BASE, steps=25) pipe = FakePipe() self.generate(pipe) self.assertIsNone(pipe.kwargs["sigmas"]) self.sigmas.assert_not_called() self.assertEqual(pipe.kwargs["num_inference_steps"], 25) self.assertEqual(pipe.called_scheduler["shift_terminal"], .02) self.scheduler_factory.assert_called_once_with(self.config) self.assertEqual(pipe.set_adapters.call_args_list[0].args[0], [detail.DETAIL_ADAPTER]) pipe.set_adapters.assert_called_with(["turbo"], adapter_weights=[1.0]) self.assertEqual(self.config, {"shift_terminal": .02, "shift": 1.0}) def test_inference_failure_restores_scheduler_tiling_and_turbo_adapters(self): self.data.update(detail_mode=detail.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.vae.disable_tiling.assert_called() pipe.set_adapters.assert_called_with(["turbo"], adapter_weights=[1.0]) def test_adapter_scheduler_and_decode_failures_restore_shared_state(self): for stage in ("load", "scheduler", "decode"): pipe = FakePipe() original = pipe.scheduler self.decoder.side_effect = RuntimeError("decode failed") if stage == "decode" else None self.scheduler_factory.side_effect = RuntimeError("scheduler failed") if stage == "scheduler" else lambda config, **kwargs: {**config, **kwargs} with self.subTest(stage=stage), patch.dict(sys.modules, self.modules), patch.object(detail, "ensure_detail", side_effect=RuntimeError("load failed") if stage == "load" else None), self.assertRaises(RuntimeError): detail.generate(pipe, self.data, turbo_adapter="turbo", base_scheduler_config=self.config) self.assertIs(pipe.scheduler, original) pipe.vae.disable_tiling.assert_called() pipe.set_adapters.assert_called_with(["turbo"], adapter_weights=[1.0]) def test_wrong_output_size_is_rejected_and_shared_state_restored(self): self.decoder.return_value = Image.new("RGB", (64, 64)) pipe = FakePipe() original = pipe.scheduler with self.assertRaisesRegex(ValueError, "unexpected output size"): self.generate(pipe) self.assertIs(pipe.scheduler, original) pipe.set_adapters.assert_called_with(["turbo"], adapter_weights=[1.0]) def test_cache_budget_and_vae_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.decoder.assert_called_with(pipe, "latents", self.data["height"], self.data["width"], False) self.data["vae_tiling"] = True self.generate(pipe, kv_budget_gb=30) self.assertTrue(pipe.kwargs["use_kv_cache"]) self.assertTrue(self.decoder.call_args.args[-1]) def test_bad_optional_adapter_state_is_rejected_before_mutation(self): for names, weights in ((["turbo"], [1]), ([detail.DETAIL_ADAPTER], [1]), (["custom"], []), (["custom"], [float("nan")]), (["custom"], [float("inf")])): pipe = FakePipe() with self.subTest(names=names, weights=weights), self.assertRaises(ValueError): self.generate(pipe, user_adapters=names, user_weights=weights) pipe.set_adapters.assert_not_called() self.assertFalse(hasattr(pipe, "kwargs")) def test_preparation_seed_and_budget_are_required_before_mutation(self): for changes, extra in (({"_detail_reference": None}, {}), ({"_detail_path": ""}, {}), ({"seed": -1}, {}), ({}, {"kv_budget_gb": -1}), ({}, {"kv_budget_gb": float("nan")})): previous = self.data.copy() self.data.update(changes) pipe = FakePipe() with self.subTest(changes=changes, extra=extra), self.assertRaises(ValueError): self.generate(pipe, **extra) pipe.set_adapters.assert_not_called() self.data = previous if __name__ == "__main__": unittest.main()