from __future__ import annotations import importlib.util import json import pathlib import unittest ROOT = pathlib.Path(__file__).parents[1] spec = importlib.util.spec_from_file_location( "dumas_clothing_layout_planner_test", ROOT / "dumas_clothing_layout_planner.py", ) PLANNER = importlib.util.module_from_spec(spec) assert spec.loader is not None spec.loader.exec_module(PLANNER) def inventory(*items): return json.dumps({"items": list(items)}) class ClothingLayoutPlannerTests(unittest.TestCase): def test_accepts_markdown_fenced_json_and_preserves_description(self): items = PLANNER.normalize_inventory("```json\n" + inventory({ "id": "shirt", "name": "shirt", "description": "blue linen", }) + "\n```") self.assertEqual(items[0]["description"], "blue linen") def test_repairs_literal_newlines_and_unescaped_prose_quotes(self): raw = '{"items":[{"id":"shirt","name":"shirt","description":"Blue shirt\nwith a "soft" collar"}]}' items = PLANNER.normalize_inventory(raw) self.assertEqual(items[0]["description"], 'Blue shirt\nwith a "soft" collar') def test_repairs_truncated_vlm_json_by_closing_open_containers(self): raw = '{"items":[{"id":"shoe","name":"shoe","description":"Black leather' items = PLANNER.normalize_inventory(raw) self.assertEqual(items[0]["description"], "Black leather") def test_ignores_vlm_prose_after_json_object(self): raw = inventory({"id": "hat", "name": "hat"}) + "\nHere is the inventory." self.assertEqual(PLANNER.normalize_inventory(raw)[0]["id"], "hat") def test_salvages_schema_items_when_json_repair_cannot_parse(self): raw = '{"items":[{"id":"shirt","name":"shirt","quantity":1,"description":"blue shirt' original_repair = PLANNER._repair_vlm_json PLANNER._repair_vlm_json = lambda _text: '{broken' try: items = PLANNER.normalize_inventory(raw) finally: PLANNER._repair_vlm_json = original_repair self.assertEqual(items[0]["id"], "shirt") self.assertEqual(items[0]["description"], "blue shirt") def test_quantities_and_pairs_create_deterministic_instances(self): plan = PLANNER.plan_layout(inventory( {"id": "sock", "name": "sock", "quantity": 3}, {"id": "shoes", "name": "shoes", "quantity": 2, "unit": "pair"}, ), 1200, 800) self.assertEqual(len(plan["regions"]), 5) self.assertEqual([region["id"] for region in plan["regions"]], [ "sock_001", "sock_002", "sock_003", "shoes_001", "shoes_002", ]) self.assertEqual(plan["regions"][3]["original_id"], "shoes") self.assertEqual(plan["regions"][3]["unit"], "pair") def test_regions_are_in_bounds_and_do_not_overlap(self): plan = PLANNER.plan_layout(inventory(*[ {"id": f"item_{index}", "name": f"Object {index}", "size": "large" if index == 1 else "small"} for index in range(1, 11) ]), 1536, 1024, "balanced") regions = plan["regions"] for region in regions: self.assertGreaterEqual(region["x"], 0) self.assertGreaterEqual(region["y"], 0) self.assertLessEqual(region["x"] + region["width"], 1) self.assertLessEqual(region["y"] + region["height"], 1) for left_index, left in enumerate(regions): for right in regions[left_index + 1:]: overlap_x = min(left["x"] + left["width"], right["x"] + right["width"]) - max(left["x"], right["x"]) overlap_y = min(left["y"] + left["height"], right["y"] + right["height"]) - max(left["y"], right["y"]) self.assertFalse(overlap_x > 1e-7 and overlap_y > 1e-7) def test_same_inputs_are_deterministic(self): value = inventory({"id": "a", "name": "A", "aspect_ratio": "portrait"}, {"id": "b", "name": "B"}) self.assertEqual(PLANNER.plan_layout(value), PLANNER.plan_layout(value)) def test_balanced_mode_gives_large_items_more_area(self): plan = PLANNER.plan_layout(inventory( {"id": "large", "name": "Large", "size": "large"}, {"id": "small", "name": "Small", "size": "small"}, ), 1200, 800) areas = {region["id"]: region["width"] * region["height"] for region in plan["regions"]} self.assertGreater(areas["large"], areas["small"]) @unittest.skipUnless(importlib.util.find_spec("PIL"), "Pillow is only available in the ComfyUI runtime") def test_empty_inventory_has_empty_layout_and_preview(self): plan = PLANNER.plan_layout('{"items": []}', 640, 480) preview = PLANNER.render_preview(plan, "#EEE8DC") self.assertEqual(plan["regions"], []) self.assertEqual(preview.size, (640, 480)) self.assertEqual(PLANNER.build_layout_prompt(plan), "") def test_layout_prompt_contains_ids_descriptions_and_positions(self): plan = PLANNER.plan_layout(inventory({ "id": "item_001", "name": "blue shirt", "description": "cotton shirt", })) prompt = PLANNER.build_layout_prompt(plan) self.assertIn("item_001", prompt) self.assertIn("blue shirt", prompt) self.assertIn("cotton shirt", prompt) self.assertIn("region", prompt) def test_flux3_boxes_use_official_order_and_1000_grid(self): plan = PLANNER.plan_layout(inventory( {"id": "item_001", "name": "blue shirt", "description": "blue cotton"}, {"id": "item_002", "name": "red bag", "description": "red leather"}, ), 1200, 800, "grid") rows = PLANNER.build_flux3_boxes(plan) self.assertEqual(len(rows), 2) for row in rows: top, left, bottom, right = row["bbox"] self.assertTrue(0 <= top < bottom <= 1000) self.assertTrue(0 <= left < right <= 1000) self.assertEqual(rows[0]["desc"], "blue cotton") def test_flux3_prompt_has_matching_tags_and_trailing_json(self): plan = PLANNER.plan_layout(inventory({ "id": "item_001", "name": "blue shirt", "description": "blue cotton", })) prompt, boxes_json = PLANNER.build_flux3_prompt(plan) self.assertIn("", prompt) self.assertTrue(prompt.endswith(boxes_json)) self.assertEqual(json.loads(boxes_json)[0]["id"], "item_001") def test_flux3_padding_shrinks_without_changing_legacy_plan(self): plan = PLANNER.plan_layout(inventory({"id": "item_001", "name": "shirt"})) original = dict(plan["regions"][0]) padded = PLANNER.build_flux3_boxes(plan, 10)[0]["bbox"] self.assertEqual(plan["regions"][0], original) self.assertGreater(padded[2] - padded[0], 0) self.assertGreater(padded[3] - padded[1], 0) def test_flux3_editing_mode_requires_source_coordinates(self): with self.assertRaisesRegex(ValueError, "editing.*source bounding boxes"): PLANNER.DumasClothingLayoutPlanner().plan( inventory({"id": "item_001", "name": "shirt"}), 640, 480, "balanced", 5, 3, "#EEE8DC", True, "flux3", 0, True, "editing", ) def test_invalid_fields_have_actionable_errors(self): with self.assertRaisesRegex(ValueError, "invalid unit"): PLANNER.normalize_inventory(inventory({"id": "x", "name": "X", "unit": "trio"})) with self.assertRaisesRegex(ValueError, "invalid JSON"): PLANNER.normalize_inventory("{not-json}") @unittest.skipUnless(importlib.util.find_spec("PIL"), "Pillow is only available in the ComfyUI runtime") def test_preview_matches_requested_dimensions_and_labels(self): plan = PLANNER.plan_layout(inventory({"id": "hat", "name": "hat"}), 777, 333, "grid") preview = PLANNER.render_preview(plan, "#123456", True) self.assertEqual(preview.size, (777, 333)) self.assertEqual(preview.getpixel((0, 0)), (18, 52, 86)) if __name__ == "__main__": unittest.main()