diff --git a/README.md b/README.md index 7da0010..e4aabce 100644 --- a/README.md +++ b/README.md @@ -203,12 +203,15 @@ previous clip is never passed forward as the continuity input. ## Other nodes - Dumas Image Compare + - Emits collision-safe temporary previews for every connected slot while retaining the DUMAS result output for downstream workflows. - Save Image Dumas - Saves PNG, JPG, or WebP to the ComfyUI output folder or a selected external folder. - Uses collision-safe counters for files and nested folders, with batch-safe numbering. - Preview mode writes temporary images for inspection without touching the destination folder. - Supports filename chips for inputs, date/time, counter, dimensions, and batch number. - Load Images from Folder Dumas + - Pixaroma-style folder browser with recursive listing, thumbnail metadata, selected/all/first-N/random modes, date/name sorting, alpha masks, and batch outputs. + - Outputs one list item per selected image, including image, mask, dimensions, filename, index, total, and absolute path. - Dumas JSON helpers ## Installation diff --git a/dumas_image_nodes.py b/dumas_image_nodes.py index 2b5fe41..c4f7752 100644 --- a/dumas_image_nodes.py +++ b/dumas_image_nodes.py @@ -30,7 +30,14 @@ def _folder_is_image(name): def _list_folder_image_files(real_folder, recursive=False): root = Path(real_folder) paths = root.rglob("*") if recursive else root.glob("*") - return sorted(str(path.relative_to(root)).replace(os.sep, "/") for path in paths if path.is_file() and _folder_is_image(path.name)) + files = [] + for path in paths: + if path.is_file() and _folder_is_image(path.name): + files.append({ + "file": str(path.relative_to(root)).replace(os.sep, "/"), + "mtime": path.stat().st_mtime, + }) + return sorted(files, key=lambda item: item["file"].lower()) def _next_counter_for_relative_path(base_directory, relative_template): @@ -114,7 +121,9 @@ class DumasImageCompareNode: for slot, image in enumerate((image1, image2), 1): if image is None: continue - path = Path(folder_paths.get_temp_directory()) / f"dumas_compare_{slot}.png" + # The compare viewer can be used by several executions at once. + # Fixed filenames caused one run to replace another run's preview. + path = Path(folder_paths.get_temp_directory()) / f"dumas_compare_{uuid.uuid4().hex}_{slot}.png" path.parent.mkdir(parents=True, exist_ok=True) _image_to_pil(image[0]).save(path) images.append({"filename": path.name, "subfolder": "", "type": "temp", "slot": slot}) @@ -214,24 +223,91 @@ def _safe_token(value): class DumasLoadImagesFolderNode: @classmethod def INPUT_TYPES(cls): - return {"required": {"folder": ("STRING", {"default": ""})}} + # The browser UI stores its complete selection in this hidden input. + # Keep an optional folder for old workflows which used the original + # single-folder widget before the Pixaroma-style picker was added. + return { + "optional": {"folder": ("STRING", {"default": ""})}, + "hidden": {"LoadImagesFolderState": ("STRING", {"default": ""})}, + } - RETURN_TYPES = ("IMAGE", "MASK", "INT", "INT", "STRING", "INT", "INT") - RETURN_NAMES = ("image", "mask", "width", "height", "filename", "index", "total") + RETURN_TYPES = ("IMAGE", "MASK", "INT", "INT", "STRING", "INT", "INT", "STRING") + RETURN_NAMES = ("image", "mask", "width", "height", "filename", "index", "total", "path") + OUTPUT_IS_LIST = (True, True, True, True, True, True, True, True) FUNCTION = "load" CATEGORY = "Dumas/Image" - def load(self, folder): - files = sorted(path for path in Path(folder).iterdir() if path.suffix.lower() in _IMAGE_EXTENSIONS) if folder and Path(folder).is_dir() else [] - if not files: - raise ValueError("No image files found in the selected folder.") - image = Image.open(files[0]).convert("RGB") - import torch + def load(self, folder="", LoadImagesFolderState="", **_kwargs): + state = {} + if LoadImagesFolderState: + try: + state = json.loads(LoadImagesFolderState) + except (TypeError, ValueError): + state = {} + + selected_folder = str(state.get("folder") or folder or "").strip() + root = Path(selected_folder).expanduser() + if not root.is_dir(): + raise ValueError("Selected image folder does not exist.") + + recursive = bool(state.get("recursive", False)) + candidates = [Path(item["file"]) for item in _list_folder_image_files(str(root), recursive)] + by_relative = {path.as_posix(): path for path in candidates} + selected = [str(value).replace("\\", "/") for value in (state.get("selected") or [])] + mode = str(state.get("selection_mode") or "selected") + + if state: + if mode == "all": + relative_files = [path.as_posix() for path in candidates] + elif mode == "first_n": + try: + count = max(0, int(state.get("first_n", 0))) + except (TypeError, ValueError): + count = 0 + relative_files = [path.as_posix() for path in candidates[:count]] + elif mode == "random": + import random + relative_files = [random.choice([path.as_posix() for path in candidates])] if candidates else [] + else: + relative_files = [value for value in selected if value in by_relative] + else: + # Legacy workflows without the hidden state load the whole folder. + relative_files = [path.as_posix() for path in candidates] + + if not relative_files: + raise ValueError("No images selected in the folder.") + + sort_name = str(state.get("sort") or "name") + reverse = str(state.get("sort_dir") or "asc").lower() == "desc" + if sort_name == "date": + relative_files.sort(key=lambda name: (root / name).stat().st_mtime, reverse=reverse) + else: + relative_files.sort(key=str.lower, reverse=reverse) + import numpy as np - tensor = torch.from_numpy(np.asarray(image).astype("float32") / 255.0)[None, ...] - height, width = image.height, image.width - mask = torch.zeros((1, height, width), dtype=torch.float32) - return tensor, mask, width, height, files[0].name, 0, len(files) + import torch + images, masks, widths, heights, names, indexes, totals, paths = [], [], [], [], [], [], [], [] + total = len(relative_files) + for index, relative in enumerate(relative_files): + path = (root / relative).resolve() + if not _is_within_directory(root, path) or not path.is_file(): + continue + with Image.open(path) as source: + source = source.convert("RGBA") + rgba = np.asarray(source).astype("float32") / 255.0 + image = torch.from_numpy(rgba[..., :3].copy())[None, ...] + mask = torch.from_numpy((1.0 - rgba[..., 3]).copy()) + images.append(image) + masks.append(mask) + widths.append(int(source.width)) + heights.append(int(source.height)) + names.append(path.name) + indexes.append(index) + totals.append(total) + paths.append(str(path)) + if not images: + raise ValueError("No readable images were found in the selected folder.") + return images, masks, widths, heights, names, indexes, totals, paths NODE_CLASS_MAPPINGS = { diff --git a/tests/test_dumas_image_nodes.py b/tests/test_dumas_image_nodes.py index 4f0c486..f91e3b1 100644 --- a/tests/test_dumas_image_nodes.py +++ b/tests/test_dumas_image_nodes.py @@ -78,11 +78,28 @@ class DumasImageNodeTests(unittest.TestCase): self.assertEqual(result["ui"]["images"], []) self.assertIsNone(result["result"][0]) + def test_compare_preview_names_are_unique(self): + first = self.nodes.DumasImageCompareNode().compare_images(FakeBatch()) + second = self.nodes.DumasImageCompareNode().compare_images(FakeBatch()) + self.assertNotEqual( + first["ui"]["images"][0]["filename"], + second["ui"]["images"][0]["filename"], + ) + def test_load_folder_node_has_expected_outputs(self): self.assertEqual( self.nodes.DumasLoadImagesFolderNode.RETURN_NAMES, - ("image", "mask", "width", "height", "filename", "index", "total"), + ("image", "mask", "width", "height", "filename", "index", "total", "path"), ) + self.assertEqual(self.nodes.DumasLoadImagesFolderNode.OUTPUT_IS_LIST, (True,) * 8) + + def test_folder_listing_includes_thumbnail_metadata(self): + with tempfile.TemporaryDirectory() as directory: + path = os.path.join(directory, "frame.png") + open(path, "wb").close() + files = self.nodes._list_folder_image_files(directory) + self.assertEqual(files[0]["file"], "frame.png") + self.assertIn("mtime", files[0]) def test_counter_uses_highest_existing_file(self): with tempfile.TemporaryDirectory() as directory: