v1.1.0 Update
- Added resize_method to the Multi Image Loader node for more resize options - Added insert_mode which allows you to enter in seconds instead of frames on the LTX Sequencer node - Updated workflows with more notes - Re-added tiny vae to workflows - Fixed various bugs - more things i can't rememeber
This commit is contained in:
@@ -22,28 +22,47 @@ function toggleWidget(widget, visible) {
|
||||
}
|
||||
}
|
||||
|
||||
// --- NEW SYNC HELPER FUNCTION ---
|
||||
// Finds all other LTXSequencer nodes globally and mirrors the value to them
|
||||
function syncWidgetAcrossNodes(sourceNode, widgetName, value) {
|
||||
/**
|
||||
* FULL STATE SYNC:
|
||||
* Instead of syncing one widget, we push the entire properties object
|
||||
* to ensure no values are ever lost during subgraph transitions or deletions.
|
||||
*/
|
||||
function syncFullStateAcrossNodes(sourceNode) {
|
||||
if (!window._LTXSequencerGlobalNodes) return;
|
||||
|
||||
for (const targetNode of window._LTXSequencerGlobalNodes) {
|
||||
// Target all OTHER LTXSequencer nodes by direct object reference
|
||||
if (targetNode !== sourceNode) {
|
||||
if (targetNode === sourceNode) continue;
|
||||
|
||||
// 1. Always update the hidden properties cache so it remembers the sync
|
||||
// even if the widget isn't currently visible (e.g. fewer images loaded right now)
|
||||
targetNode.properties[widgetName] = value;
|
||||
// 1. Mirror the properties object completely
|
||||
// We use a shallow copy to ensure we don't accidentally share object references
|
||||
const newState = { ...sourceNode.properties };
|
||||
targetNode.properties = { ...targetNode.properties, ...newState };
|
||||
|
||||
// 2. If the widget is currently visible on the UI, update it visually
|
||||
if (targetNode.widgets) {
|
||||
const targetWidget = targetNode.widgets.find(w => w.name === widgetName);
|
||||
if (targetWidget && targetWidget.value !== value) {
|
||||
targetWidget.value = value;
|
||||
targetNode.setDirtyCanvas(true, false);
|
||||
// 2. Check if we need to rebuild the widget list (if num_images changed)
|
||||
const targetImageCount = targetNode.properties["num_images"] || 0;
|
||||
const currentVisibleCount = targetNode._currentImageCount;
|
||||
|
||||
if (targetImageCount !== currentVisibleCount) {
|
||||
targetNode._applyWidgetCount(targetImageCount);
|
||||
}
|
||||
|
||||
// 3. Update all existing widget values visually
|
||||
if (targetNode.widgets) {
|
||||
let modeChanged = false;
|
||||
targetNode.widgets.forEach(w => {
|
||||
const newValue = targetNode.properties[w.name];
|
||||
if (newValue !== undefined && w.value !== newValue) {
|
||||
w.value = newValue;
|
||||
if (w.name === "insert_mode") modeChanged = true;
|
||||
}
|
||||
});
|
||||
|
||||
if (modeChanged && targetNode._updateVisibility) {
|
||||
targetNode._updateVisibility();
|
||||
}
|
||||
}
|
||||
|
||||
targetNode.setDirtyCanvas(true, false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,12 +107,76 @@ app.registerExtension({
|
||||
node.widgets.splice(idx, 0, separator);
|
||||
}
|
||||
};
|
||||
setTimeout(moveSeparator, 50); // Small delay to ensure num_images is present
|
||||
setTimeout(moveSeparator, 50);
|
||||
|
||||
// Binds custom callbacks to python-schema generated widgets
|
||||
node._hookStaticWidgets = function() {
|
||||
if (!this.widgets) return;
|
||||
const staticNames = ["num_images", "insert_mode", "frame_rate"];
|
||||
staticNames.forEach(name => {
|
||||
const w = this.widgets.find(w => w.name === name);
|
||||
if (w && !w._has_custom_callback) {
|
||||
const orig = w.callback;
|
||||
w.callback = (val) => {
|
||||
this.properties[name] = val;
|
||||
|
||||
if (name === "num_images") {
|
||||
this._applyWidgetCount(val);
|
||||
}
|
||||
|
||||
// Push full state to siblings
|
||||
syncFullStateAcrossNodes(this);
|
||||
|
||||
if (name === "insert_mode") {
|
||||
this._updateVisibility();
|
||||
}
|
||||
if (orig) orig.apply(w, [val]);
|
||||
};
|
||||
w._has_custom_callback = true;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// Handles show/hiding widgets based on insertion method
|
||||
node._updateVisibility = function() {
|
||||
const mode = this.properties["insert_mode"] || "frames";
|
||||
if (!this.widgets) return;
|
||||
|
||||
let changed = false;
|
||||
for (const w of this.widgets) {
|
||||
let shouldBeVisible = true;
|
||||
|
||||
if (w.name.startsWith("insert_frame_")) {
|
||||
shouldBeVisible = (mode === "frames");
|
||||
} else if (w.name.startsWith("insert_second_")) {
|
||||
shouldBeVisible = (mode === "seconds");
|
||||
}
|
||||
|
||||
const isHidden = (w.type === "hidden");
|
||||
if (shouldBeVisible && isHidden) {
|
||||
toggleWidget(w, true);
|
||||
changed = true;
|
||||
} else if (!shouldBeVisible && !isHidden) {
|
||||
toggleWidget(w, false);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (changed) {
|
||||
this.setDirtyCanvas(true, true);
|
||||
requestAnimationFrame(() => {
|
||||
if (this.computeSize) {
|
||||
this.setSize(this.computeSize());
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Core update: synchronize widget visibility to match imageCount
|
||||
node._applyWidgetCount = function(count) {
|
||||
const isInitialLoad = this._currentImageCount === -1;
|
||||
this._hookStaticWidgets();
|
||||
|
||||
const isInitialLoad = this._currentImageCount === -1;
|
||||
if (this._currentImageCount === count && !isInitialLoad) return;
|
||||
this._currentImageCount = count;
|
||||
|
||||
@@ -104,20 +187,20 @@ app.registerExtension({
|
||||
numWidget.value = Math.max(0, Math.min(count || 0, 50));
|
||||
}
|
||||
|
||||
// 1. Store current widget values in properties BEFORE removing them
|
||||
// We skip reading from `this.widgets` on the initial load because it might be scrambling.
|
||||
if (!isInitialLoad && this.widgets) {
|
||||
// 1. Update properties from current widget values before restructuring
|
||||
if (this.widgets) {
|
||||
this.widgets.forEach(w => {
|
||||
if (w.name.startsWith("insert_frame_") || w.name.startsWith("strength_")) {
|
||||
this.properties[w.name] = w.value;
|
||||
if (w.name.startsWith("insert_") || w.name.startsWith("strength_") || ["num_images", "insert_mode", "frame_rate"].includes(w.name)) {
|
||||
if (w.type !== "hidden" && w.type !== "button") this.properties[w.name] = w.value;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 2. Remove all existing dynamic insert_frame/strength/header widgets
|
||||
// 2. Clear dynamic widgets
|
||||
if (this.widgets) {
|
||||
this.widgets = this.widgets.filter(w =>
|
||||
!w.name.startsWith("insert_frame_") &&
|
||||
!w.name.startsWith("insert_second_") &&
|
||||
!w.name.startsWith("strength_") &&
|
||||
!w.name.startsWith("header_")
|
||||
);
|
||||
@@ -125,9 +208,9 @@ app.registerExtension({
|
||||
this.widgets = [];
|
||||
}
|
||||
|
||||
// 3. Add back exactly the right amount of widgets using the cached values
|
||||
// 3. Rebuild precisely
|
||||
for (let i = 1; i <= count; i++) {
|
||||
// Add header/separator widget for grouping
|
||||
// Header
|
||||
const headerName = `header_${i}`;
|
||||
this.addCustomWidget({
|
||||
name: headerName,
|
||||
@@ -137,279 +220,175 @@ app.registerExtension({
|
||||
ctx.save();
|
||||
const margin = 10;
|
||||
const topPadding = 15;
|
||||
|
||||
// Subtle separator line
|
||||
ctx.strokeStyle = "#333";
|
||||
ctx.lineWidth = 1;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(margin, y + 5);
|
||||
ctx.lineTo(widget_width - margin, y + 5);
|
||||
ctx.stroke();
|
||||
|
||||
// Text label
|
||||
ctx.fillStyle = "#dddddd"; // Light gray
|
||||
ctx.fillStyle = "#dddddd";
|
||||
ctx.font = "bold 12px Arial";
|
||||
ctx.textAlign = "left";
|
||||
ctx.fillText(`Image #${i}`, margin, y + topPadding + 10);
|
||||
ctx.restore();
|
||||
},
|
||||
computeSize(width) {
|
||||
return [width, 35]; // Vertical gap + label height
|
||||
}
|
||||
computeSize(width) { return [width, 35]; }
|
||||
});
|
||||
|
||||
const insertFrameWidgetName = `insert_frame_${i}`;
|
||||
const strengthWidgetName = `strength_${i}`;
|
||||
// Helper to add widget with full sync
|
||||
const addSyncedWidget = (type, name, def, options) => {
|
||||
const saved = this.properties[name];
|
||||
return this.addWidget(type, name, saved !== undefined ? saved : def, (val) => {
|
||||
this.properties[name] = val;
|
||||
syncFullStateAcrossNodes(this);
|
||||
}, options);
|
||||
};
|
||||
|
||||
// Add insert_frame widget with Sync Callback
|
||||
const savedInsertFrameValue = this.properties[insertFrameWidgetName];
|
||||
this.addWidget("number", insertFrameWidgetName,
|
||||
savedInsertFrameValue !== undefined ? savedInsertFrameValue : 0,
|
||||
(value) => {
|
||||
const rounded = Math.round(value);
|
||||
this.properties[insertFrameWidgetName] = rounded;
|
||||
syncWidgetAcrossNodes(this, insertFrameWidgetName, rounded); // Sync out
|
||||
}, { min: -9999, max: 9999, step: 10, precision: 0 }
|
||||
);
|
||||
|
||||
// Add strength widget with Sync Callback
|
||||
const savedStrengthValue = this.properties[strengthWidgetName];
|
||||
this.addWidget("number", strengthWidgetName,
|
||||
savedStrengthValue !== undefined ? savedStrengthValue : 1.0,
|
||||
(value) => {
|
||||
this.properties[strengthWidgetName] = value;
|
||||
syncWidgetAcrossNodes(this, strengthWidgetName, value); // Sync out
|
||||
}, { min: 0.0, max: 1.0, step: 0.01 }
|
||||
);
|
||||
addSyncedWidget("number", `insert_frame_${i}`, 0, { min: -9999, max: 9999, step: 10, precision: 0 });
|
||||
addSyncedWidget("number", `insert_second_${i}`, 0.0, { min: 0.0, max: 9999.0, step: 0.1, precision: 2 });
|
||||
addSyncedWidget("number", `strength_${i}`, 1.0, { min: 0.0, max: 1.0, step: 0.01 });
|
||||
}
|
||||
|
||||
this._updateVisibility();
|
||||
this.setDirtyCanvas(true, true);
|
||||
requestAnimationFrame(() => {
|
||||
if (this.computeSize) {
|
||||
this.setSize(this.computeSize());
|
||||
this.size[0] = initialWidth; // keep width fixed when restructuring
|
||||
this.size[0] = initialWidth;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// --- STRICT ARRAY MAPPER: FIXES ALL SHIFTING FOREVER ---
|
||||
// This runs the exact instant the node is loaded, before any UI widgets shift indices.
|
||||
// It locks the perfectly mapped array values directly into our properties dictionary.
|
||||
const origConfigure = node.configure;
|
||||
node.configure = function(info) {
|
||||
if (origConfigure) {
|
||||
origConfigure.apply(this, arguments);
|
||||
}
|
||||
if (origConfigure) origConfigure.apply(this, arguments);
|
||||
if (this.widgets) {
|
||||
this.widgets.forEach(w => {
|
||||
if (w.name === "num_images" || w.name.startsWith("insert_frame_") || w.name.startsWith("strength_")) {
|
||||
this.properties[w.name] = w.value;
|
||||
if (w.name.startsWith("insert_") || w.name.startsWith("strength_") || ["num_images", "insert_mode", "frame_rate"].includes(w.name)) {
|
||||
if (w.type !== "button") this.properties[w.name] = w.value;
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Handle deserialization to load properties properly from JSON
|
||||
const originalOnConfigure = node.onConfigure;
|
||||
node.onConfigure = function(info) {
|
||||
if (originalOnConfigure) {
|
||||
originalOnConfigure.apply(this, arguments);
|
||||
}
|
||||
if (info.properties) {
|
||||
this.properties = { ...this.properties, ...info.properties };
|
||||
}
|
||||
this._hookStaticWidgets();
|
||||
setTimeout(() => {
|
||||
const count = readSourceImageCount(this);
|
||||
// Fallback to properties.num_images if source node disconnected
|
||||
let targetCount = count !== null ? count : (this.properties.num_images || 0);
|
||||
this._applyWidgetCount(targetCount);
|
||||
this._updateVisibility();
|
||||
}, 100);
|
||||
};
|
||||
|
||||
// --- STRICT ARRAY GENERATOR ---
|
||||
// Completely detach from ComfyUI's blind visual array saving.
|
||||
// We construct an exact 101-element strict array that Python expects.
|
||||
// This makes your node 100% immune to UI/Header index shifting.
|
||||
const originalOnSerialize = node.onSerialize;
|
||||
node.onSerialize = function(info) {
|
||||
// Ensure properties are strictly synced with current widget values before building
|
||||
if (this.widgets) {
|
||||
this.widgets.forEach(w => {
|
||||
if (w.name === "num_images" || w.name.startsWith("insert_frame_") || w.name.startsWith("strength_")) {
|
||||
this.properties[w.name] = w.value;
|
||||
if (w.name.startsWith("insert_") || w.name.startsWith("strength_") || ["num_images", "insert_mode", "frame_rate"].includes(w.name)) {
|
||||
if (w.type !== "hidden" && w.type !== "button") this.properties[w.name] = w.value;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (originalOnSerialize) {
|
||||
originalOnSerialize.apply(this, arguments);
|
||||
}
|
||||
|
||||
if (originalOnSerialize) originalOnSerialize.apply(this, arguments);
|
||||
info.properties = { ...this.properties };
|
||||
|
||||
// Build the exact strict array that maps 1-to-1 to the Python backend
|
||||
const strictArray = [];
|
||||
const numWidgetVal = this.properties["num_images"];
|
||||
strictArray.push(numWidgetVal !== undefined ? numWidgetVal : 1);
|
||||
strictArray.push(this.properties["num_images"] !== undefined ? this.properties["num_images"] : 1);
|
||||
strictArray.push(this.properties["insert_mode"] !== undefined ? this.properties["insert_mode"] : "frames");
|
||||
strictArray.push(this.properties["frame_rate"] !== undefined ? this.properties["frame_rate"] : 24);
|
||||
|
||||
for (let i = 1; i <= 50; i++) {
|
||||
const fVal = this.properties[`insert_frame_${i}`];
|
||||
const sVal = this.properties[`strength_${i}`];
|
||||
strictArray.push(fVal !== undefined ? fVal : 0);
|
||||
strictArray.push(sVal !== undefined ? sVal : 1.0);
|
||||
strictArray.push(this.properties[`insert_frame_${i}`] !== undefined ? this.properties[`insert_frame_${i}`] : 0);
|
||||
strictArray.push(this.properties[`insert_second_${i}`] !== undefined ? this.properties[`insert_second_${i}`] : 0.0);
|
||||
strictArray.push(this.properties[`strength_${i}`] !== undefined ? this.properties[`strength_${i}`] : 1.0);
|
||||
}
|
||||
|
||||
info.widgets_values = strictArray;
|
||||
};
|
||||
|
||||
// Set up manual num_images widget callback
|
||||
setTimeout(() => {
|
||||
const numWidget = node.widgets?.find(w => w.name === "num_images");
|
||||
if (numWidget) {
|
||||
numWidget.callback = (val) => {
|
||||
node.properties["num_images"] = val;
|
||||
node._applyWidgetCount(val);
|
||||
};
|
||||
}
|
||||
}, 100);
|
||||
|
||||
// Exposed receiver for push-based notifications
|
||||
node._syncImageCount = function(count) {
|
||||
this._applyWidgetCount(count);
|
||||
};
|
||||
|
||||
// Helper: read image count from a connected MultiImageLoader node
|
||||
function readSourceImageCount(self) {
|
||||
const multiInput = self.inputs?.find(inp => inp.name === "multi_input");
|
||||
if (!multiInput || !multiInput.link) return null;
|
||||
|
||||
const nodeGraph = self.graph || app.graph;
|
||||
|
||||
// Helper to safely trace back through Reroutes and ComfyUI Group Nodes/Subgraphs
|
||||
function traceUpstream(graph, linkId, visited = new Set()) {
|
||||
if (!linkId || visited.has(linkId)) return null;
|
||||
visited.add(linkId);
|
||||
|
||||
const link = graph.links[linkId];
|
||||
if (!link) return null;
|
||||
|
||||
const originNode = graph.getNodeById(link.origin_id);
|
||||
if (!originNode) return null;
|
||||
|
||||
if (originNode.comfyClass === "MultiImageLoader") {
|
||||
return originNode;
|
||||
}
|
||||
|
||||
// Traverse Reroute nodes
|
||||
if (originNode.comfyClass === "MultiImageLoader") return originNode;
|
||||
if (originNode.type === "Reroute" || originNode.comfyClass === "Reroute") {
|
||||
if (originNode.inputs && originNode.inputs.length > 0 && originNode.inputs[0].link) {
|
||||
return traceUpstream(graph, originNode.inputs[0].link, visited);
|
||||
}
|
||||
if (originNode.inputs?.[0]?.link) return traceUpstream(graph, originNode.inputs[0].link, visited);
|
||||
}
|
||||
|
||||
// Traverse standard ComfyUI Group Nodes (subgraphs)
|
||||
if (typeof originNode.getInnerNode === "function") {
|
||||
try {
|
||||
const innerNode = originNode.getInnerNode(link.origin_slot);
|
||||
if (innerNode && innerNode.comfyClass === "MultiImageLoader") {
|
||||
return innerNode;
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn("Could not trace inner node", e);
|
||||
}
|
||||
if (innerNode?.comfyClass === "MultiImageLoader") return innerNode;
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
let sourceNode = traceUpstream(nodeGraph, multiInput.link);
|
||||
|
||||
// Helper to extract the count once we find a node
|
||||
function getCountFromNode(n) {
|
||||
if (typeof n._imageCount === "number") return n._imageCount;
|
||||
const pathsWidget = n.widgets?.find(w => w.name === "image_paths");
|
||||
if (pathsWidget) {
|
||||
return (pathsWidget.value || "").split('\n').map(p => p.trim()).filter(p => p.length > 0).length;
|
||||
}
|
||||
return null;
|
||||
return pathsWidget ? (pathsWidget.value || "").split('\n').filter(p => p.trim()).length : null;
|
||||
}
|
||||
|
||||
if (sourceNode) {
|
||||
return getCountFromNode(sourceNode);
|
||||
}
|
||||
if (sourceNode) return getCountFromNode(sourceNode);
|
||||
|
||||
// Fallback Strategy: If it is connected to something, but we couldn't resolve it
|
||||
// directly (e.g. complex nested 3rd party subgraphs), scan the entire UI.
|
||||
// If there is EXACTLY ONE MultiImageLoader in the workspace, safely assume that's the one.
|
||||
let multiImageLoaders = [];
|
||||
function findAllLoaders(nodes) {
|
||||
if (!nodes) return;
|
||||
for (let n of nodes) {
|
||||
if (n.comfyClass === "MultiImageLoader") {
|
||||
multiImageLoaders.push(n);
|
||||
}
|
||||
if (n.subgraph && n.subgraph._nodes) {
|
||||
findAllLoaders(n.subgraph._nodes);
|
||||
}
|
||||
if (n.comfyClass === "MultiImageLoader") multiImageLoaders.push(n);
|
||||
if (n.subgraph?._nodes) findAllLoaders(n.subgraph._nodes);
|
||||
}
|
||||
}
|
||||
if (app.graph && app.graph._nodes) {
|
||||
findAllLoaders(app.graph._nodes);
|
||||
}
|
||||
|
||||
if (multiImageLoaders.length === 1) {
|
||||
return getCountFromNode(multiImageLoaders[0]);
|
||||
}
|
||||
|
||||
if (app.graph?._nodes) findAllLoaders(app.graph._nodes);
|
||||
if (multiImageLoaders.length === 1) return getCountFromNode(multiImageLoaders[0]);
|
||||
return null;
|
||||
}
|
||||
|
||||
// --- Backup polling via setInterval (4 Hz) ---
|
||||
const pollInterval = setInterval(() => {
|
||||
if (!node.graph) {
|
||||
clearInterval(pollInterval);
|
||||
return;
|
||||
}
|
||||
const count = readSourceImageCount(node);
|
||||
if (count !== null) {
|
||||
if (count !== null && count !== node._currentImageCount) {
|
||||
node._applyWidgetCount(count);
|
||||
syncFullStateAcrossNodes(node); // Sync the new count to others
|
||||
}
|
||||
}, 250);
|
||||
}, 500);
|
||||
|
||||
// Clean up the interval when the node is deleted
|
||||
const origOnRemoved = node.onRemoved;
|
||||
node.onRemoved = function() {
|
||||
// Unregister this node instance
|
||||
window._LTXSequencerGlobalNodes.delete(node);
|
||||
|
||||
clearInterval(pollInterval);
|
||||
if (origOnRemoved) origOnRemoved.apply(this, arguments);
|
||||
};
|
||||
|
||||
// --- Connection change handler ---
|
||||
const onConnectionsChange = node.onConnectionsChange;
|
||||
node.onConnectionsChange = function(type, index, connected, link_info) {
|
||||
if (onConnectionsChange) onConnectionsChange.apply(this, arguments);
|
||||
|
||||
if (type === 1) { // 1 = Input
|
||||
const input = this.inputs[index];
|
||||
if (input && input.name === "multi_input") {
|
||||
if (connected) {
|
||||
setTimeout(() => {
|
||||
const count = readSourceImageCount(this);
|
||||
this._applyWidgetCount(count !== null ? count : (this.properties.num_images || 0));
|
||||
}, 100);
|
||||
} else {
|
||||
this._applyWidgetCount(0);
|
||||
}
|
||||
node.onConnectionsChange = function(type, index, connected) {
|
||||
if (type === 1 && this.inputs[index]?.name === "multi_input") {
|
||||
if (connected) {
|
||||
setTimeout(() => {
|
||||
const count = readSourceImageCount(this);
|
||||
this._applyWidgetCount(count !== null ? count : (this.properties.num_images || 0));
|
||||
}, 100);
|
||||
} else {
|
||||
this._applyWidgetCount(0);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// --- Initial sync when first placed on canvas ---
|
||||
const origOnAdded = node.onAdded;
|
||||
node.onAdded = function() {
|
||||
if (origOnAdded) origOnAdded.apply(this, arguments);
|
||||
setTimeout(() => {
|
||||
const count = readSourceImageCount(this);
|
||||
this._applyWidgetCount(count !== null ? count : (this.properties.num_images || 0));
|
||||
|
||||
@@ -77,17 +77,28 @@ app.registerExtension({
|
||||
// Permanently neutralize the DOM widget's built-in computeSize to prevent infinite LiteGraph loops
|
||||
galleryWidget.computeSize = () => [0, 0];
|
||||
|
||||
// Find the paths widget and hide it
|
||||
// --- BUG FIX ---
|
||||
// Find the paths widget and properly hide it from LiteGraph
|
||||
const pathsWidget = node.widgets.find(w => w.name === "image_paths");
|
||||
if (pathsWidget) {
|
||||
pathsWidget.type = "hidden";
|
||||
if (pathsWidget.element) pathsWidget.element.style.display = "none";
|
||||
// Tell LiteGraph to ignore this widget for hit-testing and drawing
|
||||
pathsWidget.hidden = true;
|
||||
|
||||
// Return -4 to absorb LiteGraph's default 4px vertical margin between widgets,
|
||||
// entirely eliminating its invisible "ghost" hitbox.
|
||||
pathsWidget.computeSize = () => [0, -4];
|
||||
|
||||
// Hide the actual DOM element
|
||||
if (pathsWidget.element) {
|
||||
pathsWidget.element.style.display = "none";
|
||||
}
|
||||
}
|
||||
|
||||
const oldCallback = pathsWidget.callback;
|
||||
const oldCallback = pathsWidget?.callback;
|
||||
|
||||
// Centralized helper to prevent infinite loops when updating values internally
|
||||
function setWidgetValue(newPathsArray, isRearranging = false) {
|
||||
if (!pathsWidget) return;
|
||||
const val = newPathsArray.join("\n");
|
||||
|
||||
// Temporarily silence the main callback
|
||||
@@ -145,7 +156,7 @@ app.registerExtension({
|
||||
|
||||
// 2D Square Packing Algorithm: Calculates the optimal grid sizes to fill empty space
|
||||
function optimizeGrid(nodeW, containerH) {
|
||||
const paths = (pathsWidget.value || "").split(/\n|,/).map(s => s.trim()).filter(s => s);
|
||||
const paths = (pathsWidget?.value || "").split(/\n|,/).map(s => s.trim()).filter(s => s);
|
||||
const N = paths.length;
|
||||
|
||||
if (N === 0) {
|
||||
@@ -285,7 +296,7 @@ app.registerExtension({
|
||||
|
||||
function refreshGallery(isRearranging = false) {
|
||||
grid.innerHTML = "";
|
||||
const paths = (pathsWidget.value || "").split(/\n|,/).map(s => s.trim()).filter(s => s);
|
||||
const paths = (pathsWidget?.value || "").split(/\n|,/).map(s => s.trim()).filter(s => s);
|
||||
|
||||
if (!isRearranging) {
|
||||
syncOutputs(paths.length);
|
||||
@@ -377,7 +388,7 @@ app.registerExtension({
|
||||
|
||||
// The DOM visually reorders during dragover. Here we finalize it to data.
|
||||
const newPaths = Array.from(grid.children).map(n => n.dataset.path);
|
||||
const currentVal = (pathsWidget.value || "").trim();
|
||||
const currentVal = (pathsWidget?.value || "").trim();
|
||||
if (newPaths.join("\n") !== currentVal) {
|
||||
setWidgetValue(newPaths, true);
|
||||
}
|
||||
@@ -492,7 +503,7 @@ app.registerExtension({
|
||||
} catch (e) { console.error("Upload error", e); }
|
||||
}
|
||||
if (uploaded.length > 0) {
|
||||
const current = (pathsWidget.value || "").trim();
|
||||
const current = (pathsWidget?.value || "").trim();
|
||||
const allPaths = current ? current.split('\n').concat(uploaded) : uploaded;
|
||||
setWidgetValue(allPaths, false);
|
||||
}
|
||||
@@ -551,10 +562,12 @@ app.registerExtension({
|
||||
};
|
||||
|
||||
// Hooks the main callback for external state loads (e.g., undo/redo or initial graph load)
|
||||
pathsWidget.callback = (v) => {
|
||||
if (oldCallback) oldCallback.apply(pathsWidget, [v]);
|
||||
refreshGallery();
|
||||
};
|
||||
if (pathsWidget) {
|
||||
pathsWidget.callback = (v) => {
|
||||
if (oldCallback) oldCallback.apply(pathsWidget, [v]);
|
||||
refreshGallery();
|
||||
};
|
||||
}
|
||||
|
||||
setTimeout(() => refreshGallery(), 100);
|
||||
}
|
||||
|
||||
@@ -16,6 +16,10 @@ class LTXSequencer(LTXVAddGuide):
|
||||
|
||||
inputs.append(io.Int.Input("num_images", default=1, min=0, max=50, step=1, display_name="images_loaded", tooltip="Select how many index/strength widgets to configure."))
|
||||
|
||||
# New global settings widgets
|
||||
inputs.append(io.Combo.Input("insert_mode", options=["frames", "seconds"], default="frames", tooltip="Select the method for determining insertion points."))
|
||||
inputs.append(io.Int.Input("frame_rate", default=24, min=1, max=120, step=1, tooltip="Video FPS (used for calculating second insertions)."))
|
||||
|
||||
for i in range(1, 51): # 1 to 50 images
|
||||
inputs.extend([
|
||||
io.Int.Input(
|
||||
@@ -24,7 +28,16 @@ class LTXSequencer(LTXVAddGuide):
|
||||
min=-9999,
|
||||
max=9999,
|
||||
step=1,
|
||||
tooltip=f"Frame insert_frame for image {i} (in pixel space).",
|
||||
tooltip=f"Frame insert point for image {i} (in pixel space).",
|
||||
optional=True,
|
||||
),
|
||||
io.Float.Input(
|
||||
f"insert_second_{i}",
|
||||
default=0.0,
|
||||
min=0.0,
|
||||
max=9999.0,
|
||||
step=0.1,
|
||||
tooltip=f"Second insert point for image {i}.",
|
||||
optional=True,
|
||||
),
|
||||
io.Float.Input(
|
||||
@@ -42,7 +55,7 @@ class LTXSequencer(LTXVAddGuide):
|
||||
node_id="LTXSequencer",
|
||||
display_name="LTX Sequencer",
|
||||
category="LTXVCustom",
|
||||
description="Add multiple guide images at specified frame indices with strengths. Number of widgets is dynamically configured.",
|
||||
description="Add multiple guide images at specified frame indices or seconds with strengths. Number of widgets is dynamically configured.",
|
||||
inputs=inputs,
|
||||
outputs=[
|
||||
io.Conditioning.Output(display_name="positive"),
|
||||
@@ -72,6 +85,10 @@ class LTXSequencer(LTXVAddGuide):
|
||||
_, _, latent_length, latent_height, latent_width = latent_image.shape
|
||||
batch_size = multi_input.shape[0] if multi_input is not None else 0
|
||||
|
||||
# Retrieve selected insertion settings
|
||||
insert_mode = kwargs.get("insert_mode", "frames")
|
||||
frame_rate = kwargs.get("frame_rate", 24)
|
||||
|
||||
# Process inputs up to num_images, extracting dynamic frame/strength values from kwargs
|
||||
for i in range(1, num_images + 1):
|
||||
# Skip if this image index exceeds the batch
|
||||
@@ -82,9 +99,18 @@ class LTXSequencer(LTXVAddGuide):
|
||||
if img is None:
|
||||
continue
|
||||
|
||||
f_idx = kwargs.get(f"insert_frame_{i}")
|
||||
# Calculate the final frame index based on the chosen mode
|
||||
f_idx = None
|
||||
if insert_mode == "frames":
|
||||
f_idx = kwargs.get(f"insert_frame_{i}")
|
||||
elif insert_mode == "seconds":
|
||||
sec = kwargs.get(f"insert_second_{i}")
|
||||
if sec is not None:
|
||||
f_idx = int(sec * frame_rate)
|
||||
|
||||
if f_idx is None:
|
||||
continue
|
||||
|
||||
strength = kwargs.get(f"strength_{i}", 1.0)
|
||||
|
||||
# Execution logic mirrored from LTXVAddGuideMulti
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import numpy as np
|
||||
from PIL import Image, ImageOps
|
||||
import os
|
||||
import folder_paths
|
||||
import io
|
||||
import comfy.utils
|
||||
|
||||
class MultiImageLoader:
|
||||
@classmethod
|
||||
@@ -13,8 +15,9 @@ class MultiImageLoader:
|
||||
"image_paths": ("STRING", {"default": "", "multiline": True}),
|
||||
"width": ("INT", {"default": 0, "min": 0, "max": 8192, "step": 1}),
|
||||
"height": ("INT", {"default": 0, "min": 0, "max": 8192, "step": 1}),
|
||||
"upscale_method": (["lanczos", "bilinear", "nearest-exact"],),
|
||||
"divisible_by": ("INT", {"default": 32, "min": 1, "max": 512, "step": 1}),
|
||||
"interpolation": (["lanczos", "nearest", "bilinear", "bicubic", "area", "nearest-exact"],),
|
||||
"resize_method": (["keep proportion", "stretch", "pad", "crop"],),
|
||||
"multiple_of": ("INT", {"default": 0, "min": 0, "max": 512, "step": 1}),
|
||||
"img_compression": ("INT", {"default": 18, "min": 0, "max": 100, "step": 1}),
|
||||
},
|
||||
}
|
||||
@@ -25,13 +28,101 @@ class MultiImageLoader:
|
||||
FUNCTION = "load_images"
|
||||
CATEGORY = "image"
|
||||
|
||||
def load_images(self, image_paths, width, height, upscale_method, divisible_by, img_compression):
|
||||
def resize_image(self, image, width, height, resize_method="keep proportion", interpolation="nearest", multiple_of=0):
|
||||
MAX_RESOLUTION = 8192
|
||||
_, oh, ow, _ = image.shape
|
||||
x = y = x2 = y2 = 0
|
||||
pad_left = pad_right = pad_top = pad_bottom = 0
|
||||
|
||||
if multiple_of > 1:
|
||||
width = width - (width % multiple_of)
|
||||
height = height - (height % multiple_of)
|
||||
|
||||
if resize_method == 'keep proportion' or resize_method == 'pad':
|
||||
if width == 0 and oh < height:
|
||||
width = MAX_RESOLUTION
|
||||
elif width == 0 and oh >= height:
|
||||
width = ow
|
||||
|
||||
if height == 0 and ow < width:
|
||||
height = MAX_RESOLUTION
|
||||
elif height == 0 and ow >= width:
|
||||
height = oh
|
||||
|
||||
ratio = min(width / ow, height / oh)
|
||||
new_width = round(ow * ratio)
|
||||
new_height = round(oh * ratio)
|
||||
|
||||
if resize_method == 'pad':
|
||||
pad_left = (width - new_width) // 2
|
||||
pad_right = width - new_width - pad_left
|
||||
pad_top = (height - new_height) // 2
|
||||
pad_bottom = height - new_height - pad_top
|
||||
|
||||
width = new_width
|
||||
height = new_height
|
||||
|
||||
elif resize_method == 'crop':
|
||||
width = width if width > 0 else ow
|
||||
height = height if height > 0 else oh
|
||||
|
||||
ratio = max(width / ow, height / oh)
|
||||
new_width = round(ow * ratio)
|
||||
new_height = round(oh * ratio)
|
||||
x = (new_width - width) // 2
|
||||
y = (new_height - height) // 2
|
||||
x2 = x + width
|
||||
y2 = y + height
|
||||
if x2 > new_width:
|
||||
x -= (x2 - new_width)
|
||||
if x < 0:
|
||||
x = 0
|
||||
if y2 > new_height:
|
||||
y -= (y2 - new_height)
|
||||
if y < 0:
|
||||
y = 0
|
||||
width = new_width
|
||||
height = new_height
|
||||
|
||||
else:
|
||||
width = width if width > 0 else ow
|
||||
height = height if height > 0 else oh
|
||||
|
||||
# Always apply resize logic
|
||||
outputs = image.permute(0, 3, 1, 2)
|
||||
|
||||
if interpolation == "lanczos":
|
||||
outputs = comfy.utils.lanczos(outputs, width, height)
|
||||
else:
|
||||
outputs = F.interpolate(outputs, size=(height, width), mode=interpolation)
|
||||
|
||||
if resize_method == 'pad':
|
||||
if pad_left > 0 or pad_right > 0 or pad_top > 0 or pad_bottom > 0:
|
||||
outputs = F.pad(outputs, (pad_left, pad_right, pad_top, pad_bottom), value=0)
|
||||
|
||||
outputs = outputs.permute(0, 2, 3, 1)
|
||||
|
||||
if resize_method == 'crop':
|
||||
if x > 0 or y > 0 or x2 > 0 or y2 > 0:
|
||||
outputs = outputs[:, y:y2, x:x2, :]
|
||||
|
||||
if multiple_of > 1 and (outputs.shape[2] % multiple_of != 0 or outputs.shape[1] % multiple_of != 0):
|
||||
width = outputs.shape[2]
|
||||
height = outputs.shape[1]
|
||||
x = (width % multiple_of) // 2
|
||||
y = (height % multiple_of) // 2
|
||||
x2 = width - ((width % multiple_of) - x)
|
||||
y2 = height - ((height % multiple_of) - y)
|
||||
outputs = outputs[:, y:y2, x:x2, :]
|
||||
|
||||
outputs = torch.clamp(outputs, 0, 1)
|
||||
|
||||
return outputs
|
||||
|
||||
def load_images(self, image_paths, width, height, interpolation, resize_method, multiple_of, img_compression):
|
||||
results = []
|
||||
valid_paths = [p.strip() for p in image_paths.split("\n") if p.strip()]
|
||||
|
||||
# Track the dimensions of the first processed image
|
||||
first_target_w, first_target_h = None, None
|
||||
|
||||
for path in valid_paths:
|
||||
try:
|
||||
# Resolve full path
|
||||
@@ -43,49 +134,42 @@ class MultiImageLoader:
|
||||
print(f"Warning: Image path not found: {path}")
|
||||
continue
|
||||
|
||||
# Load image
|
||||
image = Image.open(full_path)
|
||||
image = ImageOps.exif_transpose(image)
|
||||
image = image.convert("RGB")
|
||||
|
||||
orig_w, orig_h = image.size
|
||||
target_w, target_h = width, height
|
||||
|
||||
if target_w == 0 and target_h == 0:
|
||||
target_w, target_h = orig_w, orig_h
|
||||
elif target_w == 0:
|
||||
target_w = int(orig_w * (target_h / orig_h))
|
||||
elif target_h == 0:
|
||||
target_h = int(orig_h * (target_w / orig_w))
|
||||
|
||||
# Divisible by constraint
|
||||
target_w = (target_w // divisible_by) * divisible_by
|
||||
target_h = (target_h // divisible_by) * divisible_by
|
||||
|
||||
# To prevent torch.cat errors, ALL images in the batch must match the dimensions
|
||||
# of the first successfully loaded image.
|
||||
if first_target_w is None:
|
||||
first_target_w, first_target_h = target_w, target_h
|
||||
else:
|
||||
target_w, target_h = first_target_w, first_target_h
|
||||
|
||||
if target_w != orig_w or target_h != orig_h:
|
||||
resample = Image.LANCZOS if upscale_method == "lanczos" else Image.BILINEAR
|
||||
image = image.resize((target_w, target_h), resample=resample)
|
||||
|
||||
# Compression
|
||||
if img_compression > 0:
|
||||
img_byte_arr = io.BytesIO()
|
||||
image.save(img_byte_arr, format="JPEG", quality=max(1, 100 - img_compression))
|
||||
image = Image.open(img_byte_arr)
|
||||
|
||||
# Convert to Torch Tensor to prepare for Advanced Resize Logic
|
||||
image_np = np.array(image).astype(np.float32) / 255.0
|
||||
results.append(torch.from_numpy(image_np)[None,])
|
||||
image_tensor = torch.from_numpy(image_np)[None,]
|
||||
|
||||
# Apply Advanced Resize
|
||||
image_tensor = self.resize_image(image_tensor, width, height, resize_method, interpolation, multiple_of)
|
||||
|
||||
# Compression (Applied after resize to accurately maintain the effect)
|
||||
if img_compression > 0:
|
||||
img_np = (image_tensor[0].numpy() * 255).clip(0, 255).astype(np.uint8)
|
||||
img_pil = Image.fromarray(img_np)
|
||||
img_byte_arr = io.BytesIO()
|
||||
img_pil.save(img_byte_arr, format="JPEG", quality=max(1, 100 - img_compression))
|
||||
img_pil = Image.open(img_byte_arr)
|
||||
image_tensor = torch.from_numpy(np.array(img_pil).astype(np.float32) / 255.0)[None,]
|
||||
|
||||
results.append(image_tensor)
|
||||
except Exception as e:
|
||||
print(f"Error loading {path}: {e}")
|
||||
|
||||
# Combine all successfully loaded images into a single batched tensor for multi_output
|
||||
if len(results) > 0:
|
||||
multi_output = torch.cat(results, dim=0)
|
||||
# Safety Check: Advanced resize methods might output differently sized tensors (e.g., 'keep proportion')
|
||||
first_shape = results[0].shape
|
||||
all_same_shape = all(r.shape == first_shape for r in results)
|
||||
|
||||
if all_same_shape:
|
||||
multi_output = torch.cat(results, dim=0)
|
||||
else:
|
||||
print("MultiImageLoader Warning: Images have different dimensions due to resize settings. Cannot batch into multi_output. Outputting zero tensor for the batch, but individual output nodes will still work fine.")
|
||||
multi_output = torch.zeros((1, 64, 64, 3))
|
||||
else:
|
||||
# Fallback empty tensor if no valid paths
|
||||
multi_output = torch.zeros((1, 64, 64, 3))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "WhatDreamsCost-ComfyUI"
|
||||
description = "A variety of custom ComfyUI nodes and workflows for creatives."
|
||||
version = "1.0.1"
|
||||
version = "1.1.0"
|
||||
license = {file = "LICENSE"}
|
||||
# classifiers = [
|
||||
# # For OS-independent nodes (works on all operating systems)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
Before Width: | Height: | Size: 378 KiB |
7916
workflows/LTX I2V First Last Frame 3 Stage Workflow v6.json
Normal file
7916
workflows/LTX I2V First Last Frame 3 Stage Workflow v6.json
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user