diff --git a/README.md b/README.md index e4aabce..c1396b1 100644 --- a/README.md +++ b/README.md @@ -213,6 +213,9 @@ previous clip is never passed forward as the continuity input. - 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 +- DUMAS Resolution + - Pixaroma-inspired ratio and AI-friendly size picker with 1:1, 16:9, 9:16, 2:1, 3:2, 2:3, 4:3, 3:4, and 4:5 presets. + - Includes Custom Ratio, Custom Resolution, 8/16/32/64px snapping, megapixel feedback, batch state, and width/height plus Empty-Latent-compatible outputs. ## Installation diff --git a/__init__.py b/__init__.py index 01544e1..19e99e1 100644 --- a/__init__.py +++ b/__init__.py @@ -35,6 +35,10 @@ from .dumas_h3_refmod_picker import ( NODE_CLASS_MAPPINGS as H3_REFMOD_PICKER_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as H3_REFMOD_PICKER_NODE_DISPLAY_NAME_MAPPINGS, ) +from .dumas_resolution_nodes import ( + NODE_CLASS_MAPPINGS as RESOLUTION_NODE_CLASS_MAPPINGS, + NODE_DISPLAY_NAME_MAPPINGS as RESOLUTION_NODE_DISPLAY_NAME_MAPPINGS, +) from .dumas_vendored_nodes import ( NODE_CLASS_MAPPINGS as VENDORED_NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS as VENDORED_NODE_DISPLAY_NAME_MAPPINGS, @@ -49,6 +53,7 @@ NODE_CLASS_MAPPINGS.update(H3_PROMPT_NODE_CLASS_MAPPINGS) NODE_CLASS_MAPPINGS.update(H3_UPSCALE_NODE_CLASS_MAPPINGS) NODE_CLASS_MAPPINGS.update(H3_REFMOD_NODE_CLASS_MAPPINGS) NODE_CLASS_MAPPINGS.update(H3_REFMOD_PICKER_NODE_CLASS_MAPPINGS) +NODE_CLASS_MAPPINGS.update(RESOLUTION_NODE_CLASS_MAPPINGS) NODE_CLASS_MAPPINGS.update(VENDORED_NODE_CLASS_MAPPINGS) NODE_DISPLAY_NAME_MAPPINGS = {} @@ -60,6 +65,7 @@ NODE_DISPLAY_NAME_MAPPINGS.update(H3_PROMPT_NODE_DISPLAY_NAME_MAPPINGS) NODE_DISPLAY_NAME_MAPPINGS.update(H3_UPSCALE_NODE_DISPLAY_NAME_MAPPINGS) NODE_DISPLAY_NAME_MAPPINGS.update(H3_REFMOD_NODE_DISPLAY_NAME_MAPPINGS) NODE_DISPLAY_NAME_MAPPINGS.update(H3_REFMOD_PICKER_NODE_DISPLAY_NAME_MAPPINGS) +NODE_DISPLAY_NAME_MAPPINGS.update(RESOLUTION_NODE_DISPLAY_NAME_MAPPINGS) NODE_DISPLAY_NAME_MAPPINGS.update(VENDORED_NODE_DISPLAY_NAME_MAPPINGS) WEB_DIRECTORY = "./js" diff --git a/dumas_resolution_nodes.py b/dumas_resolution_nodes.py new file mode 100644 index 0000000..00882db --- /dev/null +++ b/dumas_resolution_nodes.py @@ -0,0 +1,77 @@ +"""DUMAS resolution helpers inspired by Pixaroma's Resolution node.""" + +from __future__ import annotations + +import json + + +DEFAULT_STATE = { + "mode": "preset", + "ratio": "1:1", + "w": 1024, + "h": 1024, + "custom_w": 1024, + "custom_h": 1024, + "custom_ratio_w": 4, + "custom_ratio_h": 3, + "snap": 16, + "batch": 1, +} + + +def _clamp(value, low=64, high=16384): + return max(low, min(high, int(value))) + + +def resolution_wh(state_text): + try: + state = json.loads(state_text or "{}") + width = _clamp(state.get("w", DEFAULT_STATE["w"])) + height = _clamp(state.get("h", DEFAULT_STATE["h"])) + except (TypeError, ValueError, json.JSONDecodeError): + width, height = DEFAULT_STATE["w"], DEFAULT_STATE["h"] + return width, height + + +def _empty_latent(state_text, width, height): + import torch + + try: + batch = int(json.loads(state_text or "{}").get("batch", 1)) + except (TypeError, ValueError, json.JSONDecodeError): + batch = 1 + batch = max(1, min(64, batch)) + return {"samples": torch.zeros((batch, 4, max(1, height // 8), max(1, width // 8)))} + + +class DumasResolutionNode: + DESCRIPTION = ( + "DUMAS Resolution picker based on Pixaroma. Choose an AI-friendly aspect " + "ratio and size, or enter a custom ratio/resolution with snapping. Outputs " + "width, height, and an Empty-Latent-compatible image latent." + ) + + @classmethod + def INPUT_TYPES(cls): + return { + "required": {}, + "hidden": { + "ResolutionState": ( + "STRING", + {"default": json.dumps(DEFAULT_STATE)}, + ), + }, + } + + RETURN_TYPES = ("INT", "INT", "LATENT") + RETURN_NAMES = ("width", "height", "latent") + FUNCTION = "get_resolution" + CATEGORY = "Dumas/Values" + + def get_resolution(self, ResolutionState=""): + width, height = resolution_wh(ResolutionState) + return width, height, _empty_latent(ResolutionState, width, height) + + +NODE_CLASS_MAPPINGS = {"DumasResolution": DumasResolutionNode} +NODE_DISPLAY_NAME_MAPPINGS = {"DumasResolution": "DUMAS Resolution"} diff --git a/js/dumas_resolution.js b/js/dumas_resolution.js new file mode 100644 index 0000000..9e3a8b5 --- /dev/null +++ b/js/dumas_resolution.js @@ -0,0 +1,143 @@ +import { app } from "/scripts/app.js"; + +const CLASS = "DumasResolution"; +const STATE_PROP = "dumasResolutionState"; +const HIDDEN = "ResolutionState"; +const DEFAULT = { + mode: "preset", ratio: "1:1", w: 1024, h: 1024, + custom_w: 1024, custom_h: 1024, custom_ratio_w: 4, custom_ratio_h: 3, + snap: 16, batch: 1, +}; +const SIZES = { + "1:1": [[512,512],[768,768],[1024,1024],[1280,1280],[1328,1328],[1408,1408],[1536,1536],[2048,2048]], + "16:9": [[832,480],[1280,720],[1344,768],[1536,864],[1600,896],[1664,928],[1792,1008],[1920,1088]], + "9:16": [[480,832],[720,1280],[768,1344],[864,1536],[896,1600],[928,1664],[1008,1792],[1088,1920]], + "2:1": [[512,256],[1024,512],[1280,640],[1536,768],[1600,800],[1792,896],[1920,960],[2048,1024]], + "3:2": [[768,512],[1024,680],[1152,768],[1344,896],[1536,1024],[1632,1088],[1728,1152],[1920,1280]], + "2:3": [[512,768],[680,1024],[768,1152],[896,1344],[1024,1536],[1088,1632],[1152,1728],[1280,1920]], + "4:3": [[512,384],[640,480],[768,576],[1024,768],[1280,960],[1408,1056],[1600,1200],[1920,1440]], + "3:4": [[384,512],[480,640],[576,768],[768,1024],[960,1280],[1056,1408],[1200,1600],[1440,1920]], + "4:5": [[512,640],[640,800],[768,960],[832,1040],[1024,1280],[1152,1440],[1280,1600],[1536,1920]], +}; +const DEFAULT_SIZE = {"1:1":[1024,1024],"16:9":[1280,720],"9:16":[720,1280],"2:1":[1280,640],"3:2":[1152,768],"2:3":[768,1152],"4:3":[1024,768],"3:4":[768,1024],"4:5":[1024,1280]}; +const RATIOS = Object.keys(SIZES); +const clamp = (n) => Math.max(64, Math.min(4096, Number(n) || 1024)); +const snap = (n, step) => Math.round(n / step) * step; +const gcd = (a, b) => { while (b) [a, b] = [b, a % b]; return a || 1; }; + +function read(node) { + const raw = node.properties?.[STATE_PROP]; + if (raw) { try { return {...DEFAULT, ...JSON.parse(raw)}; } catch {} } + return {...DEFAULT}; +} +function write(node, value) { + node.properties ||= {}; + node.properties[STATE_PROP] = JSON.stringify({...DEFAULT, ...value}); + node.setDirtyCanvas?.(true, true); +} +function ratioPair(raw, rw, rh, step) { + let w = snap(clamp(raw), step); + let h = snap(w * rh / rw, step); + if (h > 4096) { h = 4096 - (4096 % step); w = snap(h * rw / rh, step); } + if (h < 64) { h = step; w = snap(h * rw / rh, step); } + return [clamp(w), clamp(h)]; +} +function stateText(node) { return JSON.stringify(read(node)); } +function collectNodes(graph, output = []) { + if (!graph) return output; + for (const node of graph._nodes || graph.nodes || []) { + if (node) output.push(node); + const inner = node?.subgraph || node?.graph || node?._graph; + if (inner && inner !== graph) collectNodes(inner, output); + } + return output; +} +function injectState(result, nodes) { + for (const id in result?.output || {}) { + const entry = result.output[id]; + if (entry?.class_type !== CLASS) continue; + const node = nodes.find((n) => String(n.id) === String(id) || String(n.id) === String(id).split(":").pop()); + entry.inputs ||= {}; + entry.inputs[HIDDEN] = stateText(node || {properties: {}}); + } +} + +const style = document.createElement("style"); +style.textContent = ` +.dumas-res { box-sizing:border-box; width:100%; padding:6px; background:#292929; color:#ddd; font:11px system-ui; } +.dumas-res .chips { display:grid; grid-template-columns:repeat(3,1fr); gap:4px; } +.dumas-res button { min-height:26px; padding:2px 5px; border:1px solid #555; border-radius:4px; background:#1d1d1d; color:#ddd; cursor:pointer; } +.dumas-res button.active { background:#b9573d; color:white; border-color:#ef8c6d; } +.dumas-res .wide { grid-column:span 3; } +.dumas-res .sizes { margin-top:6px; display:grid; grid-template-columns:repeat(2,1fr); gap:3px; max-height:170px; overflow:auto; } +.dumas-res .size { text-align:left; font-family:ui-monospace,monospace; } +.dumas-res .custom { display:grid; grid-template-columns:1fr 1fr; gap:4px; margin-top:6px; } +.dumas-res input { width:100%; box-sizing:border-box; background:#181818; color:#eee; border:1px solid #555; border-radius:3px; padding:4px; } +.dumas-res .label { grid-column:1/-1; color:#aaa; } +.dumas-res .meta { margin-top:5px; color:#9dd8a5; font-family:ui-monospace,monospace; } +`; +document.head.appendChild(style); + +function render(node, root) { + const s = read(node), ratio = s.ratio || "1:1"; + root.replaceChildren(); + const chips = document.createElement("div"); chips.className = "chips"; + [...RATIOS, "custom_ratio", "custom"].forEach((id) => { + const button = document.createElement("button"); + button.textContent = id === "custom_ratio" ? "Custom Ratio" : id === "custom" ? "Custom Resolution" : id; + button.className = (s.mode === "preset" && id === ratio) || (s.mode === id) ? "active" : ""; + button.dataset.id = id; chips.append(button); + }); + root.append(chips); + if (s.mode === "custom" || s.mode === "custom_ratio") { + const panel = document.createElement("div"); panel.className = "custom"; + const label = document.createElement("div"); label.className = "label"; + label.textContent = s.mode === "custom" ? "Custom resolution · snap" : "Custom ratio · width · snap"; + panel.append(label); + const fields = s.mode === "custom" ? [["custom_w", "Width"],["custom_h", "Height"]] : [["custom_ratio_w", "Ratio W"],["custom_ratio_h", "Ratio H"]]; + for (const [key, text] of fields) { const input=document.createElement("input"); input.dataset.key=key; input.title=text; input.value=s[key]; input.placeholder=text; panel.append(input); } + const snapLabel=document.createElement("div"); snapLabel.className="label"; snapLabel.textContent="Snap step"; panel.append(snapLabel); + for (const step of [8,16,32,64]) { const b=document.createElement("button"); b.textContent=`${step}px`; b.dataset.snap=step; b.className=Number(s.snap)===step?"active":""; panel.append(b); } + root.append(panel); + } else { + const sizes = document.createElement("div"); sizes.className="sizes"; + for (const [w,h] of (SIZES[ratio] || [])) { const b=document.createElement("button"); b.className="size"; b.dataset.w=w; b.dataset.h=h; b.textContent=`${w} × ${h} (${(w*h/1e6).toFixed(2)} MP)`; if (w===Number(s.w)&&h===Number(s.h)) b.classList.add("active"); sizes.append(b); } + root.append(sizes); + } + const meta=document.createElement("div"); meta.className="meta"; meta.textContent=`Output ${s.w} × ${s.h} · ${(s.w*s.h/1e6).toFixed(2)} MP · batch ${Math.max(1,Math.min(64,Number(s.batch)||1))}`; root.append(meta); +} + +function setup(node) { + node.resizable = false; + const root=document.createElement("div"); root.className="dumas-res"; + const widget=node.addDOMWidget("dumas_resolution_ui", "custom", root, {serialize:false, getValue:()=>read(node), setValue:()=>{}, getMinHeight:()=>250}); + widget.computeLayoutSize=()=>({minHeight:250,minWidth:1}); + root.addEventListener("click", (event) => { + const button=event.target.closest("button"); if (!button) return; + const s=read(node), id=button.dataset.id; + if (id && SIZES[id]) { const [w,h]=DEFAULT_SIZE[id]; write(node,{...s,mode:"preset",ratio:id,w,h}); } + else if (id === "custom") write(node,{...s,mode:"custom",w:s.custom_w,h:s.custom_h}); + else if (id === "custom_ratio") write(node,{...s,mode:"custom_ratio",w:ratioPair(s.w,s.custom_ratio_w,s.custom_ratio_h,s.snap)[0],h:ratioPair(s.w,s.custom_ratio_w,s.custom_ratio_h,s.snap)[1]}); + else if (button.dataset.w) write(node,{...s,w:Number(button.dataset.w),h:Number(button.dataset.h)}); + else if (button.dataset.snap) { const step=Number(button.dataset.snap); const next={...s,snap:step}; if(s.mode==="custom") { next.w=snap(clamp(s.custom_w),step); next.h=snap(clamp(s.custom_h),step); } else if(s.mode==="custom_ratio") [next.w,next.h]=ratioPair(s.w,s.custom_ratio_w,s.custom_ratio_h,step); write(node,next); return; } + render(node,root); + }); + root.addEventListener("change", (event) => { const key=event.target.dataset.key; if(!key)return; const s=read(node), value=Math.max(1,Math.min(16384,Number(event.target.value)||1)); s[key]=value; if(s.mode==="custom") { s.w=snap(clamp(s.custom_w),s.snap); s.h=snap(clamp(s.custom_h),s.snap); } else { [s.w,s.h]=ratioPair(s.w,s.custom_ratio_w,s.custom_ratio_h,s.snap); } write(node,s); render(node,root); }); + node._dumasResolutionRoot=root; node.size=[280,300]; queueMicrotask(()=>render(node,root)); +} + +const originalGraphToPrompt=app.graphToPrompt?.bind(app); +if (originalGraphToPrompt && !app.__dumasResolutionPromptHook) { + app.__dumasResolutionPromptHook=true; + app.graphToPrompt=async (...args)=>{ const result=await originalGraphToPrompt(...args); injectState(result,collectNodes(app.graph)); return result; }; +} +app.registerExtension({ + name:"Dumas.Resolution", + beforeRegisterNodeDef(nodeType,nodeData) { + if(nodeData?.name!==CLASS)return; + const oldConfigure=nodeType.prototype.onConfigure; + nodeType.prototype.onConfigure=function(...args){const result=oldConfigure?.apply(this,args); if(this._dumasResolutionRoot)render(this,this._dumasResolutionRoot); return result;}; + nodeType.prototype.onResize=function(){this.size=[280,300];}; + }, + nodeCreated(node){if(node.comfyClass===CLASS)setup(node);}, +}); diff --git a/tests/test_dumas_resolution_nodes.py b/tests/test_dumas_resolution_nodes.py new file mode 100644 index 0000000..3aedf44 --- /dev/null +++ b/tests/test_dumas_resolution_nodes.py @@ -0,0 +1,21 @@ +import json +import unittest + +import dumas_resolution_nodes as nodes + + +class DumasResolutionTests(unittest.TestCase): + def test_registers_dumas_resolution_node(self): + self.assertIn("DumasResolution", nodes.NODE_CLASS_MAPPINGS) + self.assertEqual(nodes.DumasResolutionNode.RETURN_NAMES, ("width", "height", "latent")) + self.assertIn("ResolutionState", nodes.DumasResolutionNode.INPUT_TYPES()["hidden"]) + + def test_resolution_state_is_clamped(self): + self.assertEqual(nodes.resolution_wh(json.dumps({"w": 32, "h": 20000})), (64, 16384)) + + def test_malformed_state_falls_back_to_default(self): + self.assertEqual(nodes.resolution_wh("not json"), (1024, 1024)) + + +if __name__ == "__main__": + unittest.main()