The shared kit (js/fbui/, docs/UI_RULES.md) gives Prompt Manager's nodes the FBnodes look and its "Node color" setting (Prompt Manager > Appearance). The Prompt Extractor's file browser is now the same file as FBnodes' (thumbnails, list views, search, multi-select, Custom folder), on Prompt Manager's own routes: path_browser.js names them, and the backend gains the delete route, .hidden folders and JSON in "all". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2719 lines
118 KiB
JavaScript
2719 lines
118 KiB
JavaScript
/**
|
|
* PromptExtractor Extension for ComfyUI
|
|
* Adds image preview functionality for the extractor node
|
|
*/
|
|
|
|
import { app } from "../../scripts/app.js";
|
|
import { api } from "../../scripts/api.js";
|
|
import { createFileBrowserModal } from "./file_browser.js";
|
|
import { mediaFileUrl, getMediaRoots, classifySelection } from "./path_browser.js";
|
|
|
|
// Placeholder image path - loaded from static PNG file
|
|
const PLACEHOLDER_IMAGE_PATH = new URL("./placeholder.png", import.meta.url).href;
|
|
|
|
// Track videos that the browser cannot decode (H265/yuv444) - skip browser attempts on scrub
|
|
const _nonBrowserDecodableVideos = new Set();
|
|
|
|
function isAbsolutePath(value) {
|
|
if (!value) return false;
|
|
return /^([a-zA-Z]:[\\/]|\\\\|\/)/.test(value);
|
|
}
|
|
|
|
function hideWidget(widget) {
|
|
if (!widget) return;
|
|
widget.hidden = true;
|
|
widget.computeSize = () => [0, -4];
|
|
if (widget.inputEl) widget.inputEl.style.display = "none";
|
|
}
|
|
|
|
function buildPreviewUrl(filename, viewType) {
|
|
if (isAbsolutePath(filename)) {
|
|
return mediaFileUrl(filename);
|
|
}
|
|
|
|
let actualFilename = filename;
|
|
let subfolder = "";
|
|
if (filename.includes('/')) {
|
|
const lastSlash = filename.lastIndexOf('/');
|
|
subfolder = filename.substring(0, lastSlash);
|
|
actualFilename = filename.substring(lastSlash + 1);
|
|
}
|
|
|
|
let url = `/view?filename=${encodeURIComponent(actualFilename)}&type=${viewType || 'input'}`;
|
|
if (subfolder) {
|
|
url += `&subfolder=${encodeURIComponent(subfolder)}`;
|
|
}
|
|
return url;
|
|
}
|
|
|
|
function resolveMediaSource(filename, sourceFolder) {
|
|
return isAbsolutePath(filename) ? "absolute" : (sourceFolder || "input");
|
|
}
|
|
|
|
function basenameForDisplay(value) {
|
|
const s = String(value || "");
|
|
const normalized = s.replace(/\\/g, "/");
|
|
const i = normalized.lastIndexOf("/");
|
|
return i >= 0 ? normalized.substring(i + 1) : normalized;
|
|
}
|
|
|
|
function stripAnnotation(filename) {
|
|
if (!filename) return filename;
|
|
const match = filename.match(/^(.+)\s+\[(input|output|temp)\]$/);
|
|
return match ? match[1] : filename;
|
|
}
|
|
|
|
/**
|
|
* Extract metadata from PNG file
|
|
* Reads tEXt/iTXt chunks for prompt and workflow (ComfyUI native approach)
|
|
*/
|
|
async function getPNGMetadata(file) {
|
|
return new Promise((resolve) => {
|
|
const reader = new FileReader();
|
|
reader.onload = (event) => {
|
|
const pngData = new Uint8Array(event.target.result);
|
|
const dataView = new DataView(pngData.buffer);
|
|
const decoder = new TextDecoder();
|
|
|
|
// Verify PNG signature
|
|
if (dataView.getUint32(0) !== 0x89504E47 || dataView.getUint32(4) !== 0x0D0A1A0A) {
|
|
resolve(null);
|
|
return;
|
|
}
|
|
|
|
let prompt = null;
|
|
let workflow = null;
|
|
let parameters = null; // A1111/Forge parameters that ComfyUI can convert to workflow
|
|
let offset = 8; // Skip PNG signature
|
|
|
|
// Parse PNG chunks
|
|
while (offset < pngData.length - 12) {
|
|
const chunkLength = dataView.getUint32(offset);
|
|
const chunkType = String.fromCharCode(
|
|
pngData[offset + 4],
|
|
pngData[offset + 5],
|
|
pngData[offset + 6],
|
|
pngData[offset + 7]
|
|
);
|
|
|
|
// Check for tEXt or iTXt chunks
|
|
if (chunkType === 'tEXt' || chunkType === 'iTXt') {
|
|
const chunkData = pngData.slice(offset + 8, offset + 8 + chunkLength);
|
|
|
|
// Find null terminator for keyword
|
|
let keywordEnd = 0;
|
|
while (keywordEnd < chunkData.length && chunkData[keywordEnd] !== 0) {
|
|
keywordEnd++;
|
|
}
|
|
|
|
const keyword = decoder.decode(chunkData.slice(0, keywordEnd));
|
|
let text = '';
|
|
|
|
if (chunkType === 'tEXt') {
|
|
text = decoder.decode(chunkData.slice(keywordEnd + 1));
|
|
} else if (chunkType === 'iTXt') {
|
|
// iTXt format: keyword\0compression\0language\0translated\0text
|
|
const compression = chunkData[keywordEnd + 1];
|
|
let textStart = keywordEnd + 2;
|
|
// Skip language and translated keyword (find two more nulls)
|
|
let nullCount = 0;
|
|
while (textStart < chunkData.length && nullCount < 2) {
|
|
if (chunkData[textStart] === 0) nullCount++;
|
|
textStart++;
|
|
}
|
|
text = decoder.decode(chunkData.slice(textStart));
|
|
}
|
|
|
|
// Check for ComfyUI metadata or A1111 parameters
|
|
if (keyword === 'prompt') {
|
|
try {
|
|
prompt = JSON.parse(text);
|
|
} catch (e) {
|
|
console.error('[PromptExtractor] Failed to parse prompt metadata:', e);
|
|
}
|
|
} else if (keyword === 'workflow') {
|
|
try {
|
|
workflow = JSON.parse(text);
|
|
} catch (e) {
|
|
console.error('[PromptExtractor] Failed to parse workflow metadata:', e);
|
|
}
|
|
} else if (keyword === 'parameters') {
|
|
// A1111/Forge generation parameters (ComfyUI can load workflow from this)
|
|
parameters = text;
|
|
}
|
|
}
|
|
|
|
// Move to next chunk (length + type + data + CRC)
|
|
offset += 12 + chunkLength;
|
|
|
|
// Stop if we found metadata or reached IEND
|
|
if ((prompt && workflow) || parameters || chunkType === 'IEND') {
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Return metadata if found (including A1111 parameters)
|
|
if (prompt || workflow || parameters) {
|
|
const metadata = { prompt, workflow, parameters };
|
|
|
|
// If we have A1111 parameters, parse them for easier access
|
|
if (parameters && !workflow) {
|
|
metadata.parsed_parameters = parseA1111Parameters(parameters);
|
|
}
|
|
|
|
resolve(metadata);
|
|
} else {
|
|
resolve(null);
|
|
}
|
|
};
|
|
reader.readAsArrayBuffer(file);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Parse A1111/Forge parameters format
|
|
* Extracts prompt, negative, and LoRAs
|
|
*/
|
|
function parseA1111Parameters(parametersText) {
|
|
if (!parametersText) return null;
|
|
|
|
const result = {
|
|
prompt: '',
|
|
negative_prompt: '',
|
|
loras: []
|
|
};
|
|
|
|
// Split by "Negative prompt:" to separate positive and negative
|
|
const parts = parametersText.split(/Negative prompt:\s*/i);
|
|
let positivePrompt = parts[0].trim();
|
|
let remainder = parts[1] || '';
|
|
|
|
// Extract LoRAs from positive prompt using pattern: <lora:name:strength> or <lora:name:model_strength:clip_strength>
|
|
const loraRegex = /<lora:([^:>]+):([^:>]+)(?::([^:>]+))?>/gi;
|
|
let loraMatch;
|
|
const loras = [];
|
|
|
|
while ((loraMatch = loraRegex.exec(positivePrompt)) !== null) {
|
|
const loraName = loraMatch[1].trim();
|
|
const strength1 = parseFloat(loraMatch[2]);
|
|
const strength2 = loraMatch[3] ? parseFloat(loraMatch[3]) : strength1;
|
|
|
|
loras.push({
|
|
name: loraName,
|
|
model_strength: strength1,
|
|
clip_strength: strength2
|
|
});
|
|
}
|
|
|
|
// Remove LoRA tags from prompt
|
|
positivePrompt = positivePrompt.replace(loraRegex, '').trim();
|
|
result.prompt = positivePrompt;
|
|
result.loras = loras;
|
|
|
|
// Extract negative prompt (before any "Steps:" line if present)
|
|
const settingsMatch = remainder.match(/^(.*?)[\r\n]+Steps:/s);
|
|
if (settingsMatch) {
|
|
result.negative_prompt = settingsMatch[1].trim();
|
|
} else {
|
|
result.negative_prompt = remainder.trim();
|
|
}
|
|
|
|
// Extract model name from settings line (e.g. "Model: modelName")
|
|
const modelMatch = parametersText.match(/\bModel:\s*([^,\n]+)/);
|
|
if (modelMatch) {
|
|
result.model = modelMatch[1].trim();
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
function _isLoraAvailableForSort(lora) {
|
|
if (!lora) return true;
|
|
if (lora.available === false) return false;
|
|
if (lora.found === false) return false;
|
|
return true;
|
|
}
|
|
|
|
function _sortLorasMissingLast(loras) {
|
|
const src = Array.isArray(loras) ? [...loras] : [];
|
|
return src.sort((a, b) => {
|
|
const aAvailable = _isLoraAvailableForSort(a);
|
|
const bAvailable = _isLoraAvailableForSort(b);
|
|
if (aAvailable !== bAvailable) return aAvailable ? -1 : 1;
|
|
return String(a?.name || "").localeCompare(String(b?.name || ""));
|
|
});
|
|
}
|
|
|
|
function _normalizeExtractedLoraOrder(extracted) {
|
|
if (!extracted || typeof extracted !== "object") return extracted;
|
|
const normalized = { ...extracted };
|
|
if (Array.isArray(normalized.loras)) {
|
|
normalized.loras = _sortLorasMissingLast(normalized.loras);
|
|
}
|
|
if (Array.isArray(normalized.loras_a)) {
|
|
normalized.loras_a = _sortLorasMissingLast(normalized.loras_a);
|
|
}
|
|
if (Array.isArray(normalized.loras_b)) {
|
|
normalized.loras_b = _sortLorasMissingLast(normalized.loras_b);
|
|
}
|
|
return normalized;
|
|
}
|
|
|
|
function _extractorParseJsonObjectSafe(rawValue, fallback = null) {
|
|
if (rawValue && typeof rawValue === "object") return rawValue;
|
|
if (typeof rawValue !== "string") return fallback;
|
|
const trimmed = rawValue.trim();
|
|
if (!trimmed) return fallback;
|
|
try {
|
|
const parsed = JSON.parse(trimmed);
|
|
return parsed && typeof parsed === "object" ? parsed : fallback;
|
|
} catch {
|
|
return fallback;
|
|
}
|
|
}
|
|
|
|
function _extractorModelNameForSummary(pathLike) {
|
|
const raw = String(pathLike || "").trim();
|
|
if (!raw) return "";
|
|
const parts = raw.replace(/\\/g, "/").split("/");
|
|
const base = parts[parts.length - 1] || raw;
|
|
return base.replace(/\.(safetensors|ckpt|pt|pth|bin|gguf|sft)$/i, "");
|
|
}
|
|
|
|
function _extractorNormalizeSummaryLoras(list) {
|
|
if (!Array.isArray(list)) return [];
|
|
return list
|
|
.map((item) => {
|
|
if (!item || typeof item !== "object") return null;
|
|
const name = String(item.name || "").trim();
|
|
if (!name) return null;
|
|
const strengthRaw = Number(item.model_strength ?? item.strength ?? 1.0);
|
|
const strength = Number.isFinite(strengthRaw) ? strengthRaw : 1.0;
|
|
const available = item.available !== false && item.found !== false;
|
|
return {
|
|
name,
|
|
strength,
|
|
active: item.active !== false,
|
|
available,
|
|
found: item.found !== false,
|
|
};
|
|
})
|
|
.filter(Boolean)
|
|
.sort((a, b) => String(a.name).localeCompare(String(b.name)));
|
|
}
|
|
|
|
function _extractorSummarizeWorkflowDataDiscovery(rawWorkflowData) {
|
|
const empty = {
|
|
modelCount: 0,
|
|
modelDetails: [],
|
|
source: "RecipeExtractor",
|
|
};
|
|
|
|
const wf = _extractorParseJsonObjectSafe(rawWorkflowData, null);
|
|
if (!wf || typeof wf !== "object") return empty;
|
|
|
|
const slotOrder = ["model_a", "model_b", "model_c", "model_d"];
|
|
const modelDetails = [];
|
|
const models = (wf.models && typeof wf.models === "object") ? wf.models : null;
|
|
|
|
if (models) {
|
|
for (const slot of slotOrder) {
|
|
const block = models[slot];
|
|
if (!block || typeof block !== "object") continue;
|
|
const modelName = String(block.model || "").trim();
|
|
const loras = _extractorNormalizeSummaryLoras(block.loras);
|
|
if (!modelName && loras.length === 0) continue;
|
|
modelDetails.push({
|
|
slotLabel: String(slot).replace("model_", "").toUpperCase(),
|
|
modelDisplay: _extractorModelNameForSummary(modelName),
|
|
family: String(block.family || "").trim(),
|
|
loras,
|
|
});
|
|
}
|
|
} else {
|
|
const modelA = String(wf.model_a || "").trim();
|
|
const modelB = String(wf.model_b || "").trim();
|
|
const lorasA = _extractorNormalizeSummaryLoras(wf.loras_a);
|
|
const lorasB = _extractorNormalizeSummaryLoras(wf.loras_b);
|
|
|
|
if (modelA || lorasA.length > 0) {
|
|
modelDetails.push({
|
|
slotLabel: "A",
|
|
modelDisplay: _extractorModelNameForSummary(modelA),
|
|
family: "",
|
|
loras: lorasA,
|
|
});
|
|
}
|
|
if (modelB || lorasB.length > 0) {
|
|
modelDetails.push({
|
|
slotLabel: "B",
|
|
modelDisplay: _extractorModelNameForSummary(modelB),
|
|
family: "",
|
|
loras: lorasB,
|
|
});
|
|
}
|
|
}
|
|
|
|
return {
|
|
modelCount: modelDetails.length,
|
|
modelDetails,
|
|
source: String(wf._source || "RecipeExtractor"),
|
|
};
|
|
}
|
|
|
|
function _createExtractorSummaryLoraTag(lora) {
|
|
const tag = document.createElement("div");
|
|
const isAvailable = lora?.available !== false && lora?.found !== false;
|
|
const strength = Number(lora?.strength ?? 1.0);
|
|
|
|
tag.style.cssText = `
|
|
display:inline-flex;
|
|
align-items:center;
|
|
gap:6px;
|
|
width:200px;
|
|
height:24px;
|
|
padding:4px 10px;
|
|
box-sizing:border-box;
|
|
border-radius:6px;
|
|
border:1px solid ${isAvailable ? "rgba(71,145,220,0.85)" : "rgba(220,53,69,0.9)"};
|
|
background:${isAvailable ? "rgba(61,134,210,0.9)" : "rgba(220,53,69,0.9)"};
|
|
color:#fff;
|
|
flex-shrink:0;
|
|
font-size:14px;
|
|
`;
|
|
|
|
const nameSpan = document.createElement("span");
|
|
nameSpan.textContent = String(lora?.name || "");
|
|
nameSpan.style.cssText = "flex-grow:1; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;";
|
|
tag.appendChild(nameSpan);
|
|
|
|
const strengthBadge = document.createElement("span");
|
|
strengthBadge.textContent = Number.isFinite(strength) ? strength.toFixed(2) : "1.00";
|
|
strengthBadge.style.cssText = "font-size:12px; font-weight:600; padding:1px 6px; border-radius:999px; background:rgba(255,255,255,0.15);";
|
|
tag.appendChild(strengthBadge);
|
|
|
|
return tag;
|
|
}
|
|
|
|
function _showExtractorWorkflowSummaryDialog(summary) {
|
|
return new Promise((resolve) => {
|
|
const overlay = document.createElement("div");
|
|
overlay.style.cssText = "position:fixed; inset:0; background:rgba(0,0,0,0.7); z-index:9999;";
|
|
|
|
const dialog = document.createElement("div");
|
|
dialog.style.cssText = "position:fixed; top:50%; left:50%; transform:translate(-50%, -50%); width:min(452px, 92vw); max-height:78vh; overflow:auto; background:#232930; border:1px solid #3c4b59; border-radius:10px; padding:12px; z-index:10000; box-shadow:0 8px 28px rgba(0,0,0,0.55);";
|
|
|
|
const title = document.createElement("div");
|
|
title.textContent = "Summary";
|
|
title.style.cssText = "margin-bottom:8px; font-size:17px; font-weight:700; color:#e7eef6;";
|
|
dialog.appendChild(title);
|
|
|
|
const meta = document.createElement("div");
|
|
meta.style.cssText = "margin-bottom:12px; color:#9eb2c6; font-size:14px; padding-bottom:10px; border-bottom:1px solid rgba(115,144,170,0.35);";
|
|
meta.innerHTML = `<b style=\"color:#c5d8ea;\">Models found:</b> ${summary.modelCount}`;
|
|
dialog.appendChild(meta);
|
|
|
|
const modelsSection = document.createElement("div");
|
|
modelsSection.style.cssText = "margin-bottom:14px;";
|
|
modelsSection.innerHTML = `<div style=\"color:#8fb8dc; font-weight:700; margin-bottom:6px;\">Models</div>`;
|
|
const modelsList = document.createElement("div");
|
|
modelsList.style.cssText = "display:flex; flex-direction:column; gap:6px;";
|
|
if (!summary.modelDetails.length) {
|
|
const none = document.createElement("div");
|
|
none.textContent = "No models found.";
|
|
none.style.cssText = "color:#9aa8b7; font-size:14px;";
|
|
modelsList.appendChild(none);
|
|
} else {
|
|
for (const item of summary.modelDetails) {
|
|
const row = document.createElement("div");
|
|
const familyText = item.family ? ` (${item.family})` : "";
|
|
row.textContent = `${item.slotLabel}: ${item.modelDisplay || "(none)"}${familyText}`;
|
|
row.style.cssText = "color:#d9e6f3; font-size:15px; background:rgba(37,48,60,0.55); border:1px solid rgba(96,124,150,0.35); border-radius:6px; padding:6px 8px;";
|
|
modelsList.appendChild(row);
|
|
}
|
|
}
|
|
modelsSection.appendChild(modelsList);
|
|
dialog.appendChild(modelsSection);
|
|
|
|
const loraDivider = document.createElement("div");
|
|
loraDivider.style.cssText = "height:1px; background:rgba(115,144,170,0.35); margin:2px 0 12px 0;";
|
|
dialog.appendChild(loraDivider);
|
|
|
|
const loraSection = document.createElement("div");
|
|
loraSection.innerHTML = `<div style=\"color:#8fb8dc; font-weight:700; margin-bottom:8px;\">LoRAs</div>`;
|
|
if (!summary.modelDetails.some((m) => Array.isArray(m.loras) && m.loras.length > 0)) {
|
|
const none = document.createElement("div");
|
|
none.textContent = "No LoRAs found.";
|
|
none.style.cssText = "color:#9aa8b7; font-size:14px; margin-bottom:8px;";
|
|
loraSection.appendChild(none);
|
|
} else {
|
|
for (const item of summary.modelDetails) {
|
|
if (!Array.isArray(item.loras) || item.loras.length === 0) continue;
|
|
const stackCard = document.createElement("div");
|
|
stackCard.style.cssText = "background:rgba(30,40,52,0.55); border:1px solid rgba(96,124,150,0.35); border-radius:8px; padding:6px; margin-bottom:6px;";
|
|
|
|
const stackTitle = document.createElement("div");
|
|
stackTitle.textContent = `Stack ${item.slotLabel}:`;
|
|
stackTitle.style.cssText = "color:#c5d8ea; font-size:14px; margin:0 0 6px 0;";
|
|
stackCard.appendChild(stackTitle);
|
|
|
|
const stackTags = document.createElement("div");
|
|
stackTags.style.cssText = "display:grid; grid-template-columns: 200px 200px; justify-content:start; gap:2px;";
|
|
for (const lora of item.loras) {
|
|
stackTags.appendChild(_createExtractorSummaryLoraTag(lora));
|
|
}
|
|
stackCard.appendChild(stackTags);
|
|
loraSection.appendChild(stackCard);
|
|
}
|
|
}
|
|
dialog.appendChild(loraSection);
|
|
|
|
const actions = document.createElement("div");
|
|
actions.style.cssText = "display:flex; justify-content:flex-end; margin-top:14px;";
|
|
const okBtn = document.createElement("button");
|
|
okBtn.textContent = "OK";
|
|
okBtn.style.cssText = "padding:8px 16px; background:#2f7dbf; color:#fff; border:none; border-radius:6px; cursor:pointer;";
|
|
actions.appendChild(okBtn);
|
|
dialog.appendChild(actions);
|
|
|
|
const cleanup = () => {
|
|
if (overlay.parentNode) document.body.removeChild(overlay);
|
|
if (dialog.parentNode) document.body.removeChild(dialog);
|
|
};
|
|
|
|
okBtn.onclick = () => { cleanup(); resolve(true); };
|
|
overlay.onclick = () => { cleanup(); resolve(true); };
|
|
|
|
document.body.appendChild(overlay);
|
|
document.body.appendChild(dialog);
|
|
okBtn.focus();
|
|
});
|
|
}
|
|
|
|
async function showExtractorWorkflowDiscoverySummary(node) {
|
|
const rawCached = node?.properties?.pe_extracted_data;
|
|
let workflowData = _extractorParseJsonObjectSafe(rawCached, null);
|
|
|
|
if (!workflowData) {
|
|
const imageWidget = node?.widgets?.find((w) => w.name === "image");
|
|
const filename = String(imageWidget?.value || "").trim();
|
|
const sourceFolder = resolveMediaSource(filename, node?._sourceFolder || "input");
|
|
if (filename && filename !== "(none)") {
|
|
try {
|
|
const previewResp = await fetch(`/prompt-extractor/extract-preview?filename=${encodeURIComponent(filename)}&source=${encodeURIComponent(sourceFolder)}`);
|
|
if (previewResp.ok) {
|
|
const previewData = await previewResp.json();
|
|
if (previewData?.extracted && typeof previewData.extracted === "object") {
|
|
workflowData = _normalizeExtractedLoraOrder(previewData.extracted);
|
|
node.properties = node.properties || {};
|
|
node.properties.pe_extracted_data = JSON.stringify(workflowData);
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.warn('[PromptExtractor] Could not refresh extracted preview data:', error);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!workflowData || typeof workflowData !== "object") {
|
|
await _showExtractorWorkflowSummaryDialog({ modelCount: 0, modelDetails: [], source: "RecipeExtractor" });
|
|
return;
|
|
}
|
|
|
|
const summary = _extractorSummarizeWorkflowDataDiscovery(workflowData);
|
|
await _showExtractorWorkflowSummaryDialog(summary);
|
|
}
|
|
|
|
/**
|
|
* Extract metadata from JPEG/WebP file
|
|
* Reads EXIF UserComment field (0x9286) for workflow metadata
|
|
*/
|
|
async function getJPEGMetadata(file) {
|
|
return new Promise((resolve) => {
|
|
const reader = new FileReader();
|
|
reader.onload = (event) => {
|
|
const imageData = new Uint8Array(event.target.result);
|
|
const dataView = new DataView(imageData.buffer);
|
|
const decoder = new TextDecoder();
|
|
|
|
// Check for JPEG signature (0xFFD8)
|
|
if (dataView.getUint16(0) !== 0xFFD8) {
|
|
resolve(null);
|
|
return;
|
|
}
|
|
|
|
// Search for APP1 marker (EXIF) - 0xFFE1
|
|
let offset = 2;
|
|
while (offset < imageData.length - 4) {
|
|
const marker = dataView.getUint16(offset);
|
|
const segmentLength = dataView.getUint16(offset + 2);
|
|
|
|
if (marker === 0xFFE1) {
|
|
// Check for EXIF header
|
|
const exifHeader = String.fromCharCode(...imageData.slice(offset + 4, offset + 10));
|
|
if (exifHeader === 'Exif\x00\x00') {
|
|
// Parse TIFF header
|
|
const tiffOffset = offset + 10;
|
|
const byteOrder = dataView.getUint16(tiffOffset);
|
|
const littleEndian = byteOrder === 0x4949;
|
|
|
|
// Get IFD0 offset
|
|
const ifd0Offset = tiffOffset + dataView.getUint32(tiffOffset + 4, littleEndian);
|
|
|
|
// Search for UserComment tag (0x9286)
|
|
const metadata = parseIFD(imageData, ifd0Offset, tiffOffset, littleEndian, decoder);
|
|
if (metadata) {
|
|
resolve(metadata);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Move to next marker
|
|
if (marker >= 0xFF00) {
|
|
offset += 2 + segmentLength;
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
|
|
resolve(null);
|
|
};
|
|
reader.readAsArrayBuffer(file);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Parse EXIF IFD (Image File Directory) for ComfyUI metadata
|
|
* ComfyUI stores metadata in:
|
|
* - 0x010e (ImageDescription): "Workflow: {json}"
|
|
* - 0x010f (Make): "Prompt: {json}"
|
|
* - 0x9286 (UserComment): direct JSON (some tools)
|
|
*/
|
|
function parseIFD(imageData, ifdOffset, tiffOffset, littleEndian, decoder) {
|
|
const dataView = new DataView(imageData.buffer);
|
|
const numEntries = dataView.getUint16(ifdOffset, littleEndian);
|
|
|
|
// Collect workflow and prompt from separate EXIF tags
|
|
let workflow = null;
|
|
let prompt = null;
|
|
|
|
for (let i = 0; i < numEntries; i++) {
|
|
const entryOffset = ifdOffset + 2 + (i * 12);
|
|
const tag = dataView.getUint16(entryOffset, littleEndian);
|
|
|
|
// Tags that store string data: 0x010e (ImageDescription), 0x010f (Make), 0x9286 (UserComment)
|
|
if (tag === 0x010e || tag === 0x010f || tag === 0x9286) {
|
|
const count = dataView.getUint32(entryOffset + 4, littleEndian);
|
|
const valueOffset = dataView.getUint32(entryOffset + 8, littleEndian);
|
|
|
|
// Get actual data offset (values > 4 bytes are stored at an offset)
|
|
const dataOffset = count > 4 ? tiffOffset + valueOffset : entryOffset + 8;
|
|
|
|
// Read the raw string data
|
|
const rawData = imageData.slice(dataOffset, dataOffset + count);
|
|
let text = decoder.decode(rawData);
|
|
|
|
// Remove ASCII/UNICODE prefix and null bytes (for UserComment tag)
|
|
text = text.replace(/^(ASCII|UNICODE)\x00*/, '').replace(/\x00/g, '').trim();
|
|
|
|
// ComfyUI format: "Workflow: {json}" or "Prompt: {json}" with prefix
|
|
if (text.startsWith('Workflow:')) {
|
|
const jsonStr = text.substring('Workflow:'.length).trim();
|
|
try { workflow = JSON.parse(jsonStr); } catch (e) {
|
|
console.error('[PromptExtractor] Failed to parse Workflow from EXIF:', e);
|
|
}
|
|
} else if (text.startsWith('Prompt:')) {
|
|
const jsonStr = text.substring('Prompt:'.length).trim();
|
|
try { prompt = JSON.parse(jsonStr); } catch (e) {
|
|
console.error('[PromptExtractor] Failed to parse Prompt from EXIF:', e);
|
|
}
|
|
} else {
|
|
// Try parsing as direct JSON (UserComment from some tools)
|
|
try {
|
|
const json = JSON.parse(text);
|
|
return json;
|
|
} catch (e) {
|
|
// Not JSON, skip
|
|
}
|
|
}
|
|
}
|
|
|
|
// Check for EXIF SubIFD (tag 0x8769)
|
|
if (tag === 0x8769) {
|
|
const subIfdOffset = tiffOffset + dataView.getUint32(entryOffset + 8, littleEndian);
|
|
const metadata = parseIFD(imageData, subIfdOffset, tiffOffset, littleEndian, decoder);
|
|
if (metadata) return metadata;
|
|
}
|
|
}
|
|
|
|
// Return collected workflow/prompt if found
|
|
if (workflow || prompt) {
|
|
return { workflow, prompt };
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Extract metadata from WebP file
|
|
* WebP uses RIFF container format with EXIF data stored in an "EXIF" chunk
|
|
*/
|
|
async function getWebPMetadata(file) {
|
|
return new Promise((resolve) => {
|
|
const reader = new FileReader();
|
|
reader.onload = (event) => {
|
|
const data = new Uint8Array(event.target.result);
|
|
const dataView = new DataView(data.buffer);
|
|
const decoder = new TextDecoder();
|
|
|
|
// Verify RIFF + WEBP signature
|
|
if (data.length < 12) { resolve(null); return; }
|
|
const riff = String.fromCharCode(data[0], data[1], data[2], data[3]);
|
|
const webp = String.fromCharCode(data[8], data[9], data[10], data[11]);
|
|
if (riff !== 'RIFF' || webp !== 'WEBP') {
|
|
resolve(null);
|
|
return;
|
|
}
|
|
|
|
// Walk RIFF chunks looking for EXIF chunk
|
|
let offset = 12;
|
|
while (offset < data.length - 8) {
|
|
const chunkId = String.fromCharCode(data[offset], data[offset + 1], data[offset + 2], data[offset + 3]);
|
|
const chunkSize = dataView.getUint32(offset + 4, true); // RIFF uses little-endian
|
|
|
|
if (chunkId === 'EXIF') {
|
|
// EXIF chunk data starts after the chunk header (8 bytes)
|
|
let exifStart = offset + 8;
|
|
|
|
// Some WebP files include "Exif\0\0" prefix before TIFF header, some don't
|
|
const possibleExif = String.fromCharCode(data[exifStart], data[exifStart + 1], data[exifStart + 2], data[exifStart + 3]);
|
|
if (possibleExif === 'Exif') {
|
|
exifStart += 6; // Skip "Exif\0\0"
|
|
}
|
|
|
|
// Parse TIFF header
|
|
if (exifStart + 8 <= data.length) {
|
|
const byteOrder = dataView.getUint16(exifStart);
|
|
const littleEndian = byteOrder === 0x4949;
|
|
|
|
// Verify TIFF magic number (42)
|
|
const tiffMagic = dataView.getUint16(exifStart + 2, littleEndian);
|
|
if (tiffMagic === 42) {
|
|
const ifd0Offset = exifStart + dataView.getUint32(exifStart + 4, littleEndian);
|
|
const metadata = parseIFD(data, ifd0Offset, exifStart, littleEndian, decoder);
|
|
if (metadata) {
|
|
resolve(metadata);
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Move to next chunk (pad to even size per RIFF spec)
|
|
offset += 8 + chunkSize + (chunkSize % 2);
|
|
}
|
|
|
|
resolve(null);
|
|
};
|
|
reader.readAsArrayBuffer(file);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Extract metadata from JSON file
|
|
*/
|
|
async function getJSONMetadata(file) {
|
|
return new Promise((resolve) => {
|
|
const reader = new FileReader();
|
|
reader.onload = (event) => {
|
|
try {
|
|
const json = JSON.parse(event.target.result);
|
|
resolve(json);
|
|
} catch (e) {
|
|
console.error('[PromptExtractor] Failed to parse JSON file:', e);
|
|
resolve(null);
|
|
}
|
|
};
|
|
reader.readAsText(file);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Extract metadata from video file (WebM/MKV/MP4)
|
|
* Reads container metadata directly
|
|
*/
|
|
async function getVideoMetadata(file) {
|
|
return new Promise((resolve) => {
|
|
const reader = new FileReader();
|
|
reader.onload = (event) => {
|
|
const videoData = new Uint8Array(event.target.result);
|
|
const dataView = new DataView(videoData.buffer);
|
|
const decoder = new TextDecoder();
|
|
|
|
// Check for WebM/MKV (EBML/Matroska format) - magic: 0x1A45DFA3
|
|
if (dataView.getUint32(0) === 0x1A45DFA3) {
|
|
// Look for COMMENT tag (0x4487) which contains workflow metadata
|
|
let offset = 4 + 8;
|
|
while (offset < videoData.length - 16) {
|
|
if (dataView.getUint16(offset) === 0x4487) {
|
|
const name = String.fromCharCode(...videoData.slice(offset - 7, offset));
|
|
if (name === "COMMENT") {
|
|
let vint = dataView.getUint32(offset + 2);
|
|
let n_octets = Math.clz32(vint) + 1;
|
|
if (n_octets < 4) {
|
|
let length = (vint >> (8 * (4 - n_octets))) & ~(1 << (7 * n_octets));
|
|
const content = decoder.decode(videoData.slice(offset + 2 + n_octets, offset + 2 + n_octets + length));
|
|
try {
|
|
const json = JSON.parse(content);
|
|
resolve(json);
|
|
return;
|
|
} catch (e) {
|
|
console.error("[PromptExtractor] Failed to parse WebM/MKV metadata:", e);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
offset += 1;
|
|
}
|
|
}
|
|
// Check for MP4 (ISO Media format) - ftyp: 0x66747970, isom: 0x69736F6D
|
|
else if (dataView.getUint32(4) === 0x66747970 && dataView.getUint32(8) === 0x69736F6D) {
|
|
// Look for 'cmt' (comment) data tag in MP4
|
|
let offset = videoData.length - 4;
|
|
while (offset > 16) {
|
|
if (dataView.getUint32(offset) === 0x64617461) { // 'data' tag
|
|
if (dataView.getUint32(offset - 8) === 0xa9636d74) { // 'cmt' tag
|
|
let size = dataView.getUint32(offset - 4) - 4 * 4;
|
|
const content = decoder.decode(videoData.slice(offset + 12, offset + 12 + size));
|
|
try {
|
|
const json = JSON.parse(content);
|
|
resolve(json);
|
|
return;
|
|
} catch (e) {
|
|
console.error("[PromptExtractor] Failed to parse MP4 metadata:", e);
|
|
}
|
|
}
|
|
}
|
|
offset -= 1;
|
|
}
|
|
}
|
|
|
|
resolve(null);
|
|
};
|
|
reader.readAsArrayBuffer(file);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Request Python to extract video metadata using ffprobe (fallback)
|
|
*/
|
|
async function extractVideoMetadataWithPython(filename, source = 'input') {
|
|
try {
|
|
console.log(`[PromptExtractor] Requesting Python ffprobe extraction for: ${filename}`);
|
|
const response = await api.fetchApi("/prompt-extractor/extract-video-metadata", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ filename, source })
|
|
});
|
|
|
|
if (response.ok) {
|
|
const result = await response.json();
|
|
if (result.success && result.metadata) {
|
|
console.log(`[PromptExtractor] Python extracted video metadata successfully for: ${filename}`);
|
|
console.log(`[PromptExtractor] Metadata:`, result.metadata);
|
|
return result.metadata;
|
|
} else if (result.warning && result.error === 'ffprobe_not_found') {
|
|
console.warn(`[PromptExtractor] WARNING: Video metadata fallback unavailable - ffprobe not found.`);
|
|
console.warn(`[PromptExtractor] Install FFmpeg to enable metadata extraction for all video formats.`);
|
|
} else {
|
|
console.log(`[PromptExtractor] Python extraction returned no metadata for: ${filename}`);
|
|
}
|
|
} else {
|
|
console.error(`[PromptExtractor] Python extraction failed with status: ${response.status}`);
|
|
}
|
|
return null;
|
|
} catch (error) {
|
|
console.error("[PromptExtractor] Error requesting Python video extraction:", error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Send file metadata to Python backend for caching
|
|
*/
|
|
async function cacheFileMetadata(filename, metadata) {
|
|
try {
|
|
const response = await api.fetchApi("/prompt-extractor/cache-file-metadata", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ filename, metadata })
|
|
});
|
|
|
|
if (response.ok) {
|
|
console.log(`[PromptExtractor] Cached metadata for: ${filename}`);
|
|
} else {
|
|
console.error("[PromptExtractor] Failed to cache metadata:", response.status);
|
|
}
|
|
} catch (error) {
|
|
console.error("[PromptExtractor] Error caching metadata:", error);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Send video frame to Python backend for caching
|
|
*/
|
|
async function cacheVideoFrame(filename, frameData, framePosition) {
|
|
try {
|
|
const response = await api.fetchApi("/prompt-extractor/cache-video-frame", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ filename, frame: frameData, frame_position: framePosition })
|
|
});
|
|
|
|
if (response.ok) {
|
|
console.log(`[PromptExtractor] Cached video frame at position ${framePosition.toFixed(2)} for: ${filename}`);
|
|
} else {
|
|
console.error("[PromptExtractor] Failed to cache video frame:", response.status);
|
|
}
|
|
} catch (error) {
|
|
console.error("[PromptExtractor] Error caching video frame:", error);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Create and show image preview modal
|
|
*/
|
|
function showImagePreviewModal(filename, viewType) {
|
|
const imageUrl = buildPreviewUrl(filename, viewType);
|
|
|
|
// Create modal overlay
|
|
const overlay = document.createElement('div');
|
|
overlay.style.cssText = `
|
|
position: fixed;
|
|
top: 0;
|
|
left: 0;
|
|
width: 100%;
|
|
height: 100%;
|
|
background: rgba(0, 0, 0, 0.85);
|
|
z-index: 10000;
|
|
display: flex;
|
|
flex-direction: column;
|
|
align-items: center;
|
|
justify-content: center;
|
|
`;
|
|
|
|
// Create header with filename and close button
|
|
const header = document.createElement('div');
|
|
header.style.cssText = `
|
|
position: absolute;
|
|
top: 0;
|
|
left: 0;
|
|
right: 0;
|
|
padding: 15px 20px;
|
|
display: flex;
|
|
justify-content: space-between;
|
|
align-items: center;
|
|
background: rgba(0, 0, 0, 0.5);
|
|
`;
|
|
|
|
const title = document.createElement('span');
|
|
title.textContent = filename;
|
|
title.style.cssText = `
|
|
color: #fff;
|
|
font-size: 16px;
|
|
font-family: sans-serif;
|
|
overflow: hidden;
|
|
text-overflow: ellipsis;
|
|
white-space: nowrap;
|
|
max-width: calc(100% - 50px);
|
|
`;
|
|
|
|
const closeBtn = document.createElement('button');
|
|
closeBtn.textContent = 'X';
|
|
closeBtn.style.cssText = `
|
|
background: rgba(255, 255, 255, 0.1);
|
|
border: none;
|
|
color: #fff;
|
|
font-size: 20px;
|
|
width: 36px;
|
|
height: 36px;
|
|
border-radius: 50%;
|
|
cursor: pointer;
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: center;
|
|
transition: background 0.2s;
|
|
`;
|
|
closeBtn.onmouseover = () => closeBtn.style.background = 'rgba(255, 255, 255, 0.2)';
|
|
closeBtn.onmouseout = () => closeBtn.style.background = 'rgba(255, 255, 255, 0.1)';
|
|
closeBtn.onclick = () => overlay.remove();
|
|
|
|
header.appendChild(title);
|
|
header.appendChild(closeBtn);
|
|
|
|
// Create image container
|
|
const imageContainer = document.createElement('div');
|
|
imageContainer.style.cssText = `
|
|
max-width: 90%;
|
|
max-height: 80%;
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: center;
|
|
`;
|
|
|
|
// Create image element
|
|
const img = document.createElement('img');
|
|
img.src = imageUrl;
|
|
img.style.cssText = `
|
|
max-width: 100%;
|
|
max-height: 80vh;
|
|
border-radius: 8px;
|
|
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
|
|
`;
|
|
|
|
// Error handling
|
|
img.onerror = () => {
|
|
imageContainer.innerHTML = `
|
|
<div style="color: #ff6666; font-family: sans-serif; text-align: center;">
|
|
<div style="font-size: 48px; margin-bottom: 10px;">??</div>
|
|
<div>Failed to load image</div>
|
|
<div style="font-size: 14px; margin-top: 5px; opacity: 0.7;">${filename}</div>
|
|
</div>
|
|
`;
|
|
};
|
|
|
|
imageContainer.appendChild(img);
|
|
|
|
// Create keyboard hint
|
|
const hint = document.createElement('div');
|
|
hint.textContent = 'Press ESC or click outside to close';
|
|
hint.style.cssText = `
|
|
position: absolute;
|
|
bottom: 20px;
|
|
color: rgba(255, 255, 255, 0.5);
|
|
font-size: 14px;
|
|
font-family: sans-serif;
|
|
`;
|
|
|
|
overlay.appendChild(header);
|
|
overlay.appendChild(imageContainer);
|
|
overlay.appendChild(hint);
|
|
|
|
// Close on overlay click (but not image click)
|
|
overlay.onclick = (e) => {
|
|
if (e.target === overlay) {
|
|
overlay.remove();
|
|
}
|
|
};
|
|
|
|
// Close on ESC key
|
|
const handleKeydown = (e) => {
|
|
if (e.key === 'Escape') {
|
|
overlay.remove();
|
|
document.removeEventListener('keydown', handleKeydown);
|
|
}
|
|
};
|
|
document.addEventListener('keydown', handleKeydown);
|
|
|
|
// Add to document
|
|
document.body.appendChild(overlay);
|
|
}
|
|
|
|
/**
|
|
* Create and show video preview modal
|
|
*/
|
|
function showVideoPreviewModal(filename, viewType) {
|
|
const videoUrl = buildPreviewUrl(filename, viewType);
|
|
|
|
// Create modal overlay
|
|
const overlay = document.createElement('div');
|
|
overlay.style.cssText = `
|
|
position: fixed;
|
|
top: 0;
|
|
left: 0;
|
|
width: 100%;
|
|
height: 100%;
|
|
background: rgba(0, 0, 0, 0.85);
|
|
z-index: 10000;
|
|
display: flex;
|
|
flex-direction: column;
|
|
align-items: center;
|
|
justify-content: center;
|
|
`;
|
|
|
|
// Create header with filename and close button
|
|
const header = document.createElement('div');
|
|
header.style.cssText = `
|
|
position: absolute;
|
|
top: 0;
|
|
left: 0;
|
|
right: 0;
|
|
padding: 15px 20px;
|
|
display: flex;
|
|
justify-content: space-between;
|
|
align-items: center;
|
|
background: rgba(0, 0, 0, 0.5);
|
|
`;
|
|
|
|
const title = document.createElement('span');
|
|
title.textContent = filename;
|
|
title.style.cssText = `
|
|
color: #fff;
|
|
font-size: 16px;
|
|
font-family: sans-serif;
|
|
overflow: hidden;
|
|
text-overflow: ellipsis;
|
|
white-space: nowrap;
|
|
max-width: calc(100% - 50px);
|
|
`;
|
|
|
|
const closeBtn = document.createElement('button');
|
|
closeBtn.textContent = 'X';
|
|
closeBtn.style.cssText = `
|
|
background: rgba(255, 255, 255, 0.1);
|
|
border: none;
|
|
color: #fff;
|
|
font-size: 20px;
|
|
width: 36px;
|
|
height: 36px;
|
|
border-radius: 50%;
|
|
cursor: pointer;
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: center;
|
|
transition: background 0.2s;
|
|
`;
|
|
closeBtn.onmouseover = () => closeBtn.style.background = 'rgba(255, 255, 255, 0.2)';
|
|
closeBtn.onmouseout = () => closeBtn.style.background = 'rgba(255, 255, 255, 0.1)';
|
|
closeBtn.onclick = () => overlay.remove();
|
|
|
|
header.appendChild(title);
|
|
header.appendChild(closeBtn);
|
|
|
|
// Create video container
|
|
const videoContainer = document.createElement('div');
|
|
videoContainer.style.cssText = `
|
|
max-width: 90%;
|
|
max-height: 80%;
|
|
display: flex;
|
|
align-items: center;
|
|
justify-content: center;
|
|
`;
|
|
|
|
// Create video element
|
|
const video = document.createElement('video');
|
|
video.src = videoUrl;
|
|
video.controls = true;
|
|
video.autoplay = true;
|
|
video.loop = true;
|
|
video.style.cssText = `
|
|
max-width: 100%;
|
|
max-height: 80vh;
|
|
border-radius: 8px;
|
|
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
|
|
`;
|
|
|
|
// Error handling - browser can't decode (H265/yuv444)
|
|
video.onerror = () => {
|
|
// Fall back to server-extracted frame with overlay
|
|
const frameSource = resolveMediaSource(filename, viewType || 'input');
|
|
const frameUrl = `/prompt-extractor/video-frame?filename=${encodeURIComponent(filename)}&source=${frameSource}&position=0`;
|
|
const fallbackImg = document.createElement('img');
|
|
fallbackImg.style.cssText = `
|
|
max-width: 100%; max-height: 80vh; border-radius: 8px;
|
|
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
|
|
`;
|
|
fallbackImg.onload = () => {
|
|
videoContainer.innerHTML = '';
|
|
videoContainer.style.position = 'relative';
|
|
videoContainer.appendChild(fallbackImg);
|
|
const msgOverlay = document.createElement('div');
|
|
msgOverlay.style.cssText = `
|
|
position: absolute; bottom: 20px; left: 50%; transform: translateX(-50%);
|
|
background: rgba(0, 0, 0, 0.75); color: #ccc; padding: 8px 16px;
|
|
border-radius: 6px; font-family: sans-serif; font-size: 15px;
|
|
pointer-events: none; white-space: nowrap;
|
|
`;
|
|
msgOverlay.textContent = 'H265/yuv444 \u2014 browser playback not supported';
|
|
videoContainer.appendChild(msgOverlay);
|
|
};
|
|
fallbackImg.onerror = () => {
|
|
videoContainer.innerHTML = `
|
|
<div style="color: #aaa; font-family: sans-serif; text-align: center;">
|
|
<div style="font-size: 48px; margin-bottom: 10px;">\uD83C\uDFAC</div>
|
|
<div>This video format cannot be played in the browser</div>
|
|
<div style="font-size: 14px; margin-top: 5px; opacity: 0.7;">H265 or yuv444 encoded</div>
|
|
</div>
|
|
`;
|
|
};
|
|
fallbackImg.src = frameUrl;
|
|
};
|
|
|
|
videoContainer.appendChild(video);
|
|
|
|
// Create keyboard hint
|
|
const hint = document.createElement('div');
|
|
hint.textContent = 'Press ESC or click outside to close';
|
|
hint.style.cssText = `
|
|
position: absolute;
|
|
bottom: 20px;
|
|
color: rgba(255, 255, 255, 0.5);
|
|
font-size: 14px;
|
|
font-family: sans-serif;
|
|
`;
|
|
|
|
overlay.appendChild(header);
|
|
overlay.appendChild(videoContainer);
|
|
overlay.appendChild(hint);
|
|
|
|
// Close on overlay click (but not video click)
|
|
overlay.onclick = (e) => {
|
|
if (e.target === overlay) {
|
|
overlay.remove();
|
|
}
|
|
};
|
|
|
|
// Close on ESC key
|
|
const handleKeydown = (e) => {
|
|
if (e.key === 'Escape') {
|
|
overlay.remove();
|
|
document.removeEventListener('keydown', handleKeydown);
|
|
}
|
|
};
|
|
document.addEventListener('keydown', handleKeydown);
|
|
|
|
// Add to document
|
|
document.body.appendChild(overlay);
|
|
|
|
// Focus video for keyboard controls
|
|
video.focus();
|
|
}
|
|
|
|
/**
|
|
* Check if filename is a video file
|
|
*/
|
|
function isVideoFile(filename) {
|
|
if (!filename) return false;
|
|
const ext = filename.split('.').pop().toLowerCase();
|
|
return ['mp4', 'webm', 'mov', 'avi', 'mkv', 'm4v', 'wmv'].includes(ext);
|
|
}
|
|
|
|
/**
|
|
* Check if filename is a previewable file (image or video)
|
|
*/
|
|
function isPreviewableFile(filename) {
|
|
if (!filename || filename === '(none)') return false;
|
|
const ext = filename.split('.').pop().toLowerCase();
|
|
const imageExtensions = ['png', 'jpg', 'jpeg', 'webp', 'gif', 'bmp'];
|
|
const videoExtensions = ['mp4', 'webm', 'mov', 'avi', 'mkv', 'm4v', 'wmv'];
|
|
return imageExtensions.includes(ext) || videoExtensions.includes(ext);
|
|
}
|
|
|
|
// --- Arrow-key media navigation (Left/Right steps files while hovering a node) ---
|
|
let _peHoveredNode = null;
|
|
let _peKeyListenerInstalled = false;
|
|
|
|
function isPromptExtractorNodeInGraph(node) {
|
|
if (!node || !app.graph?._nodes) return false;
|
|
return app.graph._nodes.includes(node);
|
|
}
|
|
|
|
function getActivePromptExtractorNode() {
|
|
// Hover-only: only react when the cursor is actually over a live node.
|
|
if (_peHoveredNode && !_peHoveredNode.flags?.collapsed && isPromptExtractorNodeInGraph(_peHoveredNode)) {
|
|
return _peHoveredNode;
|
|
}
|
|
if (_peHoveredNode && !isPromptExtractorNodeInGraph(_peHoveredNode)) {
|
|
_peHoveredNode = null;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function isTypingTarget(target) {
|
|
if (!target) return false;
|
|
const tag = String(target.tagName || "").toUpperCase();
|
|
return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || !!target.isContentEditable;
|
|
}
|
|
|
|
function installArrowKeyNavigation() {
|
|
if (_peKeyListenerInstalled) return;
|
|
_peKeyListenerInstalled = true;
|
|
|
|
window.addEventListener("keydown", (event) => {
|
|
if (event.defaultPrevented) return;
|
|
if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
|
|
if (event.ctrlKey || event.altKey || event.metaKey || event.shiftKey) return;
|
|
if (isTypingTarget(event.target)) return;
|
|
|
|
const node = getActivePromptExtractorNode();
|
|
if (!node || typeof node._stepImageByDelta !== "function") return;
|
|
|
|
const dir = event.key === "ArrowRight" ? 1 : -1;
|
|
if (!node._stepImageByDelta(dir)) return;
|
|
event.preventDefault();
|
|
event.stopPropagation();
|
|
}, true);
|
|
}
|
|
|
|
app.registerExtension({
|
|
name: "PromptExtractor",
|
|
|
|
async setup() {
|
|
// Listen for frame extraction requests from Python backend
|
|
api.addEventListener("prompt-extractor-extract-frame", async (event) => {
|
|
const { filename, frame_position } = event.detail;
|
|
console.log(`[PromptExtractor] Received extraction request for ${filename} at position ${frame_position}`);
|
|
|
|
// Find the node with this filename
|
|
if (app.graph && app.graph._nodes) {
|
|
for (const node of app.graph._nodes) {
|
|
if (node.type === "PromptExtractor" || node.type === "RecipeExtractor") {
|
|
const imageWidget = node.widgets?.find(w => w.name === "image");
|
|
const frameWidget = node.widgets?.find(w => w.name === "frame_position");
|
|
|
|
if (imageWidget && imageWidget.value === filename) {
|
|
// Update frame position if provided
|
|
if (frameWidget && frame_position !== undefined) {
|
|
frameWidget.value = frame_position;
|
|
}
|
|
|
|
// Trigger extraction
|
|
await loadAndDisplayImage(node, filename);
|
|
console.log(`[PromptExtractor] Extracted and cached frame for ${filename}`);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
});
|
|
},
|
|
|
|
async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
|
if (nodeData.name === "PromptExtractor" || nodeData.name === "RecipeExtractor") {
|
|
const onNodeCreated = nodeType.prototype.onNodeCreated;
|
|
|
|
nodeType.prototype.onNodeCreated = function () {
|
|
const result = onNodeCreated?.apply(this, arguments);
|
|
|
|
const node = this;
|
|
|
|
// Track workflow metadata status for indicator
|
|
node.hasWorkflow = false;
|
|
// Track the currently loaded image filename and frame position to prevent unnecessary reloads
|
|
node._loadedImageFilename = null;
|
|
node._loadedFramePosition = null;
|
|
// Track source folder for URL type
|
|
node._sourceFolder = 'input';
|
|
node._imagePickerMap = { "(none)": "(none)" };
|
|
// Find the frame_position widget (slider) early so we can reference it
|
|
const framePositionWidget = this.widgets?.find(w => w.name === "frame_position");
|
|
let imagePickerWidget = null;
|
|
let updateImagePickerOptions = () => {};
|
|
let refreshImageOptionsForSource = async () => {};
|
|
let refreshImageOptionsForBrowsePath = async () => false;
|
|
|
|
// Find the source_folder widget
|
|
const sourceFolderWidget = this.widgets?.find(w => w.name === "source_folder");
|
|
if (sourceFolderWidget) {
|
|
node._sourceFolder = sourceFolderWidget.value || 'input';
|
|
hideWidget(sourceFolderWidget);
|
|
const origSourceFolderCb = sourceFolderWidget.callback;
|
|
sourceFolderWidget.callback = async function(value) {
|
|
if (origSourceFolderCb) origSourceFolderCb.apply(this, arguments);
|
|
node._sourceFolder = value || 'input';
|
|
// Refresh file list for the new source folder.
|
|
// Keep current selection (including absolute paths) if still valid.
|
|
try {
|
|
const listResponse = await api.fetchApi(`/prompt-extractor/list-files?source=${encodeURIComponent(value)}`);
|
|
if (listResponse.ok) {
|
|
const result = await listResponse.json();
|
|
if (imageWidget) {
|
|
const files = Array.isArray(result.files) ? result.files : [];
|
|
imageWidget.options.values = ["(none)", ...files];
|
|
|
|
if (imagePickerWidget) {
|
|
const labels = ["(none)"];
|
|
const map = { "(none)": "(none)" };
|
|
const usedLabels = new Set(["(none)"]);
|
|
for (const fullValue of files) {
|
|
const base = basenameForDisplay(fullValue) || fullValue;
|
|
let label = base;
|
|
let idx = 2;
|
|
while (usedLabels.has(label)) {
|
|
label = `${base} (${idx++})`;
|
|
}
|
|
usedLabels.add(label);
|
|
labels.push(label);
|
|
map[label] = fullValue;
|
|
}
|
|
node._imagePickerMap = map;
|
|
imagePickerWidget.options.values = labels;
|
|
}
|
|
|
|
const currentValue = imageWidget.value;
|
|
const keepValue = isAbsolutePath(currentValue) || files.includes(currentValue);
|
|
if (keepValue && currentValue && currentValue !== "(none)") {
|
|
if (!imageWidget.options.values.includes(currentValue)) {
|
|
imageWidget.options.values = [...imageWidget.options.values, currentValue];
|
|
}
|
|
imageWidget.value = currentValue;
|
|
} else {
|
|
imageWidget.value = "(none)";
|
|
if (imageWidget.callback) imageWidget.callback("(none)");
|
|
}
|
|
}
|
|
}
|
|
} catch (err) {
|
|
console.warn('[PromptExtractor] Could not fetch file list for source folder:', err);
|
|
}
|
|
node.setDirtyCanvas(true);
|
|
};
|
|
}
|
|
|
|
// Find the image widget (combo dropdown)
|
|
const imageWidget = this.widgets?.find(w => w.name === "image");
|
|
if (imageWidget) {
|
|
updateImagePickerOptions = (values, preferredValue = null) => {
|
|
if (!imagePickerWidget) return;
|
|
|
|
const labels = ["(none)"];
|
|
const map = { "(none)": "(none)" };
|
|
const usedLabels = new Set(["(none)"]);
|
|
|
|
for (const fullValue of values || []) {
|
|
const base = basenameForDisplay(fullValue) || fullValue;
|
|
let label = base;
|
|
let idx = 2;
|
|
while (usedLabels.has(label)) {
|
|
label = `${base} (${idx++})`;
|
|
}
|
|
usedLabels.add(label);
|
|
labels.push(label);
|
|
map[label] = fullValue;
|
|
}
|
|
|
|
node._imagePickerMap = map;
|
|
imagePickerWidget.options.values = labels;
|
|
|
|
const desired = stripAnnotation(preferredValue != null ? preferredValue : imageWidget?.value);
|
|
if (desired && desired !== "(none)") {
|
|
const label = Object.keys(map).find((k) => map[k] === desired);
|
|
imagePickerWidget.value = label || "(none)";
|
|
} else {
|
|
imagePickerWidget.value = "(none)";
|
|
}
|
|
};
|
|
|
|
refreshImageOptionsForSource = async (source, options = {}) => {
|
|
const { resetSelection = false, preferredValue = null } = options;
|
|
try {
|
|
const listResponse = await api.fetchApi(`/prompt-extractor/list-files?source=${encodeURIComponent(source || 'input')}`);
|
|
if (!listResponse.ok) return;
|
|
|
|
const result = await listResponse.json();
|
|
const files = Array.isArray(result?.files) ? result.files : [];
|
|
imageWidget.options.values = ["(none)", ...files];
|
|
updateImagePickerOptions(files, preferredValue);
|
|
|
|
if (resetSelection) {
|
|
if (imageWidget.value !== "(none)") {
|
|
imageWidget.value = "(none)";
|
|
if (imageWidget.callback) imageWidget.callback("(none)");
|
|
}
|
|
return;
|
|
}
|
|
|
|
const desiredRaw = preferredValue != null ? preferredValue : imageWidget.value;
|
|
const desired = stripAnnotation(desiredRaw);
|
|
if (desired && desired !== "(none)") {
|
|
if (!imageWidget.options.values.includes(desired)) {
|
|
imageWidget.options.values = ["(none)", desired, ...files.filter((f) => f !== desired)];
|
|
}
|
|
imageWidget.value = desired;
|
|
}
|
|
} catch (err) {
|
|
console.warn('[PromptExtractor] Could not fetch file list:', err);
|
|
}
|
|
};
|
|
|
|
refreshImageOptionsForBrowsePath = async (browsePath, preferredValue = null) => {
|
|
if (!browsePath) return false;
|
|
try {
|
|
const roots = await getMediaRoots();
|
|
const resp = await api.fetchApi(
|
|
`/prompt-extractor/path-browser/list?path=${encodeURIComponent(browsePath)}&kind=media`
|
|
);
|
|
if (!resp.ok) return false;
|
|
|
|
const data = await resp.json();
|
|
const files = Array.isArray(data?.files) ? data.files : [];
|
|
const mapped = [];
|
|
const seen = new Set();
|
|
|
|
for (const f of files) {
|
|
const absPath = typeof f === "string" ? f : f?.path;
|
|
if (!absPath) continue;
|
|
const cls = classifySelection(absPath, roots);
|
|
const value = cls?.value || String(absPath);
|
|
if (!seen.has(value)) {
|
|
seen.add(value);
|
|
mapped.push(value);
|
|
}
|
|
}
|
|
|
|
const desiredRaw = preferredValue != null ? preferredValue : imageWidget.value;
|
|
const desired = stripAnnotation(desiredRaw);
|
|
imageWidget.options.values = ["(none)", ...mapped];
|
|
updateImagePickerOptions(mapped, desired);
|
|
if (desired && desired !== "(none)") imageWidget.value = desired;
|
|
return true;
|
|
} catch (err) {
|
|
console.warn('[PromptExtractor] Could not refresh options for browse path:', err);
|
|
return false;
|
|
}
|
|
};
|
|
|
|
// Track the last known value to detect changes
|
|
let lastImageValue = imageWidget.value;
|
|
let extractionInProgress = false;
|
|
|
|
hideWidget(imageWidget);
|
|
|
|
// Store original callback
|
|
const originalCallback = imageWidget.callback;
|
|
|
|
// Override callback to load and display image
|
|
imageWidget.callback = function(value) {
|
|
if (originalCallback) {
|
|
originalCallback.apply(this, arguments);
|
|
}
|
|
|
|
// Reset metadata cache when selecting a new file
|
|
node._metadataCached = false;
|
|
|
|
// Reset frame position to 0 when selecting a new video
|
|
if (value && framePositionWidget) {
|
|
const ext = value.split('.').pop().toLowerCase();
|
|
const videoExtensions = ['mp4', 'webm', 'mov', 'avi'];
|
|
if (videoExtensions.includes(ext)) {
|
|
framePositionWidget.value = 0;
|
|
}
|
|
}
|
|
|
|
// Load and display the image/video (handles all display logic)
|
|
loadAndDisplayImage(node, value);
|
|
};
|
|
|
|
const setImageFilename = (value) => {
|
|
if (!imageWidget) return;
|
|
if (!imageWidget.options) imageWidget.options = {};
|
|
const values = imageWidget.options.values;
|
|
if (Array.isArray(values)) {
|
|
if (value && !values.includes(value)) {
|
|
imageWidget.options.values = [...values, value];
|
|
}
|
|
} else if (values && typeof values === "object") {
|
|
const existingValues = Object.values(values);
|
|
if (value && !existingValues.includes(value)) {
|
|
const base = basenameForDisplay(value) || value;
|
|
let label = base;
|
|
let n = 2;
|
|
while (Object.prototype.hasOwnProperty.call(values, label)) {
|
|
label = `${base} (${n++})`;
|
|
}
|
|
imageWidget.options.values = { ...values, [label]: value };
|
|
}
|
|
} else {
|
|
imageWidget.options.values = ["(none)"];
|
|
if (value && value !== "(none)") {
|
|
imageWidget.options.values.push(value);
|
|
}
|
|
}
|
|
|
|
imageWidget.value = value;
|
|
if (imageWidget.callback) imageWidget.callback(value);
|
|
|
|
const map = node._imagePickerMap || { "(none)": "(none)" };
|
|
const currentLabel = Object.keys(map).find((k) => map[k] === value);
|
|
if (imagePickerWidget) {
|
|
imagePickerWidget.value = currentLabel || "(none)";
|
|
}
|
|
node.setDirtyCanvas(true);
|
|
};
|
|
|
|
// Build the flat list of selectable file values (same order as
|
|
// the picker combo) for arrow-key stepping.
|
|
const listImageValues = () => {
|
|
const out = [];
|
|
const seen = new Set();
|
|
|
|
const add = (v) => {
|
|
if (typeof v !== "string") return;
|
|
const value = stripAnnotation(v);
|
|
if (!value || value === "(none)" || seen.has(value)) return;
|
|
seen.add(value);
|
|
out.push(value);
|
|
};
|
|
|
|
const map = node._imagePickerMap;
|
|
if (map && typeof map === "object") {
|
|
for (const value of Object.values(map)) {
|
|
add(value);
|
|
}
|
|
if (out.length > 0) return out;
|
|
}
|
|
|
|
const values = imageWidget.options.values;
|
|
if (Array.isArray(values)) {
|
|
for (const value of values) add(value);
|
|
} else if (values && typeof values === "object") {
|
|
for (const value of Object.values(values)) add(value);
|
|
}
|
|
|
|
return out;
|
|
};
|
|
|
|
node._stepImageByDelta = (delta) => {
|
|
if (!imageWidget) return false;
|
|
|
|
// When the video input is connected the picker UI is hidden,
|
|
// so stepping files is not meaningful.
|
|
const videoInput = (node.inputs || []).find(i => i?.name === "video");
|
|
if (videoInput && videoInput.link != null) return false;
|
|
|
|
const values = listImageValues();
|
|
if (values.length <= 1) return false;
|
|
|
|
const dir = delta >= 0 ? 1 : -1;
|
|
const current = stripAnnotation(imageWidget.value);
|
|
const currentIndex = values.indexOf(current);
|
|
|
|
let nextIndex;
|
|
if (currentIndex < 0) {
|
|
nextIndex = dir > 0 ? 0 : values.length - 1;
|
|
} else {
|
|
nextIndex = (currentIndex + dir + values.length) % values.length;
|
|
}
|
|
|
|
setImageFilename(values[nextIndex]);
|
|
return true;
|
|
};
|
|
|
|
// Watch for value changes to update metadata indicator
|
|
const originalOnDrawForeground = node.onDrawForeground;
|
|
node.onDrawForeground = function(ctx) {
|
|
if (originalOnDrawForeground) {
|
|
originalOnDrawForeground.call(this, ctx);
|
|
}
|
|
|
|
// Check if image value changed and not already extracting
|
|
if (imageWidget.value !== lastImageValue && !extractionInProgress) {
|
|
extractionInProgress = true;
|
|
lastImageValue = imageWidget.value;
|
|
extractAndUpdateMetadata(node, imageWidget.value).finally(() => {
|
|
extractionInProgress = false;
|
|
});
|
|
}
|
|
};
|
|
|
|
// Add custom "Browse Files" button AFTER the image widget
|
|
const imageWidgetIndex = this.widgets.indexOf(imageWidget);
|
|
|
|
imagePickerWidget = this.addWidget(
|
|
"combo",
|
|
"file",
|
|
"(none)",
|
|
(label) => {
|
|
const selected = node._imagePickerMap?.[label] || "(none)";
|
|
setImageFilename(selected);
|
|
},
|
|
{ values: ["(none)"] }
|
|
);
|
|
imagePickerWidget.serialize = false;
|
|
|
|
const pickerIndex = this.widgets.indexOf(imagePickerWidget);
|
|
if (pickerIndex >= 0) {
|
|
this.widgets.splice(pickerIndex, 1);
|
|
this.widgets.splice(imageWidgetIndex + 1, 0, imagePickerWidget);
|
|
}
|
|
|
|
const browseButton = {
|
|
type: "button",
|
|
name: "Browse Files",
|
|
value: null,
|
|
callback: async () => {
|
|
const roots = await getMediaRoots();
|
|
const currentFile = imageWidget.value === "(none)" ? null : imageWidget.value;
|
|
let initialPath = node.properties?._browsePath || "";
|
|
if (!initialPath) {
|
|
const sf = node.widgets?.find(w => w.name === "source_folder")?.value || "input";
|
|
initialPath = sf === "output" ? roots.output : roots.input;
|
|
}
|
|
const sf = node.widgets?.find(w => w.name === "source_folder")?.value || "input";
|
|
const currentSelection = stripAnnotation(imageWidget.value);
|
|
let selectedAbsPath = "";
|
|
if (currentSelection && currentSelection !== "(none)") {
|
|
if (isAbsolutePath(currentSelection)) {
|
|
selectedAbsPath = currentSelection;
|
|
} else {
|
|
const root = sf === "output" ? roots.output : roots.input;
|
|
if (root) {
|
|
const rootNorm = String(root).replace(/[\\/]+$/, "");
|
|
const relNorm = String(currentSelection).replace(/^[\\/]+/, "");
|
|
selectedAbsPath = `${rootNorm}/${relNorm}`;
|
|
}
|
|
}
|
|
}
|
|
if (!selectedAbsPath && node.properties?._browseSelectedAbsPath) {
|
|
selectedAbsPath = node.properties._browseSelectedAbsPath;
|
|
}
|
|
|
|
// Open file browser modal
|
|
await createFileBrowserModal(currentSelection, (selected, meta) => {
|
|
if (!node.properties) node.properties = {};
|
|
|
|
if (meta && meta.absPath) {
|
|
node.properties._browsePath = meta.dir || "";
|
|
node.properties._browseSelectedAbsPath = meta.absPath;
|
|
const cls = classifySelection(meta.absPath, meta.roots);
|
|
const sfW = node.widgets?.find(w => w.name === "source_folder");
|
|
if (cls.sourceFolder && sfW) {
|
|
sfW.value = cls.sourceFolder;
|
|
node._sourceFolder = cls.sourceFolder;
|
|
}
|
|
setImageFilename(cls.value);
|
|
refreshImageOptionsForBrowsePath(meta.dir, cls.value);
|
|
} else {
|
|
node.properties._browseSelectedAbsPath = "";
|
|
setImageFilename(selected);
|
|
if (node.properties?._browsePath) {
|
|
refreshImageOptionsForBrowsePath(node.properties._browsePath, selected);
|
|
}
|
|
}
|
|
|
|
// Mark node as needing update
|
|
node.setDirtyCanvas(true);
|
|
}, sf, {
|
|
navKind: "all",
|
|
allowedTypes: ["image", "video", "json"],
|
|
initialPath,
|
|
selectedAbsPath,
|
|
});
|
|
},
|
|
serialize: false // Don't save button state
|
|
};
|
|
|
|
// Insert button right after the image widget
|
|
this.widgets.splice(imageWidgetIndex + 2, 0, browseButton);
|
|
Object.defineProperty(browseButton, "node", { value: node });
|
|
node._browseFilesButton = browseButton;
|
|
|
|
// Track if current file is a video for UI behavior
|
|
node._isVideoFile = false;
|
|
|
|
// Function to update video-specific UI visibility
|
|
const updateVideoUIVisibility = () => {
|
|
const isVideo = isVideoFile(imageWidget.value);
|
|
node._isVideoFile = isVideo;
|
|
|
|
// Show/hide frame_position widget based on file type
|
|
if (framePositionWidget) {
|
|
framePositionWidget.hidden = !isVideo;
|
|
}
|
|
|
|
node.setDirtyCanvas(true);
|
|
};
|
|
|
|
// Wrap the image widget callback to also update visibility
|
|
const wrappedCallback = imageWidget.callback;
|
|
imageWidget.callback = function(value) {
|
|
if (wrappedCallback) {
|
|
wrappedCallback.apply(this, arguments);
|
|
}
|
|
updateVideoUIVisibility();
|
|
};
|
|
|
|
// Initial visibility check
|
|
setTimeout(updateVideoUIVisibility, 100);
|
|
}
|
|
|
|
// Configure frame_position widget behavior
|
|
if (framePositionWidget) {
|
|
// Ensure the widget is serialized (saved in workflows)
|
|
framePositionWidget.serialize = true;
|
|
|
|
// Initially hide frame_position (will be shown if video is loaded)
|
|
framePositionWidget.hidden = true;
|
|
|
|
// Store original callback
|
|
const originalFrameCallback = framePositionWidget.callback;
|
|
|
|
// Debounce timer to prevent excessive frame extraction during slider drag
|
|
let frameUpdateTimer = null;
|
|
|
|
// Override callback to reload video frame when position changes
|
|
framePositionWidget.callback = function(value) {
|
|
if (originalFrameCallback) {
|
|
originalFrameCallback.apply(this, arguments);
|
|
}
|
|
|
|
// Clear any pending frame update
|
|
if (frameUpdateTimer) {
|
|
clearTimeout(frameUpdateTimer);
|
|
}
|
|
|
|
// Debounce: only extract frame after user stops moving slider for 300ms
|
|
frameUpdateTimer = setTimeout(() => {
|
|
// If a video is currently loaded, reload it with new frame position
|
|
if (imageWidget && imageWidget.value) {
|
|
const filename = imageWidget.value;
|
|
const ext = filename.split('.').pop().toLowerCase();
|
|
const videoExtensions = ['mp4', 'webm', 'mov', 'avi'];
|
|
|
|
if (videoExtensions.includes(ext)) {
|
|
loadVideoFrame(node, filename);
|
|
}
|
|
}
|
|
}, 300);
|
|
};
|
|
}
|
|
|
|
// Hook into workflow restoration to load preview for restored values
|
|
const onConfigure = node.onConfigure;
|
|
node.onConfigure = function(info) {
|
|
const result = onConfigure ? onConfigure.apply(this, arguments) : undefined;
|
|
|
|
// ── Migration: remove stale inputs/outputs from old workflows ──
|
|
const isWorkflowExtractor = this.type === "RecipeExtractor";
|
|
const VALID_INPUTS = isWorkflowExtractor
|
|
? new Set([])
|
|
: new Set(["lora_stack_a", "lora_stack_b", "video"]);
|
|
if (this.inputs) {
|
|
for (let i = this.inputs.length - 1; i >= 0; i--) {
|
|
if (!VALID_INPUTS.has(this.inputs[i].name)) {
|
|
this.removeInput(i);
|
|
}
|
|
}
|
|
}
|
|
const VALID_OUTPUTS = isWorkflowExtractor
|
|
? [
|
|
{ name: "image", type: "IMAGE" },
|
|
{ name: "manager_data", type: "MANAGER_DATA" },
|
|
]
|
|
: [
|
|
{ name: "positive_prompt", type: "STRING" },
|
|
{ name: "negative_prompt", type: "STRING" },
|
|
{ name: "lora_stack_a", type: "LORA_STACK" },
|
|
{ name: "lora_stack_b", type: "LORA_STACK" },
|
|
{ name: "image", type: "IMAGE" },
|
|
];
|
|
if (this.outputs) {
|
|
const namesMatch = this.outputs.length === VALID_OUTPUTS.length &&
|
|
VALID_OUTPUTS.every((v, i) => this.outputs[i]?.name === v.name && this.outputs[i]?.type === v.type);
|
|
if (!namesMatch) {
|
|
// Preserve existing links by output name (recipe_data was renamed manager_data)
|
|
const legacyNames = { recipe_data: "manager_data" };
|
|
const savedByIndex = this.outputs.map(o => o.links ? [...o.links] : null);
|
|
const savedLinks = new Map(this.outputs.map((o, i) => [legacyNames[o.name] || o.name, savedByIndex[i]]));
|
|
this.outputs.length = 0;
|
|
for (let i = 0; i < VALID_OUTPUTS.length; i++) {
|
|
this.addOutput(VALID_OUTPUTS[i].name, VALID_OUTPUTS[i].type);
|
|
const links = savedLinks.has(VALID_OUTPUTS[i].name) || isWorkflowExtractor
|
|
? savedLinks.get(VALID_OUTPUTS[i].name)
|
|
: savedByIndex[i];
|
|
if (!links) continue;
|
|
this.outputs[i].links = links;
|
|
for (const linkId of links) {
|
|
const link = this.graph?.links?.[linkId];
|
|
if (link) {
|
|
link.origin_slot = i;
|
|
link.type = VALID_OUTPUTS[i].type;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Restore source_folder from widget value
|
|
const sfWidget = this.widgets?.find(w => w.name === "source_folder");
|
|
if (sfWidget) {
|
|
node._sourceFolder = sfWidget.value || 'input';
|
|
}
|
|
|
|
// Refresh source list and keep current value, including absolute paths.
|
|
if (imageWidget) {
|
|
if (node.properties?._browsePath) {
|
|
refreshImageOptionsForBrowsePath(node.properties._browsePath, imageWidget?.value);
|
|
} else {
|
|
refreshImageOptionsForSource(node._sourceFolder, { preferredValue: imageWidget?.value });
|
|
}
|
|
}
|
|
|
|
// Restore frame_position if it exists in the workflow data
|
|
if (info && info.widgets_values && framePositionWidget) {
|
|
// Find the frame_position widget's index
|
|
const frameWidgetIndex = this.widgets.findIndex(w => w.name === "frame_position");
|
|
if (frameWidgetIndex >= 0 && info.widgets_values[frameWidgetIndex] !== undefined) {
|
|
framePositionWidget.value = info.widgets_values[frameWidgetIndex];
|
|
}
|
|
}
|
|
|
|
// After workflow is configured, load the preview if a file is selected
|
|
// Only reload if we're not already displaying this exact image/video frame (prevents refresh on queue)
|
|
if (imageWidget && imageWidget.value && imageWidget.value !== "(none)") {
|
|
const isVideo = isVideoFile(imageWidget.value);
|
|
const currentFramePos = framePositionWidget ? framePositionWidget.value : 0.0;
|
|
|
|
// Check if we already have this exact image/frame loaded
|
|
// Also verify the actual image src matches (prevents stale images when switching tabs)
|
|
const expectedFilename = encodeURIComponent(imageWidget.value);
|
|
const hasCorrectImage = node.imgs && node.imgs[0] &&
|
|
node.imgs[0].src && node.imgs[0].src.includes(expectedFilename);
|
|
|
|
const alreadyLoaded = node._loadedImageFilename === imageWidget.value &&
|
|
(!isVideo || node._loadedFramePosition === currentFramePos) &&
|
|
hasCorrectImage;
|
|
|
|
if (!alreadyLoaded) {
|
|
loadAndDisplayImage(node, imageWidget.value);
|
|
}
|
|
}
|
|
|
|
return result;
|
|
};
|
|
|
|
// Load initial image if widget has a value on creation
|
|
if (imageWidget) {
|
|
// Use setTimeout to ensure node is fully initialized
|
|
setTimeout(() => {
|
|
if (imageWidget.value && imageWidget.value !== "(none)") {
|
|
// Only load if not already loaded
|
|
if (node._loadedImageFilename !== imageWidget.value) {
|
|
loadAndDisplayImage(node, imageWidget.value);
|
|
}
|
|
} else {
|
|
// Show placeholder for (none) or empty
|
|
showPlaceholder(node);
|
|
}
|
|
}, 10);
|
|
}
|
|
|
|
// Add drag-and-drop support for file uploads
|
|
node.onDragOver = function(e) {
|
|
if (e.dataTransfer && e.dataTransfer.items) {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
return true; // Allow drop
|
|
}
|
|
return false;
|
|
};
|
|
|
|
node.onDragDrop = async function(e) {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
|
|
if (!e.dataTransfer || !e.dataTransfer.files || e.dataTransfer.files.length === 0) {
|
|
return false;
|
|
}
|
|
|
|
const file = e.dataTransfer.files[0];
|
|
const filename = file.name;
|
|
const ext = filename.split('.').pop().toLowerCase();
|
|
const supportedExtensions = ['png', 'jpg', 'jpeg', 'webp', 'json', 'mp4', 'webm', 'mov', 'avi'];
|
|
|
|
if (!supportedExtensions.includes(ext)) {
|
|
console.warn(`[PromptExtractor] Unsupported file type: ${ext}`);
|
|
return false;
|
|
}
|
|
|
|
// Upload file to input directory
|
|
const formData = new FormData();
|
|
formData.append('image', file);
|
|
formData.append('subfolder', '');
|
|
formData.append('type', 'input');
|
|
|
|
try {
|
|
const response = await api.fetchApi('/upload/image', {
|
|
method: 'POST',
|
|
body: formData
|
|
});
|
|
|
|
if (response.ok) {
|
|
const data = await response.json();
|
|
const uploadedFilename = data.name;
|
|
|
|
// Update widget with new file
|
|
if (imageWidget) {
|
|
// Fetch updated file list from server
|
|
try {
|
|
const sourceFolder = node._sourceFolder || 'input';
|
|
const listResponse = await api.fetchApi(`/prompt-extractor/list-files?source=${encodeURIComponent(sourceFolder)}`);
|
|
if (listResponse.ok) {
|
|
const result = await listResponse.json();
|
|
if (result.files && result.files.length > 0) {
|
|
// Update widget options with fresh file list
|
|
imageWidget.options.values = result.files;
|
|
}
|
|
}
|
|
} catch (err) {
|
|
console.warn('[PromptExtractor] Could not fetch file list:', err);
|
|
}
|
|
|
|
// Set the value and trigger callback
|
|
imageWidget.value = uploadedFilename;
|
|
|
|
// Trigger the original callback to load and display
|
|
if (imageWidget.callback) {
|
|
imageWidget.callback(uploadedFilename);
|
|
}
|
|
}
|
|
|
|
console.log(`[PromptExtractor] Uploaded file: ${uploadedFilename}`);
|
|
} else {
|
|
console.error('[PromptExtractor] Upload failed:', response.status);
|
|
}
|
|
} catch (error) {
|
|
console.error('[PromptExtractor] Error uploading file:', error);
|
|
}
|
|
|
|
return true;
|
|
};
|
|
|
|
// Add workflow status indicator light and preview button
|
|
const onDrawForeground = node.onDrawForeground;
|
|
node.onDrawForeground = function(ctx) {
|
|
const result = onDrawForeground ? onDrawForeground.apply(this, arguments) : undefined;
|
|
|
|
// Draw status indicator if we have an image and node is not minimized
|
|
if (node.imgs && node.imgs.length > 0 && !(node.flags && node.flags.collapsed)) {
|
|
ctx.save();
|
|
const titleHeight = LiteGraph.NODE_TITLE_HEIGHT || 30;
|
|
const infoWidth = 30;
|
|
const infoHeight = 14;
|
|
const infoX = node.size[0] - infoWidth - 8;
|
|
const infoY = (titleHeight / 2) - 37;
|
|
const cornerRadius = 7;
|
|
|
|
// Draw compact info pill (blue active, gray inactive)
|
|
const drawRoundRect = (x, y, w, h, r) => {
|
|
ctx.beginPath();
|
|
ctx.moveTo(x + r, y);
|
|
ctx.lineTo(x + w - r, y);
|
|
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
|
|
ctx.lineTo(x + w, y + h - r);
|
|
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
|
|
ctx.lineTo(x + r, y + h);
|
|
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
|
|
ctx.lineTo(x, y + r);
|
|
ctx.quadraticCurveTo(x, y, x + r, y);
|
|
ctx.closePath();
|
|
};
|
|
|
|
drawRoundRect(infoX, infoY, infoWidth, infoHeight, cornerRadius);
|
|
ctx.fillStyle = node.hasWorkflow ? 'rgba(55, 142, 255, 0.92)' : 'rgba(120, 130, 140, 0.35)';
|
|
ctx.fill();
|
|
ctx.strokeStyle = 'rgba(240, 248, 255, 0.95)';
|
|
ctx.lineWidth = 1;
|
|
ctx.stroke();
|
|
|
|
ctx.fillStyle = node.hasWorkflow ? '#ffffff' : 'rgba(220, 226, 234, 0.75)';
|
|
ctx.font = 'bold 8px sans-serif';
|
|
ctx.textAlign = 'center';
|
|
ctx.textBaseline = 'middle';
|
|
ctx.fillText('info', infoX + (infoWidth / 2), infoY + (infoHeight / 2) + 0.5);
|
|
|
|
node._workflowInfoBounds = {
|
|
x: infoX,
|
|
y: infoY,
|
|
width: infoWidth,
|
|
height: infoHeight,
|
|
};
|
|
|
|
// Draw preview play icon (simple triangle) left of workflow indicator - only for images/videos
|
|
const imageWidget = node.widgets?.find(w => w.name === "image");
|
|
const currentFile = imageWidget?.value;
|
|
|
|
if (isPreviewableFile(currentFile)) {
|
|
const playX = infoX - 14;
|
|
const playY = infoY + (infoHeight / 2);
|
|
const triSize = 7;
|
|
|
|
ctx.beginPath();
|
|
ctx.moveTo(playX - triSize, playY - triSize);
|
|
ctx.lineTo(playX - triSize, playY + triSize);
|
|
ctx.lineTo(playX + triSize, playY);
|
|
ctx.closePath();
|
|
ctx.fillStyle = node._hoverPreviewIcon ? '#ffffff' : 'rgba(255, 255, 255, 0.7)';
|
|
ctx.fill();
|
|
|
|
// Store play icon bounds for click detection
|
|
node._previewIconBounds = {
|
|
x: playX - triSize - 3,
|
|
y: playY - triSize - 3,
|
|
width: triSize * 2 + 6,
|
|
height: triSize * 2 + 6
|
|
};
|
|
} else {
|
|
node._previewIconBounds = null;
|
|
}
|
|
ctx.restore();
|
|
} else {
|
|
node._workflowInfoBounds = null;
|
|
node._previewIconBounds = null;
|
|
}
|
|
|
|
return result;
|
|
};
|
|
|
|
// Add tooltip on hover
|
|
const onMouseMove = node.onMouseMove;
|
|
node.onMouseMove = function(e, localPos, canvas) {
|
|
const result = onMouseMove ? onMouseMove.apply(this, arguments) : undefined;
|
|
|
|
const infoBounds = node._workflowInfoBounds;
|
|
if (infoBounds &&
|
|
localPos[0] >= infoBounds.x && localPos[0] <= infoBounds.x + infoBounds.width &&
|
|
localPos[1] >= infoBounds.y && localPos[1] <= infoBounds.y + infoBounds.height) {
|
|
canvas.canvas.title = node.hasWorkflow ?
|
|
'Workflow metadata found (info available)' :
|
|
'No workflow metadata';
|
|
canvas.canvas.style.cursor = node.hasWorkflow ? 'pointer' : '';
|
|
node._hoverPreviewIcon = false;
|
|
} else if (node._previewIconBounds) {
|
|
// Check if hovering over preview icon
|
|
const bounds = node._previewIconBounds;
|
|
if (localPos[0] >= bounds.x && localPos[0] <= bounds.x + bounds.width &&
|
|
localPos[1] >= bounds.y && localPos[1] <= bounds.y + bounds.height) {
|
|
canvas.canvas.style.cursor = 'pointer';
|
|
canvas.canvas.title = 'Click to preview';
|
|
node._hoverPreviewIcon = true;
|
|
node.setDirtyCanvas(true);
|
|
} else {
|
|
if (node._hoverPreviewIcon) {
|
|
node._hoverPreviewIcon = false;
|
|
node.setDirtyCanvas(true);
|
|
}
|
|
canvas.canvas.style.cursor = '';
|
|
}
|
|
} else if (isPosOverPreview(localPos)) {
|
|
canvas.canvas.style.cursor = 'pointer';
|
|
canvas.canvas.title = 'Click to browse files';
|
|
} else {
|
|
canvas.canvas.style.cursor = '';
|
|
}
|
|
|
|
return result;
|
|
};
|
|
|
|
// ── Click on the preview thumbnail to open the file browser ──
|
|
// The preview is drawn by LiteGraph in the node body below all
|
|
// visible widgets, so hit-test that area on the canvas.
|
|
const isVideoInputConnected = () =>
|
|
(node.inputs || []).some(i => i?.name === "video" && i.link != null);
|
|
|
|
const getPreviewBodyTop = () => {
|
|
const titleHeight = LiteGraph.NODE_TITLE_HEIGHT || 30;
|
|
const widgetHeight = LiteGraph.NODE_WIDGET_HEIGHT || 20;
|
|
let bodyTop = titleHeight;
|
|
for (const w of node.widgets || []) {
|
|
if (w.hidden || !Number.isFinite(w.last_y)) continue;
|
|
const size = typeof w.computeSize === "function" ? w.computeSize(node.size?.[0] || 320) : null;
|
|
const height = Number(size?.[1]) || widgetHeight;
|
|
bodyTop = Math.max(bodyTop, w.last_y + Math.max(1, height));
|
|
}
|
|
return bodyTop + 6;
|
|
};
|
|
|
|
const isPosOverPreview = (localPos) => {
|
|
if (!node.imgs || node.imgs.length === 0) return false;
|
|
if (node.flags && node.flags.collapsed) return false;
|
|
if (!node._browseFilesButton) return false;
|
|
if (isVideoInputConnected()) return false;
|
|
const bodyTop = getPreviewBodyTop();
|
|
const bodyH = (node.size?.[1] || 0) - bodyTop;
|
|
if (bodyH <= 10) return false;
|
|
return localPos[0] >= 0 && localPos[0] <= (node.size?.[0] || 0) &&
|
|
localPos[1] >= bodyTop && localPos[1] <= bodyTop + bodyH;
|
|
};
|
|
|
|
// Handle click on preview icon
|
|
const onMouseDown = node.onMouseDown;
|
|
node.onMouseDown = function(e, localPos, canvas) {
|
|
// Check if clicking on preview icon
|
|
if (node._workflowInfoBounds) {
|
|
const b = node._workflowInfoBounds;
|
|
if (localPos[0] >= b.x && localPos[0] <= b.x + b.width &&
|
|
localPos[1] >= b.y && localPos[1] <= b.y + b.height) {
|
|
if (node.hasWorkflow) {
|
|
void showExtractorWorkflowDiscoverySummary(node);
|
|
return true;
|
|
}
|
|
return onMouseDown ? onMouseDown.apply(this, arguments) : undefined;
|
|
}
|
|
}
|
|
|
|
if (node._previewIconBounds && node.imgs && node.imgs.length > 0) {
|
|
const bounds = node._previewIconBounds;
|
|
if (localPos[0] >= bounds.x && localPos[0] <= bounds.x + bounds.width &&
|
|
localPos[1] >= bounds.y && localPos[1] <= bounds.y + bounds.height) {
|
|
// Open preview modal
|
|
const imageWidget = node.widgets?.find(w => w.name === "image");
|
|
const viewType = node._sourceFolder || 'input';
|
|
if (imageWidget && imageWidget.value) {
|
|
if (node._isVideoFile) {
|
|
showVideoPreviewModal(imageWidget.value, viewType);
|
|
} else {
|
|
showImagePreviewModal(imageWidget.value, viewType);
|
|
}
|
|
}
|
|
return true; // Consume the event
|
|
}
|
|
}
|
|
|
|
// Left click on the preview thumbnail opens the file browser
|
|
// (on mouse up, so node drags don't trigger it).
|
|
if (e.button === 0 && isPosOverPreview(localPos)) {
|
|
node._previewClickCandidate = { x: localPos[0], y: localPos[1] };
|
|
} else {
|
|
node._previewClickCandidate = null;
|
|
}
|
|
|
|
return onMouseDown ? onMouseDown.apply(this, arguments) : undefined;
|
|
};
|
|
|
|
const origOnMouseUp = node.onMouseUp;
|
|
node.onMouseUp = function(e, localPos, canvas) {
|
|
const candidate = node._previewClickCandidate;
|
|
node._previewClickCandidate = null;
|
|
if (candidate && e.button === 0 && isPosOverPreview(localPos)) {
|
|
const dx = localPos[0] - candidate.x;
|
|
const dy = localPos[1] - candidate.y;
|
|
// Only treat it as a click if the pointer barely moved
|
|
// (a drag to move the node should not open the browser).
|
|
if (dx * dx + dy * dy <= 25) {
|
|
const browseButton = node._browseFilesButton;
|
|
if (browseButton && typeof browseButton.callback === "function") {
|
|
Promise.resolve(browseButton.callback()).catch((err) =>
|
|
console.error('[PromptExtractor] Error opening browser from preview:', err)
|
|
);
|
|
}
|
|
return true; // Consume the event
|
|
}
|
|
}
|
|
return origOnMouseUp ? origOnMouseUp.apply(this, arguments) : undefined;
|
|
};
|
|
|
|
// ── Ghost the file-picker UI when a VIDEO input is connected ──
|
|
// When the optional "video" input is linked, extraction reads the
|
|
// connected video directly, so the image/source/browse widgets are
|
|
// irrelevant. We hide them (LiteGraph "ghosting") while connected.
|
|
const videoInputIndex = () => (node.inputs || []).findIndex(i => i?.name === "video");
|
|
const isVideoConnected = () => {
|
|
const idx = videoInputIndex();
|
|
return idx >= 0 && node.inputs[idx]?.link != null;
|
|
};
|
|
const updateVideoConnectedUI = () => {
|
|
const connected = isVideoConnected();
|
|
const targets = [imageWidget, imagePickerWidget, sourceFolderWidget];
|
|
// Also hide the browse button (added after imagePickerWidget).
|
|
const browseBtn = node.widgets?.find(w => w?.type === "button" && w?.name && String(w.name).toLowerCase().includes("browse"));
|
|
if (browseBtn) targets.push(browseBtn);
|
|
for (const w of targets) {
|
|
if (!w) continue;
|
|
if (connected) {
|
|
if (!w._peHiddenForVideo) {
|
|
w._peHiddenForVideo = true;
|
|
w._pePrevHidden = w.hidden;
|
|
w._pePrevComputeSize = w.computeSize;
|
|
}
|
|
w.hidden = true;
|
|
w.computeSize = () => [0, -4];
|
|
if (w.inputEl) w.inputEl.style.display = "none";
|
|
} else if (w._peHiddenForVideo) {
|
|
w._peHiddenForVideo = false;
|
|
// Restore: source_folder stays hidden (it was always hidden),
|
|
// others return to their prior state.
|
|
w.hidden = w === sourceFolderWidget ? true : (w._pePrevHidden ?? false);
|
|
if (w._pePrevComputeSize) { w.computeSize = w._pePrevComputeSize; delete w._pePrevComputeSize; }
|
|
if (w.inputEl && !w.hidden) w.inputEl.style.display = "";
|
|
}
|
|
}
|
|
node.setDirtyCanvas(true, true);
|
|
node.setSize(node.computeSize());
|
|
};
|
|
|
|
const origOnConnectionsChange = node.onConnectionsChange;
|
|
node.onConnectionsChange = function (type, index, connected) {
|
|
const r = origOnConnectionsChange?.apply(this, arguments);
|
|
updateVideoConnectedUI();
|
|
return r;
|
|
};
|
|
const origOnConnectInput = node.onConnectInput;
|
|
node.onConnectInput = function (idx, type) {
|
|
const r = origOnConnectInput?.apply(this, arguments);
|
|
updateVideoConnectedUI();
|
|
return r;
|
|
};
|
|
const origOnConfigureVideo = node.onConfigure;
|
|
node.onConfigure = function (info) {
|
|
const r = origOnConfigureVideo?.apply(this, arguments);
|
|
updateVideoConnectedUI();
|
|
return r;
|
|
};
|
|
// Initial state.
|
|
setTimeout(updateVideoConnectedUI, 100);
|
|
|
|
// Install arrow-key file navigation (Left/Right steps media while
|
|
// hovering this node).
|
|
installArrowKeyNavigation();
|
|
|
|
const origOnMouseEnter = node.onMouseEnter;
|
|
node.onMouseEnter = function () {
|
|
_peHoveredNode = this;
|
|
return origOnMouseEnter ? origOnMouseEnter.apply(this, arguments) : undefined;
|
|
};
|
|
|
|
const origOnMouseLeave = node.onMouseLeave;
|
|
node.onMouseLeave = function () {
|
|
if (_peHoveredNode === this) _peHoveredNode = null;
|
|
return origOnMouseLeave ? origOnMouseLeave.apply(this, arguments) : undefined;
|
|
};
|
|
|
|
return result;
|
|
};
|
|
}
|
|
}
|
|
});
|
|
|
|
/**
|
|
* Extract metadata and update recipe indicator (without affecting display)
|
|
*/
|
|
async function extractAndUpdateMetadata(node, filename) {
|
|
if (!filename || filename === "(none)") {
|
|
node.hasWorkflow = false;
|
|
node.setDirtyCanvas(true, true);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const ext = filename.split('.').pop().toLowerCase();
|
|
const viewType = node._sourceFolder || 'input';
|
|
const fileUrl = buildPreviewUrl(filename, viewType);
|
|
|
|
// Fetch the file to extract metadata
|
|
const response = await fetch(fileUrl);
|
|
if (!response.ok) {
|
|
console.warn(`[PromptExtractor] Failed to fetch file for metadata: ${filename}`);
|
|
node.hasWorkflow = false;
|
|
node.setDirtyCanvas(true, true);
|
|
return;
|
|
}
|
|
|
|
const fileBlob = await response.blob();
|
|
let metadata = null;
|
|
|
|
// Extract based on file type
|
|
if (ext === 'png') {
|
|
metadata = await getPNGMetadata(fileBlob);
|
|
} else if (ext === 'webp') {
|
|
metadata = await getWebPMetadata(fileBlob);
|
|
} else if (['jpg', 'jpeg'].includes(ext)) {
|
|
metadata = await getJPEGMetadata(fileBlob);
|
|
} else if (ext === 'json') {
|
|
metadata = await getJSONMetadata(fileBlob);
|
|
} else if (['mp4', 'webm', 'mov', 'avi'].includes(ext)) {
|
|
console.log(`[PromptExtractor] Attempting JavaScript video metadata extraction for: ${filename}`);
|
|
metadata = await getVideoMetadata(fileBlob);
|
|
|
|
// If JavaScript parser failed, ask Python to try with ffprobe
|
|
if (metadata === null) {
|
|
console.log(`[PromptExtractor] JavaScript parser returned null, trying Python ffprobe for: ${filename}`);
|
|
metadata = await extractVideoMetadataWithPython(filename, resolveMediaSource(filename, viewType));
|
|
|
|
if (metadata) {
|
|
console.log(`[PromptExtractor] Successfully got metadata from Python for: ${filename}`);
|
|
} else {
|
|
console.log(`[PromptExtractor] Python also returned no metadata for: ${filename}`);
|
|
}
|
|
} else {
|
|
console.log(`[PromptExtractor] JavaScript successfully extracted metadata for: ${filename}`);
|
|
}
|
|
}
|
|
|
|
// Cache metadata for Python backend (only if we extracted it and Python doesn't already have it)
|
|
if (metadata !== null) {
|
|
await cacheFileMetadata(filename, metadata);
|
|
}
|
|
|
|
// Update recipe status
|
|
if (ext === 'json') {
|
|
node.hasWorkflow = !!(metadata && (metadata.workflow || (metadata.nodes && metadata.links)));
|
|
} else {
|
|
// Check for ComfyUI workflow or A1111 parameters
|
|
node.hasWorkflow = !!(metadata && (metadata.workflow || metadata.parameters));
|
|
}
|
|
|
|
// Force canvas redraw to update indicator
|
|
node.setDirtyCanvas(true, true);
|
|
app.graph.setDirtyCanvas(true, true);
|
|
|
|
// Extract full preview data for RecipeBuilder's "Update Recipe" button.
|
|
// Runs the Python parse+build pipeline on the cached metadata so WB can
|
|
// pull it without executing PromptExtractor (live-menu pattern).
|
|
if (node.hasWorkflow) {
|
|
try {
|
|
const sourceFolder = resolveMediaSource(filename, node._sourceFolder || 'input');
|
|
const previewResp = await fetch(
|
|
`/prompt-extractor/extract-preview?filename=${encodeURIComponent(filename)}&source=${encodeURIComponent(sourceFolder)}`
|
|
);
|
|
if (previewResp.ok) {
|
|
const previewData = await previewResp.json();
|
|
if (previewData.extracted) {
|
|
const normalizedExtracted = _normalizeExtractedLoraOrder(previewData.extracted);
|
|
node.properties = node.properties || {};
|
|
node.properties.pe_extracted_data = JSON.stringify(normalizedExtracted);
|
|
console.log(`[PromptExtractor] Cached extracted preview data for: ${filename}`);
|
|
}
|
|
}
|
|
} catch (previewErr) {
|
|
console.warn('[PromptExtractor] Could not cache preview data:', previewErr);
|
|
}
|
|
}
|
|
} catch (error) {
|
|
console.error("[PromptExtractor] Error extracting metadata:", error);
|
|
node.hasWorkflow = false;
|
|
node.setDirtyCanvas(true, true);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Load and display an image in the node
|
|
*/
|
|
async function loadAndDisplayImage(node, filename) {
|
|
if (!filename) {
|
|
// Show placeholder for empty
|
|
showPlaceholder(node);
|
|
return;
|
|
}
|
|
|
|
// Check file extension to determine if it's an image or video
|
|
const ext = filename.split('.').pop().toLowerCase();
|
|
const imageExtensions = ['png', 'jpg', 'jpeg', 'webp'];
|
|
const videoExtensions = ['mp4', 'webm', 'mov', 'avi'];
|
|
|
|
if (videoExtensions.includes(ext)) {
|
|
// It's a video - extract and display frame at specified position
|
|
loadVideoFrame(node, filename);
|
|
return;
|
|
}
|
|
|
|
if (!imageExtensions.includes(ext)) {
|
|
// Handle JSON files
|
|
if (ext === 'json') {
|
|
loadJSONFile(node, filename);
|
|
} else {
|
|
// Unknown file type - show placeholder
|
|
showPlaceholder(node);
|
|
}
|
|
return;
|
|
}
|
|
|
|
// It's an image - load, display, and extract metadata
|
|
loadImageFile(node, filename);
|
|
}
|
|
|
|
/**
|
|
* Load an image file, display it, and extract metadata
|
|
*/
|
|
async function loadImageFile(node, filename) {
|
|
try {
|
|
const viewType = node._sourceFolder || 'input';
|
|
const fileUrl = buildPreviewUrl(filename, viewType);
|
|
|
|
const imageBlob = await fetch(fileUrl).then(res => res.blob());
|
|
|
|
// Extract metadata from image file (PNG or JPEG/WebP)
|
|
const ext = filename.split('.').pop().toLowerCase();
|
|
let metadata = null;
|
|
|
|
if (ext === 'png') {
|
|
metadata = await getPNGMetadata(imageBlob);
|
|
} else if (ext === 'webp') {
|
|
metadata = await getWebPMetadata(imageBlob);
|
|
} else if (['jpg', 'jpeg'].includes(ext)) {
|
|
metadata = await getJPEGMetadata(imageBlob);
|
|
}
|
|
|
|
// Cache metadata (or lack thereof) for Python backend
|
|
await cacheFileMetadata(filename, metadata);
|
|
|
|
// Update recipe status flag - check for workflow or parameters
|
|
node.hasWorkflow = !!(metadata && (metadata.workflow || metadata.parameters));
|
|
|
|
// Force canvas redraw to update indicator immediately
|
|
node.setDirtyCanvas(true, true);
|
|
app.graph.setDirtyCanvas(true, true);
|
|
|
|
// Load and display the image
|
|
const img = new Image();
|
|
img.onload = () => {
|
|
node.imgs = [img];
|
|
node.imageIndex = 0;
|
|
// Track that this image is now loaded
|
|
node._loadedImageFilename = filename;
|
|
|
|
// Resize node to fit image (like Load Image does)
|
|
const targetWidth = Math.max(node.size[0], 256);
|
|
const targetHeight = Math.max(node.size[1], img.naturalHeight * (targetWidth / img.naturalWidth) + 100);
|
|
node.setSize([targetWidth, targetHeight]);
|
|
|
|
node.setDirtyCanvas(true, true);
|
|
app.graph.setDirtyCanvas(true, true);
|
|
};
|
|
|
|
img.onerror = () => {
|
|
console.error(`[PromptExtractor] Failed to load image: ${filename}`);
|
|
showPlaceholder(node);
|
|
};
|
|
|
|
// Load from input/output directory
|
|
img.src = `${fileUrl}&${Date.now()}`;
|
|
} catch (error) {
|
|
console.error("[PromptExtractor] Error loading image:", error);
|
|
showPlaceholder(node);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Load a JSON file and extract metadata
|
|
*/
|
|
async function loadJSONFile(node, filename) {
|
|
try {
|
|
const viewType = node._sourceFolder || 'input';
|
|
const fileUrl = buildPreviewUrl(filename, viewType);
|
|
|
|
const jsonBlob = await fetch(fileUrl).then(res => res.blob());
|
|
|
|
// Extract metadata from JSON file
|
|
const metadata = await getJSONMetadata(jsonBlob);
|
|
// Cache metadata (or lack thereof) for Python backend
|
|
await cacheFileMetadata(filename, metadata);
|
|
|
|
// Update recipe status flag
|
|
// Check if metadata has workflow property OR if metadata itself is a workflow (has nodes/links)
|
|
node.hasWorkflow = !!(metadata && (metadata.workflow || (metadata.nodes && metadata.links)));
|
|
// Track that this JSON is now loaded
|
|
node._loadedImageFilename = filename;
|
|
|
|
// Force canvas redraw to update indicator immediately
|
|
node.setDirtyCanvas(true, true);
|
|
app.graph.setDirtyCanvas(true, true);
|
|
|
|
// Show placeholder for JSON files (no visual preview)
|
|
showPlaceholder(node);
|
|
} catch (error) {
|
|
console.error("[PromptExtractor] Error loading JSON:", error);
|
|
showPlaceholder(node);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Load a video frame from the server-side PyAV endpoint (for H265/yuv444 videos).
|
|
*/
|
|
function loadVideoFrameFromServer(node, filename, framePosition, viewType) {
|
|
const frameSource = resolveMediaSource(filename, viewType);
|
|
const frameUrl = `/prompt-extractor/video-frame?filename=${encodeURIComponent(filename)}&source=${frameSource}&position=${framePosition}`;
|
|
const img = new Image();
|
|
img.onload = () => {
|
|
node.imgs = [img];
|
|
node.imageIndex = 0;
|
|
node._loadedImageFilename = filename;
|
|
node._loadedFramePosition = framePosition;
|
|
|
|
// Cache as base64 for Python backend
|
|
const canvas = document.createElement('canvas');
|
|
canvas.width = img.naturalWidth;
|
|
canvas.height = img.naturalHeight;
|
|
const ctx = canvas.getContext('2d');
|
|
ctx.drawImage(img, 0, 0);
|
|
const frameData = canvas.toDataURL('image/png');
|
|
cacheVideoFrame(filename, frameData, framePosition);
|
|
|
|
// Resize node to fit image
|
|
const targetWidth = Math.max(node.size[0], 256);
|
|
const targetHeight = Math.max(node.size[1], img.naturalHeight * (targetWidth / img.naturalWidth) + 100);
|
|
node.setSize([targetWidth, targetHeight]);
|
|
|
|
node.setDirtyCanvas(true, true);
|
|
app.graph.setDirtyCanvas(true, true);
|
|
};
|
|
img.onerror = () => {
|
|
console.error(`[PromptExtractor] Server-side frame extraction failed for: ${filename}`);
|
|
showPlaceholder(node);
|
|
};
|
|
img.src = frameUrl;
|
|
}
|
|
|
|
/**
|
|
* Load frame from a video file at specified position and extract metadata
|
|
*/
|
|
async function loadVideoFrame(node, filename) {
|
|
try {
|
|
// Get frame position from the widget (0.0 to 1.0)
|
|
const framePositionWidget = node.widgets?.find(w => w.name === "frame_position");
|
|
const framePosition = framePositionWidget ? framePositionWidget.value : 0.0;
|
|
const viewType = node._sourceFolder || 'input';
|
|
|
|
const videoUrl = buildPreviewUrl(filename, viewType);
|
|
|
|
// If this video is already known to be non-browser-decodable, go straight to server
|
|
if (_nonBrowserDecodableVideos.has(filename)) {
|
|
// Still fetch metadata on first load (not on scrub)
|
|
if (!node._metadataCached) {
|
|
try {
|
|
const videoBlob = await fetch(videoUrl).then(res => res.blob());
|
|
const metadata = await getVideoMetadata(videoBlob);
|
|
await cacheFileMetadata(filename, metadata);
|
|
node.hasWorkflow = !!(metadata && (metadata.workflow || metadata.parameters));
|
|
node._metadataCached = true;
|
|
node.setDirtyCanvas(true, true);
|
|
} catch (e) {
|
|
console.warn("[PromptExtractor] Metadata extraction failed:", e);
|
|
}
|
|
}
|
|
loadVideoFrameFromServer(node, filename, framePosition, viewType);
|
|
return;
|
|
}
|
|
|
|
// Fetch metadata only once per video (not on every scrub)
|
|
if (!node._metadataCached) {
|
|
try {
|
|
const videoBlob = await fetch(videoUrl).then(res => res.blob());
|
|
|
|
// Extract metadata from video file
|
|
const metadata = await getVideoMetadata(videoBlob);
|
|
// Cache metadata (or lack thereof) for Python backend
|
|
await cacheFileMetadata(filename, metadata);
|
|
node._metadataCached = true;
|
|
|
|
// Update recipe status flag - check for workflow or parameters
|
|
node.hasWorkflow = !!(metadata && (metadata.workflow || metadata.parameters));
|
|
|
|
// Force canvas redraw to update indicator immediately
|
|
node.setDirtyCanvas(true, true);
|
|
app.graph.setDirtyCanvas(true, true);
|
|
} catch (e) {
|
|
console.warn("[PromptExtractor] Metadata extraction failed:", e);
|
|
}
|
|
}
|
|
|
|
// Create a video element for frame extraction
|
|
const video = document.createElement('video');
|
|
video.crossOrigin = 'anonymous';
|
|
video.preload = 'auto';
|
|
video.muted = true;
|
|
video.playsInline = true;
|
|
video.style.cssText = 'position:fixed;top:-9999px;left:-9999px;width:1px;height:1px;opacity:0;pointer-events:none;';
|
|
|
|
const cleanupVideo = () => {
|
|
video.onloadedmetadata = null;
|
|
video.onseeked = null;
|
|
video.onerror = null;
|
|
try { video.src = ''; video.load(); } catch (e) { /* ignore */ }
|
|
if (video.parentNode) video.parentNode.removeChild(video);
|
|
};
|
|
|
|
video.onloadedmetadata = () => {
|
|
// Calculate frame time based on position (0.0 = start, 1.0 = end)
|
|
const frameTime = framePosition * Math.max(0, video.duration - 0.1);
|
|
video.currentTime = frameTime;
|
|
};
|
|
|
|
video.onseeked = () => {
|
|
// Create canvas to draw the video frame
|
|
const canvas = document.createElement('canvas');
|
|
canvas.width = video.videoWidth;
|
|
canvas.height = video.videoHeight;
|
|
const ctx = canvas.getContext('2d');
|
|
|
|
// Draw the video frame to canvas
|
|
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
|
|
|
|
// Convert canvas to image
|
|
const img = new Image();
|
|
img.onload = () => {
|
|
// Display the frame
|
|
node.imgs = [img];
|
|
node.imageIndex = 0;
|
|
// Track that this video frame is now loaded at this specific position
|
|
node._loadedImageFilename = filename;
|
|
node._loadedFramePosition = framePosition;
|
|
|
|
// Cache frame as base64 for Python backend
|
|
const frameData = canvas.toDataURL('image/png');
|
|
cacheVideoFrame(filename, frameData, framePosition);
|
|
|
|
// Resize node to fit image
|
|
const targetWidth = Math.max(node.size[0], 256);
|
|
const targetHeight = Math.max(node.size[1], img.naturalHeight * (targetWidth / img.naturalWidth) + 100);
|
|
node.setSize([targetWidth, targetHeight]);
|
|
|
|
node.setDirtyCanvas(true, true);
|
|
app.graph.setDirtyCanvas(true, true);
|
|
cleanupVideo();
|
|
};
|
|
|
|
img.onerror = () => {
|
|
console.error(`[PromptExtractor] Failed to create image from video frame at position ${framePosition.toFixed(2)}`);
|
|
cleanupVideo();
|
|
showPlaceholder(node);
|
|
};
|
|
|
|
img.src = canvas.toDataURL('image/png');
|
|
};
|
|
|
|
video.onerror = () => {
|
|
console.log(`[PromptExtractor] Browser cannot decode video, using server-side extraction: ${filename}`);
|
|
// Remember this video can't be decoded by browser - skip browser attempt on future scrubs
|
|
_nonBrowserDecodableVideos.add(filename);
|
|
cleanupVideo();
|
|
loadVideoFrameFromServer(node, filename, framePosition, viewType);
|
|
};
|
|
|
|
// Append to DOM (some browsers require this for decoding) and load
|
|
document.body.appendChild(video);
|
|
video.src = videoUrl + `&${Date.now()}`;
|
|
} catch (error) {
|
|
console.error("[PromptExtractor] Error loading video:", error);
|
|
showPlaceholder(node);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Show placeholder image for non-image files
|
|
*/
|
|
function showPlaceholder(node) {
|
|
// Clear the loaded filename and frame position since we're showing a placeholder
|
|
node._loadedImageFilename = null;
|
|
node._loadedFramePosition = null;
|
|
node._metadataCached = false;
|
|
|
|
const placeholderImg = new Image();
|
|
placeholderImg.src = PLACEHOLDER_IMAGE_PATH;
|
|
placeholderImg.onload = () => {
|
|
node.imgs = [placeholderImg];
|
|
node.imageIndex = 0;
|
|
|
|
// Resize node to fit placeholder image
|
|
const targetWidth = Math.max(node.size[0], 256);
|
|
const targetHeight = Math.max(node.size[1], placeholderImg.naturalHeight * (targetWidth / placeholderImg.naturalWidth) + 100);
|
|
node.setSize([targetWidth, targetHeight]);
|
|
|
|
node.setDirtyCanvas(true, true);
|
|
app.graph.setDirtyCanvas(true, true);
|
|
};
|
|
}
|
|
|
|
console.log("[PromptExtractor] Extension loaded");
|