/** * Vision · Liquid Prompt & OCR Studio * Unified Single / Multi / Folder Workspace with Chunked Queue Streaming & Rock-Solid Downloads */ (function () { "use strict"; // ── Default Presets ── const PROMPT_PRESETS = { prompt: "Analyze this image and write a detailed, high-quality prompt suitable for text-to-image generation (such as Midjourney, Flux, or Stable Diffusion). Describe the subject in detail, the artistic medium and style, composition, camera framing, lighting, color palette, atmosphere, and background details. Output only the prompt without conversational intro or outro.", flux: "Generate a highly descriptive prompt for Flux / Midjourney to recreate this exact image. Break down the subject, pose, attire, facial expression, artistic style, camera lens/lighting setup, depth of field, background elements, and overall mood. Output only the prompt description.", detailed: "Provide a comprehensive, dense visual description of this image. Describe all visible elements including subjects, positioning, background, textures, lighting, colors, and subtle details. Organize the description clearly.", short: "Write a concise, accurate single-sentence caption describing the main subject and action in this image.", ocr: "Extract and transcribe all visible text, letters, numbers, signs, labels, watermarks, or logos from this image. If there is no text, reply 'No text detected'.", tags: "Analyze this image and generate a comma-separated list of descriptive keywords/tags. Include subject, clothing, colors, setting, art style, mood, and camera angle. Format: tag1, tag2, tag3, ...", story: "Write an imaginative, vivid short paragraph telling the story or setting the narrative mood behind this image.", custom: "What colors, objects, and emotions are present in this image?" }; const PRESET_METAS = { prompt: { title: "Prompt (Flux / MJ)", icon: "fa-compass-drafting", desc: "Generative prompt synthesizing style, subject, camera, and lighting" }, flux: { title: "Flux.1 Detailed", icon: "fa-camera", desc: "Dense breakdown of lens, aperture, attire, and lighting for Flux" }, detailed: { title: "Dense Vision Analysis", icon: "fa-eye", desc: "Exhaustive layout, object, texture, and color examination" }, ocr: { title: "OCR Text Extraction", icon: "fa-font", desc: "Transcribe signs, documents, labels, and watermarks" }, tags: { title: "Keywords & Tags", icon: "fa-tags", desc: "Comma-separated keywords for dataset filtering and tagging" }, short: { title: "One-line Caption", icon: "fa-quote-left", desc: "Crisp single-sentence caption summarizing the subject" }, story: { title: "Atmospheric Narrative", icon: "fa-book-open", desc: "Creative short paragraph setting the mood and backstory" }, custom: { title: "Custom Instruction", icon: "fa-pen-nib", desc: "Ask any question or specify custom instructions" } }; // ── Application State ── const state = { activeTab: "studio", selectedMode: "prompt", // Unified Queue queue: [], // Array of QueueItem selectedIndex: 0, activeFilter: "all", // "all" | "pending" | "done" chunkPage: 1, chunkSize: 32, // Render 32 thumbnails per filmstrip chunk // Processing Execution isProcessing: false, stopRequested: false, processedCount: 0, batchStartTime: 0, // History historyItems: [] }; const $ = (id) => document.getElementById(id); // ── Elements Cache ── // Nav const navTabs = document.querySelectorAll(".nav-tab"); const tabPanes = document.querySelectorAll(".tab-pane"); const modelStatusCapsule = $("modelStatusCapsule"); const modelNameDisplay = $("modelNameDisplay"); const statusDot = $("statusDot"); const vramMeter = $("vramMeter"); const vramText = $("vramText"); const vramFill = $("vramFill"); const openSettingsBtn = $("openSettingsBtn"); const closeSettingsBtn = $("closeSettingsBtn"); const settingsModal = $("settingsModal"); const historyCountBadge = $("historyCountBadge"); // Intake & Dropzone const dropzoneCard = $("dropzoneCard"); const imageFileInput = $("imageFileInput"); const folderFileInput = $("folderFileInput"); const dropzoneEmpty = $("dropzoneEmpty"); const browseImagesBtn = $("browseImagesBtn"); const browseFolderBtn = $("browseFolderBtn"); const toggleServerPathBtn = $("toggleServerPathBtn"); const serverPathDrawer = $("serverPathDrawer"); const serverFolderPathInput = $("serverFolderPathInput"); const scanServerFolderBtn = $("scanServerFolderBtn"); const serverRecursiveCb = $("serverRecursiveCb"); // Single Image View const singleImageFilled = $("singleImageFilled"); const previewImg = $("previewImg"); const clearSingleImgBtn = $("clearSingleImgBtn"); const imgDimensionsPill = $("imgDimensionsPill"); const imgSizePill = $("imgSizePill"); const imgNamePill = $("imgNamePill"); const addMoreFilesBtn = $("addMoreFilesBtn"); // Multi-Image Queue View const queueContainer = $("queueContainer"); const queueTotalCount = $("queueTotalCount"); const filterAllCount = $("filterAllCount"); const filterPendingCount = $("filterPendingCount"); const filterDoneCount = $("filterDoneCount"); const queueFilterTabs = $("queueFilterTabs"); const queueAddImagesBtn = $("queueAddImagesBtn"); const clearQueueBtn = $("clearQueueBtn"); const queueFocusImg = $("queueFocusImg"); const queueFocusFilename = $("queueFocusFilename"); const queueFocusSub = $("queueFocusSub"); const queueFilmstrip = $("queueFilmstrip"); const queuePagination = $("queuePagination"); const prevPageBtn = $("prevPageBtn"); const nextPageBtn = $("nextPageBtn"); const pageInfoText = $("pageInfoText"); // Analysis Configuration const modeBtns = document.querySelectorAll(".mode-btn"); const selectedModeBadge = $("selectedModeBadge"); const instructionModeName = $("instructionModeName"); const promptInput = $("promptInput"); const resetPromptBtn = $("resetPromptBtn"); const copyPromptBtn = $("copyPromptBtn"); const clearPromptBtn = $("clearPromptBtn"); const togglePromptSizeBtn = $("togglePromptSizeBtn"); const togglePromptIcon = $("togglePromptIcon"); const promptStatsBadge = $("promptStatsBadge"); const directiveChips = document.querySelectorAll(".directive-chip"); const saveSidecarCb = $("saveSidecarCb"); const skipExistingCb = $("skipExistingCb"); const accordionToggle = $("accordionToggle"); const accordionCard = document.querySelector(".glass-accordion"); const maxTokensRange = $("maxTokensRange"); const maxTokensVal = $("maxTokensVal"); const tempRange = $("tempRange"); const tempVal = $("tempVal"); const topPRange = $("topPRange"); const topPVal = $("topPVal"); // CTA const mainActionBtn = $("mainActionBtn"); const btnSpinner = $("btnSpinner"); const btnText = $("btnText"); const shortcutKbd = $("shortcutKbd"); const pauseQueueBtn = $("pauseQueueBtn"); // Output & Results const outputCardTitle = $("outputCardTitle"); const singleOutputActions = $("singleOutputActions"); const queueOutputActions = $("queueOutputActions"); const copyResultBtn = $("copyResultBtn"); const downloadTxtBtn = $("downloadTxtBtn"); const downloadJsonBtn = $("downloadJsonBtn"); const downloadAllZipBtn = $("downloadAllZipBtn"); const exportCsvBtn = $("exportCsvBtn"); const exportJsonBtn = $("exportJsonBtn"); const copyAllPromptsBtn = $("copyAllPromptsBtn"); const queueProgressBlock = $("queueProgressBlock"); const queueProgressStatus = $("queueProgressStatus"); const queueProgressNumbers = $("queueProgressNumbers"); const queueProgressBarFill = $("queueProgressBarFill"); const queueProgressCurrentFile = $("queueProgressCurrentFile"); const queueTimeEst = $("queueTimeEst"); const outputPlaceholder = $("outputPlaceholder"); const outputResult = $("outputResult"); const resultText = $("resultText"); const chipTime = $("chipTime"); const chipTokens = $("chipTokens"); const chipMode = $("chipMode"); const chipDim = $("chipDim"); const queueResultsStream = $("queueResultsStream"); const streamSubText = $("streamSubText"); const streamItemsList = $("streamItemsList"); // Presets & History const presetsCardsGrid = $("presetsCardsGrid"); const historyGrid = $("historyGrid"); const historyEmpty = $("historyEmpty"); const clearHistoryBtn = $("clearHistoryBtn"); // Hardware Modal const gpuDeviceName = $("gpuDeviceName"); const gpuVramUsage = $("gpuVramUsage"); const gpuVramPercent = $("gpuVramPercent"); const modelIdInput = $("modelIdInput"); const quantSelect = $("quantSelect"); const unloadModelBtn = $("unloadModelBtn"); const applyModelBtn = $("applyModelBtn"); // ── Toast Notifications ── function showToast(message, type = "info", duration = 3200) { const container = $("toastContainer"); const toast = document.createElement("div"); toast.className = `toast ${type}`; let icon = "fa-circle-info"; if (type === "success") icon = "fa-circle-check"; if (type === "error") icon = "fa-triangle-exclamation"; toast.innerHTML = `${message}`; container.appendChild(toast); setTimeout(() => { toast.style.opacity = "0"; toast.style.transform = "translateY(10px)"; setTimeout(() => toast.remove(), 300); }, duration); } // ── Reliable Client-Side Blob Download ── function downloadBlob(content, filename, mimeType = "text/plain;charset=utf-8") { try { const blob = content instanceof Blob ? content : new Blob([content], { type: mimeType }); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(url), 2000); showToast(`Downloaded ${filename}`, "success"); } catch (err) { console.error("Download failed:", err); showToast(`Download failed: ${err.message}`, "error"); } } // ── Tab Switching ── function switchTab(tabName) { state.activeTab = tabName; navTabs.forEach((tab) => tab.classList.toggle("active", tab.dataset.tab === tabName)); tabPanes.forEach((pane) => pane.classList.toggle("active", pane.id === `pane-${tabName}`)); if (tabName === "history") loadHistory(); else if (tabName === "presets") renderPresetsLibrary(); } navTabs.forEach((tab) => tab.addEventListener("click", () => switchTab(tab.dataset.tab))); // ── Unified Intake & Queue Management ── // Helper: Naturally sort queue items sequentially by file name function sortQueueByFilename() { state.queue.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: "base" }) ); } // Helper: Resize image to max 720px right when uploaded if greater than 720px function prepareAndResizeImage(file, maxDimension = 720) { return new Promise((resolve) => { const validExts = [".jpg", ".jpeg", ".png", ".webp", ".bmp", ".tiff", ".tif", ".avif"]; const ext = "." + file.name.split(".").pop().toLowerCase(); if (!validExts.includes(ext) && !file.type.startsWith("image/")) { resolve(null); return; } const img = new Image(); const objectUrl = URL.createObjectURL(file); img.onload = () => { const origW = img.naturalWidth || img.width; const origH = img.naturalHeight || img.height; // If within 720 on both sides, keep original file untouched if (origW <= maxDimension && origH <= maxDimension) { resolve({ file: file, previewUrl: objectUrl, width: origW, height: origH, name: file.name, size: file.size, resized: false }); return; } // If greater than 720, downscale preserving aspect ratio let targetW = origW; let targetH = origH; if (origW >= origH) { targetW = maxDimension; targetH = Math.max(1, Math.round((origH * maxDimension) / origW)); } else { targetH = maxDimension; targetW = Math.max(1, Math.round((origW * maxDimension) / origH)); } const canvas = document.createElement("canvas"); canvas.width = targetW; canvas.height = targetH; const ctx = canvas.getContext("2d", { alpha: false }); ctx.imageSmoothingEnabled = true; ctx.imageSmoothingQuality = "high"; ctx.drawImage(img, 0, 0, targetW, targetH); let mimeType = file.type; if (!mimeType || mimeType === "" || mimeType.includes("bmp") || mimeType.includes("tiff")) { mimeType = "image/jpeg"; } canvas.toBlob( (blob) => { URL.revokeObjectURL(objectUrl); if (!blob) { resolve({ file: file, previewUrl: URL.createObjectURL(file), width: origW, height: origH, name: file.name, size: file.size, resized: false }); return; } const resizedFile = new File([blob], file.name, { type: blob.type || mimeType, lastModified: Date.now() }); const previewUrl = URL.createObjectURL(resizedFile); resolve({ file: resizedFile, previewUrl: previewUrl, width: targetW, height: targetH, name: file.name, size: resizedFile.size, resized: true, origW: origW, origH: origH }); }, mimeType, 0.92 ); }; img.onerror = () => { URL.revokeObjectURL(objectUrl); resolve(null); }; img.src = objectUrl; }); } async function addFilesToQueue(files) { if (!files || files.length === 0) return; const totalFiles = files.length; if (totalFiles > 12) { showToast(`Uploading & optimizing ${totalFiles} images (auto-resizing >720px)...`, "info"); } let addedCount = 0; let resizedCount = 0; // Process in concurrent batches of 6 for high performance & responsive UI const batchSize = 6; for (let i = 0; i < files.length; i += batchSize) { const batch = files.slice(i, i + batchSize); const preparedBatch = await Promise.all(batch.map((f) => prepareAndResizeImage(f, 720))); for (const prep of preparedBatch) { if (!prep) continue; if (prep.resized) resizedCount++; state.queue.push({ id: "q_" + Date.now() + "_" + Math.random().toString(36).slice(2, 7), file: prep.file, serverPath: null, name: prep.name, size: prep.size, previewUrl: prep.previewUrl, status: "pending", // "pending" | "processing" | "done" | "failed" result: "", elapsed: 0, width: prep.width, height: prep.height, resized: prep.resized, error: "" }); addedCount++; } } if (addedCount > 0) { // Sort queue sequentially by filename sortQueueByFilename(); if (resizedCount > 0) { showToast(`Loaded ${addedCount} images (${resizedCount} resized to max 720px)`, "info"); } else { showToast(`Loaded ${addedCount} image(s)`, "info"); } updateQueueUI(); } } window.addFilesToStudio = addFilesToQueue; window.getStudioQueue = () => state.queue; function addServerFilesToQueue(filesList) { let addedCount = 0; for (const f of filesList) { state.queue.push({ id: "q_" + Date.now() + "_" + Math.random().toString(36).slice(2, 7), file: null, serverPath: f.path, name: f.name, size: f.size || 0, previewUrl: "", status: "pending", result: "", elapsed: 0, width: 0, height: 0, resized: false, error: "" }); addedCount++; } if (addedCount > 0) { // Sort queue sequentially by filename sortQueueByFilename(); showToast(`Loaded ${addedCount} image(s) from server path`, "info"); updateQueueUI(); } } function clearQueue() { state.queue.forEach((item) => { if (item.previewUrl) URL.revokeObjectURL(item.previewUrl); }); state.queue = []; state.selectedIndex = 0; state.isProcessing = false; state.stopRequested = false; state.processedCount = 0; updateQueueUI(); } // Update the entire Studio UI based on queue state function updateQueueUI() { const total = state.queue.length; const doneCount = state.queue.filter((x) => x.status === "done").length; const pendingCount = state.queue.filter((x) => x.status === "pending" || x.status === "processing").length; queueTotalCount.textContent = total; filterAllCount.textContent = total; filterDoneCount.textContent = doneCount; filterPendingCount.textContent = pendingCount; if (total === 0) { // State: Empty Intake dropzoneEmpty.style.display = "flex"; singleImageFilled.style.display = "none"; queueContainer.style.display = "none"; singleOutputActions.style.display = "flex"; queueOutputActions.style.display = "none"; outputPlaceholder.style.display = "flex"; outputResult.style.display = "none"; queueResultsStream.style.display = "none"; queueProgressBlock.style.display = "none"; outputCardTitle.textContent = "Generated Output"; btnText.textContent = "Generate Prompt / Text"; shortcutKbd.style.display = "inline-block"; mainActionBtn.disabled = true; } else if (total === 1) { // State: Single Focus Mode dropzoneEmpty.style.display = "none"; singleImageFilled.style.display = "flex"; queueContainer.style.display = "none"; const item = state.queue[0]; previewImg.src = item.previewUrl || (item.serverPath ? "uploads/" + item.name : ""); imgNamePill.innerHTML = ` ${item.name}`; imgSizePill.innerHTML = ` ${(item.size / 1024).toFixed(1)} KB`; imgDimensionsPill.innerHTML = item.width ? ` ${item.width} × ${item.height}` : ` Image Loaded`; singleOutputActions.style.display = "flex"; queueOutputActions.style.display = "none"; queueResultsStream.style.display = "none"; queueProgressBlock.style.display = "none"; outputCardTitle.textContent = "Generated Output"; if (item.status === "done") { displaySingleResult(item); } else { outputPlaceholder.style.display = "flex"; outputResult.style.display = "none"; } btnText.textContent = "Generate Prompt / Text"; shortcutKbd.style.display = "inline-block"; mainActionBtn.disabled = false; } else { // State: Multi-Image Queue Mode dropzoneEmpty.style.display = "none"; singleImageFilled.style.display = "none"; queueContainer.style.display = "flex"; singleOutputActions.style.display = "none"; queueOutputActions.style.display = "flex"; queueResultsStream.style.display = "flex"; outputCardTitle.textContent = `Queue Results (${doneCount} / ${total} Done)`; btnText.textContent = state.isProcessing ? "Processing Queue..." : `Process Queue (${total} Images)`; shortcutKbd.style.display = "none"; mainActionBtn.disabled = state.isProcessing; renderQueueFilmstrip(); renderSelectedQueueFocus(); renderQueueStreamResults(); } } function renderSelectedQueueFocus() { if (state.queue.length === 0) return; const idx = Math.min(state.selectedIndex, state.queue.length - 1); const item = state.queue[idx]; if (!item) return; queueFocusFilename.textContent = item.name; queueFocusSub.textContent = `Status: ${item.status.toUpperCase()} ${item.elapsed ? `· ${item.elapsed}s` : ""} · Size: ${(item.size / 1024).toFixed(1)} KB`; if (item.previewUrl) { queueFocusImg.src = item.previewUrl; queueFocusImg.style.display = "block"; } else { queueFocusImg.style.display = "none"; } // If this item is done, show its text in focus output if (item.status === "done") { displaySingleResult(item); } else if (item.status === "failed") { outputPlaceholder.style.display = "none"; outputResult.style.display = "flex"; resultText.textContent = `Error: ${item.error}`; } } function renderQueueFilmstrip() { // Filter items let visibleItems = state.queue; if (state.activeFilter === "pending") { visibleItems = state.queue.filter((x) => x.status === "pending" || x.status === "processing"); } else if (state.activeFilter === "done") { visibleItems = state.queue.filter((x) => x.status === "done"); } // Chunk pagination const totalChunks = Math.max(1, Math.ceil(visibleItems.length / state.chunkSize)); if (state.chunkPage > totalChunks) state.chunkPage = totalChunks; const startIdx = (state.chunkPage - 1) * state.chunkSize; const endIdx = startIdx + state.chunkSize; const pageItems = visibleItems.slice(startIdx, endIdx); if (totalChunks > 1) { queuePagination.style.display = "flex"; pageInfoText.textContent = `Chunk ${state.chunkPage} of ${totalChunks} (${visibleItems.length} total)`; } else { queuePagination.style.display = "none"; } queueFilmstrip.innerHTML = pageItems .map((item) => { const globalIdx = state.queue.indexOf(item); const isSelected = globalIdx === state.selectedIndex; const statusBadge = item.status === "done" ? `
` : item.status === "processing" ? `
` : item.status === "failed" ? `
` : ""; return `
${item.previewUrl ? `Thumb` : `
`} ${statusBadge}
`; }) .join(""); } window.selectQueueIndex = function (idx) { state.selectedIndex = idx; renderSelectedQueueFocus(); renderQueueFilmstrip(); // Also highlight in stream list const streamCards = document.querySelectorAll(".stream-card"); streamCards.forEach((c) => c.classList.toggle("selected", parseInt(c.dataset.index, 10) === idx)); }; function renderQueueStreamResults() { const processedItems = state.queue.filter((x) => x.status === "done" || x.status === "failed"); streamSubText.textContent = `${processedItems.length} of ${state.queue.length} processed`; if (processedItems.length === 0) { streamItemsList.innerHTML = `
No items processed yet. Click 'Process Queue' to begin.
`; return; } streamItemsList.innerHTML = processedItems .map((item) => { const globalIdx = state.queue.indexOf(item); const isSelected = globalIdx === state.selectedIndex; const isSuccess = item.status === "done"; const snippet = (item.result || item.error || "").replace(/\n/g, " "); return `
${item.previewUrl ? `
thumb
` : ""}
${escapeHtml(item.name)}
${item.status} ${item.elapsed ? `${item.elapsed}s` : ""} ${isSuccess ? ` ` : ""}
${escapeHtml(snippet)}
`; }) .join(""); } // ── Intake Triggers & Drag-Drop ── browseImagesBtn.addEventListener("click", () => imageFileInput.click()); browseFolderBtn.addEventListener("click", () => folderFileInput.click()); queueAddImagesBtn.addEventListener("click", () => imageFileInput.click()); addMoreFilesBtn.addEventListener("click", () => imageFileInput.click()); imageFileInput.addEventListener("change", (e) => { if (e.target.files && e.target.files.length > 0) { addFilesToQueue(Array.from(e.target.files)); imageFileInput.value = ""; } }); folderFileInput.addEventListener("change", (e) => { if (e.target.files && e.target.files.length > 0) { addFilesToQueue(Array.from(e.target.files)); folderFileInput.value = ""; } }); clearSingleImgBtn.addEventListener("click", clearQueue); clearQueueBtn.addEventListener("click", () => { if (state.queue.length > 5 && !confirm("Clear all items from queue?")) return; clearQueue(); }); // Server Path Drawer Toggle toggleServerPathBtn.addEventListener("click", () => { const isHidden = serverPathDrawer.style.display === "none"; serverPathDrawer.style.display = isHidden ? "block" : "none"; }); scanServerFolderBtn.addEventListener("click", async () => { const path = serverFolderPathInput.value.trim(); if (!path) { showToast("Please enter an absolute server directory path", "error"); return; } scanServerFolderBtn.disabled = true; try { const resp = await fetch(`api/scan-folder?path=${encodeURIComponent(path)}&recursive=${serverRecursiveCb.checked}`); if (!resp.ok) { const err = await resp.json().catch(() => ({})); throw new Error(err.error || `HTTP ${resp.status}`); } const data = await resp.json(); if (!data.files || data.files.length === 0) { showToast("No supported image files found in directory", "info"); } else { addServerFilesToQueue(data.files); serverPathDrawer.style.display = "none"; } } catch (err) { showToast(`Scan error: ${err.message}`, "error"); } finally { scanServerFolderBtn.disabled = false; } }); // Advanced Drag-and-Drop (Handles single files, multiple files, and folder directories!) dropzoneCard.addEventListener("dragover", (e) => { e.preventDefault(); dropzoneCard.classList.add("drag-over"); }); dropzoneCard.addEventListener("dragleave", () => { dropzoneCard.classList.remove("drag-over"); }); dropzoneCard.addEventListener("drop", async (e) => { e.preventDefault(); dropzoneCard.classList.remove("drag-over"); const items = e.dataTransfer.items; if (!items) { if (e.dataTransfer.files) addFilesToQueue(Array.from(e.dataTransfer.files)); return; } const filesToLoad = []; const traverseEntry = async (entry) => { if (entry.isFile) { return new Promise((resolve) => { entry.file((file) => { filesToLoad.push(file); resolve(); }); }); } else if (entry.isDirectory) { const reader = entry.createReader(); return new Promise((resolve) => { reader.readEntries(async (entries) => { for (const child of entries) { await traverseEntry(child); } resolve(); }); }); } }; for (const item of items) { const entry = item.webkitGetAsEntry ? item.webkitGetAsEntry() : null; if (entry) { await traverseEntry(entry); } else if (item.kind === "file") { const f = item.getAsFile(); if (f) filesToLoad.push(f); } } if (filesToLoad.length > 0) { addFilesToQueue(filesToLoad); } }); // Clipboard Paste (Ctrl+V) window.addEventListener("paste", (e) => { if (state.activeTab !== "studio") return; const items = (e.clipboardData || e.originalEvent.clipboardData).items; for (const item of items) { if (item.kind === "file" && item.type.startsWith("image/")) { const blob = item.getAsFile(); if (blob) { addFilesToQueue([blob]); showToast("Image pasted into Studio", "info"); } break; } } }); // Queue Filter Tabs queueFilterTabs.addEventListener("click", (e) => { const btn = e.target.closest(".filter-tab"); if (!btn) return; document.querySelectorAll(".filter-tab").forEach((b) => b.classList.remove("active")); btn.classList.add("active"); state.activeFilter = btn.dataset.filter; state.chunkPage = 1; renderQueueFilmstrip(); }); // Queue Pagination prevPageBtn.addEventListener("click", () => { if (state.chunkPage > 1) { state.chunkPage--; renderQueueFilmstrip(); } }); nextPageBtn.addEventListener("click", () => { state.chunkPage++; renderQueueFilmstrip(); }); // ── Mode & Parameter Tuning ── function updatePromptStats() { if (!promptStatsBadge || !promptInput) return; const text = promptInput.value || ""; const charCount = text.length; // Approximation: ~4 characters per token const tokenEst = Math.ceil(charCount / 4); promptStatsBadge.textContent = `${charCount.toLocaleString()} chars • ~${tokenEst.toLocaleString()} tokens`; } function setMode(modeKey) { state.selectedMode = modeKey; modeBtns.forEach((btn) => btn.classList.toggle("active", btn.dataset.mode === modeKey)); const meta = PRESET_METAS[modeKey]; if (meta) { if (selectedModeBadge) selectedModeBadge.textContent = meta.title; if (instructionModeName) instructionModeName.textContent = meta.title; } if (PROMPT_PRESETS[modeKey]) { promptInput.value = PROMPT_PRESETS[modeKey]; } updatePromptStats(); } modeBtns.forEach((btn) => btn.addEventListener("click", () => setMode(btn.dataset.mode))); if (promptInput) { promptInput.addEventListener("input", updatePromptStats); } if (resetPromptBtn) { resetPromptBtn.addEventListener("click", () => { promptInput.value = PROMPT_PRESETS[state.selectedMode] || ""; updatePromptStats(); showToast("Prompt reset to default", "info"); }); } if (copyPromptBtn) { copyPromptBtn.addEventListener("click", () => { const val = promptInput ? promptInput.value.trim() : ""; if (!val) { showToast("Instruction box is empty", "warning"); return; } navigator.clipboard.writeText(val).then(() => { showToast("Instruction copied to clipboard", "success"); const origHtml = copyPromptBtn.innerHTML; copyPromptBtn.innerHTML = ` Copied!`; setTimeout(() => { copyPromptBtn.innerHTML = origHtml; }, 1800); }); }); } if (clearPromptBtn) { clearPromptBtn.addEventListener("click", () => { if (promptInput) { promptInput.value = ""; promptInput.focus(); updatePromptStats(); showToast("Instruction cleared", "info"); } }); } if (togglePromptSizeBtn && promptInput) { togglePromptSizeBtn.addEventListener("click", () => { promptInput.classList.toggle("expanded"); const isExp = promptInput.classList.contains("expanded"); if (togglePromptIcon) { togglePromptIcon.className = isExp ? "fa-solid fa-down-left-and-up-right-to-center" : "fa-solid fa-up-right-and-down-left-from-center"; } togglePromptSizeBtn.title = isExp ? "Compact editor height" : "Expand editor height"; }); } if (directiveChips && directiveChips.length > 0) { directiveChips.forEach((chip) => { chip.addEventListener("click", () => { const directive = chip.dataset.directive; if (!directive || !promptInput) return; const current = promptInput.value.trim(); if (!current) { promptInput.value = directive; } else if (!current.includes(directive)) { const sep = /[.?!]$/.test(current) ? " " : ". "; promptInput.value = current + sep + directive; } promptInput.focus(); updatePromptStats(); showToast("Modifier added to directives", "success"); }); }); } maxTokensRange.addEventListener("input", (e) => (maxTokensVal.textContent = e.target.value)); tempRange.addEventListener("input", (e) => (tempVal.textContent = parseFloat(e.target.value).toFixed(2))); topPRange.addEventListener("input", (e) => (topPVal.textContent = parseFloat(e.target.value).toFixed(2))); accordionToggle.addEventListener("click", () => accordionCard.classList.toggle("open")); // ── Execution Engine (Chunked & Seamless) ── async function executeQueue() { if (state.queue.length === 0) return; if (state.isProcessing) return; state.isProcessing = true; state.stopRequested = false; state.batchStartTime = Date.now(); mainActionBtn.disabled = true; btnSpinner.style.display = "inline-block"; pauseQueueBtn.style.display = "inline-flex"; queueProgressBlock.style.display = "flex"; const mode = state.selectedMode; const promptText = promptInput.value.trim(); const maxTokens = parseInt(maxTokensRange.value, 10); const temp = parseFloat(tempRange.value); const topP = parseFloat(topPRange.value); const saveSidecar = saveSidecarCb.checked; const skipExisting = skipExistingCb.checked; // Ensure queue is strictly sorted sequentially by filename before processing sortQueueByFilename(); updateQueueUI(); const total = state.queue.length; // Process queue items sequentially so user sees immediate results per item for (let i = 0; i < total; i++) { if (state.stopRequested) { showToast("Queue stopped by user", "info"); break; } const item = state.queue[i]; // Auto-skip check if (skipExisting && item.status === "done" && item.result) { continue; } item.status = "processing"; state.selectedIndex = i; // Update Progress bar const percent = Math.round(((i + 1) / total) * 100); queueProgressStatus.textContent = `Processing image ${i + 1} of ${total}...`; queueProgressNumbers.textContent = `${i + 1} / ${total} (${percent}%)`; queueProgressBarFill.style.width = `${percent}%`; queueProgressCurrentFile.textContent = item.name; // Estimate time remaining const elapsedTotal = (Date.now() - state.batchStartTime) / 1000; const avgPerItem = elapsedTotal / (i + 1); const remainingSec = Math.round(avgPerItem * (total - (i + 1))); queueTimeEst.textContent = `· Est. remaining: ${remainingSec}s`; updateQueueUI(); // Run inference try { let resp; if (item.file) { const fd = new FormData(); fd.append("image", item.file); fd.append("mode", mode); fd.append("custom_prompt", promptText); fd.append("max_new_tokens", maxTokens); fd.append("temperature", temp); fd.append("top_p", topP); fd.append("save_sidecar", saveSidecar); resp = await fetch("api/generate", { method: "POST", body: fd }); } else if (item.serverPath) { resp = await fetch("api/generate", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ image_path: item.serverPath, mode: mode, custom_prompt: promptText, max_new_tokens: maxTokens, temperature: temp, top_p: topP, save_sidecar: saveSidecar }) }); } if (!resp.ok) { const err = await resp.json().catch(() => ({})); throw new Error(err.error || `HTTP ${resp.status}`); } const data = await resp.json(); item.status = "done"; item.result = data.result || ""; item.elapsed = data.elapsed_seconds || 0; item.width = data.width || 0; item.height = data.height || 0; // Live update focus preview & stream list immediately! updateQueueUI(); } catch (err) { console.error(`Error processing ${item.name}:`, err); item.status = "failed"; item.error = err.message; updateQueueUI(); } } // Completion state.isProcessing = false; mainActionBtn.disabled = false; btnSpinner.style.display = "none"; pauseQueueBtn.style.display = "none"; const totalBatchTime = ((Date.now() - state.batchStartTime) / 1000).toFixed(1); queueProgressStatus.textContent = `Queue finished in ${totalBatchTime}s`; showToast(`Processed queue in ${totalBatchTime}s!`, "success"); loadHistoryCount(); updateQueueUI(); } mainActionBtn.addEventListener("click", executeQueue); pauseQueueBtn.addEventListener("click", () => { state.stopRequested = true; pauseQueueBtn.disabled = true; showToast("Stopping queue...", "info"); }); // Keyboard shortcut Ctrl+Enter window.addEventListener("keydown", (e) => { if ((e.ctrlKey || e.metaKey) && e.key === "Enter") { if (state.activeTab === "studio" && !state.isProcessing) { e.preventDefault(); executeQueue(); } } }); function displaySingleResult(item) { outputPlaceholder.style.display = "none"; outputResult.style.display = "flex"; resultText.textContent = item.result || "(Empty result)"; chipTime.innerHTML = ` ${item.elapsed ? item.elapsed + "s" : "--"}`; const estTokens = Math.round((item.result || "").length / 4); chipTokens.innerHTML = ` ~${estTokens} tokens`; chipMode.innerHTML = ` ${state.selectedMode}`; chipDim.innerHTML = ` ${item.width || "--"} × ${item.height || "--"}`; } // ── FIXED DOWNLOAD ACTIONS ── // 1. Single Copy copyResultBtn.addEventListener("click", () => { const item = state.queue[state.selectedIndex]; const text = item ? item.result : ""; if (!text) return; navigator.clipboard.writeText(text).then(() => showToast("Copied to clipboard!", "success")); }); // 2. Single .txt Sidecar window.downloadSingleTxt = function (itemId) { const item = state.queue.find((x) => x.id === itemId) || state.queue[state.selectedIndex]; if (!item || !item.result) return; const stem = item.name.replace(/\.[^/.]+$/, ""); downloadBlob(item.result, `${stem}.txt`, "text/plain;charset=utf-8"); }; downloadTxtBtn.addEventListener("click", () => downloadSingleTxt()); // 3. Single JSON (Strictly image_file and prompt only) window.downloadSingleJson = function (itemId) { const item = state.queue.find((x) => x.id === itemId) || state.queue[state.selectedIndex]; if (!item || !item.result) return; const stem = item.name.replace(/\.[^/.]+$/, ""); const cleanJson = { image_file: item.name, prompt: item.result }; downloadBlob(JSON.stringify(cleanJson, null, 2), `${stem}.json`, "application/json"); }; downloadJsonBtn.addEventListener("click", () => downloadSingleJson()); // 4. Batch ZIP of All Sidecars (Direct Rock-solid Server Zip Generation) downloadAllZipBtn.addEventListener("click", async () => { const doneItems = state.queue.filter((x) => x.status === "done" && x.result); if (doneItems.length === 0) { showToast("No processed results to download yet", "error"); return; } downloadAllZipBtn.disabled = true; showToast("Generating ZIP archive...", "info"); try { const payload = { job_name: "dataset_sidecars", items: doneItems.map((it) => ({ filename: it.name, text: it.result, status: it.status, elapsed: it.elapsed })) }; const resp = await fetch("api/export-zip", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) }); if (!resp.ok) throw new Error(`HTTP ${resp.status}`); const blob = await resp.blob(); downloadBlob(blob, `vision_dataset_sidecars_${Date.now()}.zip`, "application/zip"); } catch (err) { console.error("ZIP download failed:", err); showToast(`ZIP export error: ${err.message}`, "error"); } finally { downloadAllZipBtn.disabled = false; } }); // 5. Batch CSV Export exportCsvBtn.addEventListener("click", () => { const doneItems = state.queue.filter((x) => x.status === "done" || x.status === "failed"); if (doneItems.length === 0) { showToast("No processed results to export", "error"); return; } let csv = "Filename,Status,Prompt/Caption/OCR,Elapsed (s),Width,Height\n"; for (const it of doneItems) { const escapedText = (it.result || it.error || "").replace(/"/g, '""'); csv += `"${it.name}","${it.status}","${escapedText}",${it.elapsed || 0},${it.width || 0},${it.height || 0}\n`; } downloadBlob(csv, `batch_results_${Date.now()}.csv`, "text/csv;charset=utf-8"); }); // 6. Batch JSON Export (Strictly image_file and prompt only) exportJsonBtn.addEventListener("click", () => { const doneItems = state.queue.filter((x) => x.status === "done" && x.result); if (doneItems.length === 0) { showToast("No processed results to export", "error"); return; } const cleanJsonList = doneItems.map((it) => ({ image_file: it.name, prompt: it.result })); downloadBlob(JSON.stringify(cleanJsonList, null, 2), `dataset_prompts_${Date.now()}.json`, "application/json"); }); // 7. Copy All Prompts copyAllPromptsBtn.addEventListener("click", () => { const doneItems = state.queue.filter((x) => x.status === "done" && x.result); if (doneItems.length === 0) return; const allText = doneItems.map((x) => `--- ${x.name} ---\n${x.result}\n`).join("\n"); navigator.clipboard.writeText(allText).then(() => showToast(`Copied ${doneItems.length} prompts to clipboard!`, "success")); }); // ── Presets Library Tab ── function renderPresetsLibrary() { presetsCardsGrid.innerHTML = Object.entries(PROMPT_PRESETS) .map(([key, prompt]) => { const meta = PRESET_METAS[key] || { title: key, icon: "fa-cube", desc: "" }; return `
${meta.title}
${meta.desc}
${escapeHtml(prompt)}
`; }) .join(""); } window.applyPresetToStudio = function (key) { setMode(key); switchTab("studio"); showToast(`Preset '${key}' loaded in Studio`, "info"); }; // ── History Tab ── async function loadHistory() { try { const resp = await fetch("api/history"); if (!resp.ok) return; const data = await resp.json(); state.historyItems = data.items || []; historyCountBadge.textContent = state.historyItems.length; if (state.historyItems.length === 0) { historyGrid.innerHTML = `
No previous generations found.
`; return; } historyGrid.innerHTML = state.historyItems .map((item) => { const timeAgo = formatTimeAgo(new Date(item.timestamp)); const snippet = (item.result || "").slice(0, 240); let imgUrl = item.image_url ? (item.image_url.startsWith("/") ? item.image_url.replace(/^\/+/, "") : item.image_url) : ""; return `
${imgUrl ? `
Thumbnail
` : ""}
${item.mode} ${timeAgo} · ${item.elapsed_seconds}s
${escapeHtml(snippet)}...
`; }) .join(""); } catch (err) { console.warn("Failed to load history:", err); } } window.loadHistoryToStudio = function (id) { const item = state.historyItems.find((x) => x.id === id); if (!item) return; clearQueue(); state.queue.push({ id: "hist_" + item.id, file: null, serverPath: null, name: item.image_filename || "history_image.png", size: 0, previewUrl: item.image_url ? (item.image_url.startsWith("/") ? item.image_url.replace(/^\/+/, "") : item.image_url) : "", status: "done", result: item.result || "", elapsed: item.elapsed_seconds || 0, width: item.width || 0, height: item.height || 0, error: "" }); setMode(item.mode || "prompt"); switchTab("studio"); updateQueueUI(); showToast("Loaded history item into Studio", "info"); }; async function loadHistoryCount() { try { const resp = await fetch("api/history"); if (!resp.ok) return; const data = await resp.json(); historyCountBadge.textContent = (data.items || []).length; } catch (_) {} } clearHistoryBtn.addEventListener("click", async () => { if (!confirm("Clear all generation history?")) return; try { await fetch("api/history", { method: "DELETE" }); showToast("History cleared", "info"); loadHistory(); } catch (err) { showToast("Failed to clear history", "error"); } }); // ── Telemetry & Settings ── async function updateTelemetry() { try { const resp = await fetch("api/model/status"); if (!resp.ok) return; const data = await resp.json(); if (data.loaded) { statusDot.className = "status-dot online"; modelNameDisplay.textContent = `${data.model_id.split("/").pop()} · ${data.quantization}`; } else { statusDot.className = "status-dot standby"; modelNameDisplay.textContent = "Standby (No model in VRAM)"; } if (data.vram && data.vram.cuda_available) { vramText.textContent = `${data.vram.used_gb} / ${data.vram.total_gb} GB`; vramFill.style.width = `${data.vram.percent_used}%`; gpuDeviceName.textContent = data.vram.device_name || "NVIDIA GPU"; gpuVramUsage.textContent = `${data.vram.used_gb} / ${data.vram.total_gb} GB`; gpuVramPercent.textContent = `${data.vram.percent_used}%`; } else { vramText.textContent = "CPU Mode"; vramFill.style.width = "0%"; gpuDeviceName.textContent = "CPU"; gpuVramUsage.textContent = "N/A"; gpuVramPercent.textContent = "0%"; } } catch (_) {} } openSettingsBtn.addEventListener("click", () => { updateTelemetry(); settingsModal.style.display = "grid"; }); modelStatusCapsule.addEventListener("click", () => { updateTelemetry(); settingsModal.style.display = "grid"; }); closeSettingsBtn.addEventListener("click", () => { settingsModal.style.display = "none"; }); settingsModal.addEventListener("click", (e) => { if (e.target === settingsModal) settingsModal.style.display = "none"; }); applyModelBtn.addEventListener("click", async () => { const modelId = modelIdInput.value.trim(); const quant = quantSelect.value; applyModelBtn.disabled = true; showToast("Loading model into VRAM... Please wait.", "info", 6000); try { const resp = await fetch("api/model/load", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ model_name: modelId, quantization: quant }) }); if (!resp.ok) throw new Error(`HTTP ${resp.status}`); showToast("Model loaded successfully!", "success"); updateTelemetry(); settingsModal.style.display = "none"; } catch (err) { showToast(`Failed to load model: ${err.message}`, "error"); } finally { applyModelBtn.disabled = false; } }); unloadModelBtn.addEventListener("click", async () => { unloadModelBtn.disabled = true; try { await fetch("api/model/unload", { method: "POST" }); showToast("Model unloaded from VRAM", "info"); updateTelemetry(); settingsModal.style.display = "none"; } catch (err) { showToast("Failed to unload model", "error"); } finally { unloadModelBtn.disabled = false; } }); // ── Helper Utilities ── function escapeHtml(str) { if (!str) return ""; return String(str) .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) .replace(/'/g, "'"); } function escapeJsString(str) { if (!str) return ""; return str.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n"); } function formatTimeAgo(date) { const seconds = Math.floor((new Date() - date) / 1000); if (seconds < 60) return "Just now"; const minutes = Math.floor(seconds / 60); if (minutes < 60) return `${minutes}m ago`; const hours = Math.floor(minutes / 60); if (hours < 24) return `${hours}h ago`; return `${Math.floor(hours / 24)}d ago`; } // ── Initialisation ── setMode("prompt"); updateQueueUI(); updateTelemetry(); loadHistoryCount(); setInterval(updateTelemetry, 5000); })();