859 lines
35 KiB
JavaScript
859 lines
35 KiB
JavaScript
/**
|
||
* Vision · Liquid Prompt & OCR Studio
|
||
* Vanilla ES6 JavaScript application logic
|
||
*/
|
||
|
||
(function () {
|
||
"use strict";
|
||
|
||
// ── Default Presets Map ──
|
||
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 / Midjourney)", icon: "fa-compass-drafting", desc: "Generative prompt synthesizing style, subject, camera, and lighting" },
|
||
flux: { title: "Flux.1 Photographic", 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",
|
||
currentImageFile: null,
|
||
currentImageDimensions: { width: 0, height: 0 },
|
||
currentResultText: "",
|
||
currentResultMeta: null,
|
||
batchSource: "upload", // "upload" | "folder"
|
||
batchFiles: [],
|
||
activeBatchJobId: null,
|
||
batchPollTimer: null,
|
||
historyItems: []
|
||
};
|
||
|
||
// ── DOM Elements ──
|
||
const $ = (id) => document.getElementById(id);
|
||
|
||
// Nav elements
|
||
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");
|
||
|
||
// Studio Elements
|
||
const dropzoneCard = $("dropzoneCard");
|
||
const imageFileInput = $("imageFileInput");
|
||
const browseBtn = $("browseBtn");
|
||
const dropzoneEmpty = $("dropzoneEmpty");
|
||
const dropzoneFilled = $("dropzoneFilled");
|
||
const previewImg = $("previewImg");
|
||
const removeImgBtn = $("removeImgBtn");
|
||
const imgDimensionsPill = $("imgDimensionsPill");
|
||
const imgSizePill = $("imgSizePill");
|
||
const imgNamePill = $("imgNamePill");
|
||
const modeBtns = document.querySelectorAll(".mode-btn");
|
||
const selectedModeBadge = $("selectedModeBadge");
|
||
const promptInput = $("promptInput");
|
||
const resetPromptBtn = $("resetPromptBtn");
|
||
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");
|
||
const generateBtn = $("generateBtn");
|
||
const btnSpinner = $("btnSpinner");
|
||
|
||
// Output Elements
|
||
const outputPlaceholder = $("outputPlaceholder");
|
||
const outputResult = $("outputResult");
|
||
const resultText = $("resultText");
|
||
const chipTime = $("chipTime");
|
||
const chipTokens = $("chipTokens");
|
||
const chipMode = $("chipMode");
|
||
const chipDim = $("chipDim");
|
||
const copyResultBtn = $("copyResultBtn");
|
||
const downloadTxtBtn = $("downloadTxtBtn");
|
||
const downloadJsonBtn = $("downloadJsonBtn");
|
||
|
||
// Batch Elements
|
||
const batchSourceUploadBtn = $("batchSourceUploadBtn");
|
||
const batchSourceFolderBtn = $("batchSourceFolderBtn");
|
||
const batchSourceUploadSection = $("batchSourceUploadSection");
|
||
const batchSourceFolderSection = $("batchSourceFolderSection");
|
||
const batchDropzone = $("batchDropzone");
|
||
const batchFilesInput = $("batchFilesInput");
|
||
const batchBrowseBtn = $("batchBrowseBtn");
|
||
const batchFilesCount = $("batchFilesCount");
|
||
const batchFolderPathInput = $("batchFolderPathInput");
|
||
const batchRecursiveCb = $("batchRecursiveCb");
|
||
const batchModeSelect = $("batchModeSelect");
|
||
const batchCustomPromptItem = $("batchCustomPromptItem");
|
||
const batchCustomPromptInput = $("batchCustomPromptInput");
|
||
const batchSidecarCb = $("batchSidecarCb");
|
||
const batchSkipExistingCb = $("batchSkipExistingCb");
|
||
const startBatchBtn = $("startBatchBtn");
|
||
const progressBlock = $("progressBlock");
|
||
const progressStatusText = $("progressStatusText");
|
||
const progressNumbers = $("progressNumbers");
|
||
const progressBarFill = $("progressBarFill");
|
||
const progressCurrentFile = $("progressCurrentFile");
|
||
const batchExportBtns = $("batchExportBtns");
|
||
const exportZipBtn = $("exportZipBtn");
|
||
const exportJsonBtn = $("exportJsonBtn");
|
||
const exportCsvBtn = $("exportCsvBtn");
|
||
const batchTableBody = $("batchTableBody");
|
||
|
||
// Presets & History Elements
|
||
const presetsCardsGrid = $("presetsCardsGrid");
|
||
const historyGrid = $("historyGrid");
|
||
const historyEmpty = $("historyEmpty");
|
||
const clearHistoryBtn = $("clearHistoryBtn");
|
||
|
||
// Modal Elements
|
||
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 = 3000) {
|
||
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 = `<i class="fa-solid ${icon}"></i><span>${message}</span>`;
|
||
container.appendChild(toast);
|
||
|
||
setTimeout(() => {
|
||
toast.style.opacity = "0";
|
||
toast.style.transform = "translateY(10px)";
|
||
setTimeout(() => toast.remove(), 300);
|
||
}, duration);
|
||
}
|
||
|
||
// ── 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));
|
||
});
|
||
|
||
// ── Image Handling (Studio) ──
|
||
function handleSelectedFile(file) {
|
||
if (!file || !file.type.startsWith("image/")) {
|
||
showToast("Please select a valid image file", "error");
|
||
return;
|
||
}
|
||
|
||
state.currentImageFile = file;
|
||
|
||
// Preview
|
||
const reader = new FileReader();
|
||
reader.onload = (e) => {
|
||
const img = new Image();
|
||
img.onload = () => {
|
||
state.currentImageDimensions = { width: img.width, height: img.height };
|
||
imgDimensionsPill.innerHTML = `<i class="fa-regular fa-image"></i> ${img.width} × ${img.height}`;
|
||
imgSizePill.innerHTML = `<i class="fa-solid fa-weight-hanging"></i> ${(file.size / 1024).toFixed(1)} KB`;
|
||
imgNamePill.innerHTML = `<i class="fa-solid fa-tag"></i> ${file.name}`;
|
||
|
||
previewImg.src = e.target.result;
|
||
dropzoneEmpty.style.display = "none";
|
||
dropzoneFilled.style.display = "flex";
|
||
};
|
||
img.src = e.target.result;
|
||
};
|
||
reader.readAsDataURL(file);
|
||
}
|
||
|
||
function clearStudioImage() {
|
||
state.currentImageFile = null;
|
||
state.currentImageDimensions = { width: 0, height: 0 };
|
||
previewImg.src = "";
|
||
imageFileInput.value = "";
|
||
dropzoneEmpty.style.display = "flex";
|
||
dropzoneFilled.style.display = "none";
|
||
}
|
||
|
||
dropzoneCard.addEventListener("click", (e) => {
|
||
if (e.target.closest("#removeImgBtn") || e.target.closest("#dropzoneFilled")) return;
|
||
imageFileInput.click();
|
||
});
|
||
|
||
browseBtn.addEventListener("click", (e) => {
|
||
e.stopPropagation();
|
||
imageFileInput.click();
|
||
});
|
||
|
||
imageFileInput.addEventListener("change", (e) => {
|
||
if (e.target.files && e.target.files[0]) {
|
||
handleSelectedFile(e.target.files[0]);
|
||
}
|
||
});
|
||
|
||
removeImgBtn.addEventListener("click", (e) => {
|
||
e.stopPropagation();
|
||
clearStudioImage();
|
||
});
|
||
|
||
// Drag & Drop
|
||
dropzoneCard.addEventListener("dragover", (e) => {
|
||
e.preventDefault();
|
||
dropzoneCard.classList.add("drag-over");
|
||
});
|
||
|
||
dropzoneCard.addEventListener("dragleave", () => {
|
||
dropzoneCard.classList.remove("drag-over");
|
||
});
|
||
|
||
dropzoneCard.addEventListener("drop", (e) => {
|
||
e.preventDefault();
|
||
dropzoneCard.classList.remove("drag-over");
|
||
if (e.dataTransfer.files && e.dataTransfer.files[0]) {
|
||
handleSelectedFile(e.dataTransfer.files[0]);
|
||
}
|
||
});
|
||
|
||
// Paste Image from Clipboard (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();
|
||
handleSelectedFile(blob);
|
||
showToast("Image pasted from clipboard", "info");
|
||
break;
|
||
}
|
||
}
|
||
});
|
||
|
||
// ── Mode Selection ──
|
||
function setMode(modeKey) {
|
||
state.selectedMode = modeKey;
|
||
modeBtns.forEach((btn) => {
|
||
btn.classList.toggle("active", btn.dataset.mode === modeKey);
|
||
});
|
||
|
||
const meta = PRESET_METAS[modeKey];
|
||
if (meta) {
|
||
selectedModeBadge.textContent = meta.title;
|
||
}
|
||
|
||
// Auto-populate instruction text
|
||
if (PROMPT_PRESETS[modeKey]) {
|
||
promptInput.value = PROMPT_PRESETS[modeKey];
|
||
}
|
||
}
|
||
|
||
modeBtns.forEach((btn) => {
|
||
btn.addEventListener("click", () => setMode(btn.dataset.mode));
|
||
});
|
||
|
||
resetPromptBtn.addEventListener("click", () => {
|
||
promptInput.value = PROMPT_PRESETS[state.selectedMode] || "";
|
||
showToast("Prompt reset to default", "info");
|
||
});
|
||
|
||
// ── Sliders & Accordion ──
|
||
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");
|
||
});
|
||
|
||
// ── Single Generation ──
|
||
async function triggerGeneration() {
|
||
if (!state.currentImageFile) {
|
||
showToast("Please upload or paste an image first", "error");
|
||
return;
|
||
}
|
||
|
||
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);
|
||
|
||
generateBtn.disabled = true;
|
||
btnSpinner.style.display = "inline-block";
|
||
|
||
const formData = new FormData();
|
||
formData.append("image", state.currentImageFile);
|
||
formData.append("mode", mode);
|
||
formData.append("custom_prompt", promptText);
|
||
formData.append("max_new_tokens", maxTokens);
|
||
formData.append("temperature", temp);
|
||
formData.append("top_p", topP);
|
||
|
||
try {
|
||
const resp = await fetch("/api/generate", {
|
||
method: "POST",
|
||
body: formData,
|
||
});
|
||
|
||
if (!resp.ok) {
|
||
const err = await resp.json().catch(() => ({}));
|
||
throw new Error(err.error || `HTTP error ${resp.status}`);
|
||
}
|
||
|
||
const data = await resp.json();
|
||
displayGenerationResult(data);
|
||
showToast("Inference completed successfully!", "success");
|
||
loadHistoryCount();
|
||
} catch (err) {
|
||
console.error("Generation failed:", err);
|
||
showToast(`Error: ${err.message}`, "error", 5000);
|
||
} finally {
|
||
generateBtn.disabled = false;
|
||
btnSpinner.style.display = "none";
|
||
}
|
||
}
|
||
|
||
function displayGenerationResult(data) {
|
||
state.currentResultText = data.result || "";
|
||
state.currentResultMeta = data;
|
||
|
||
outputPlaceholder.style.display = "none";
|
||
outputResult.style.display = "flex";
|
||
|
||
resultText.textContent = data.result || "(Empty result)";
|
||
chipTime.innerHTML = `<i class="fa-solid fa-stopwatch"></i> ${data.elapsed_seconds}s`;
|
||
|
||
// Estimate token count (~4 chars per token)
|
||
const estTokens = Math.round((data.result || "").length / 4);
|
||
chipTokens.innerHTML = `<i class="fa-solid fa-bars-staggered"></i> ~${estTokens} tokens`;
|
||
chipMode.innerHTML = `<i class="fa-solid fa-layer-group"></i> ${data.mode}`;
|
||
chipDim.innerHTML = `<i class="fa-solid fa-vector-square"></i> ${data.width || "--"} × ${data.height || "--"}`;
|
||
}
|
||
|
||
generateBtn.addEventListener("click", triggerGeneration);
|
||
|
||
// Shortcut: Ctrl+Enter
|
||
window.addEventListener("keydown", (e) => {
|
||
if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
|
||
if (state.activeTab === "studio") {
|
||
e.preventDefault();
|
||
triggerGeneration();
|
||
}
|
||
}
|
||
});
|
||
|
||
// Copy to Clipboard
|
||
copyResultBtn.addEventListener("click", () => {
|
||
if (!state.currentResultText) return;
|
||
navigator.clipboard.writeText(state.currentResultText).then(() => {
|
||
showToast("Copied to clipboard!", "success");
|
||
});
|
||
});
|
||
|
||
// Download as .txt
|
||
downloadTxtBtn.addEventListener("click", () => {
|
||
if (!state.currentResultText) return;
|
||
const blob = new Blob([state.currentResultText], { type: "text/plain;charset=utf-8" });
|
||
const url = URL.createObjectURL(blob);
|
||
const a = document.createElement("a");
|
||
a.href = url;
|
||
const baseName = (state.currentImageFile ? state.currentImageFile.name.replace(/\.[^/.]+$/, "") : "prompt_result");
|
||
a.download = `${baseName}.txt`;
|
||
a.click();
|
||
URL.revokeObjectURL(url);
|
||
showToast("Sidecar .txt downloaded", "info");
|
||
});
|
||
|
||
// Download as JSON
|
||
downloadJsonBtn.addEventListener("click", () => {
|
||
if (!state.currentResultMeta) return;
|
||
const blob = new Blob([JSON.stringify(state.currentResultMeta, null, 2)], { type: "application/json" });
|
||
const url = URL.createObjectURL(blob);
|
||
const a = document.createElement("a");
|
||
a.href = url;
|
||
a.download = `vision_output_${Date.now()}.json`;
|
||
a.click();
|
||
URL.revokeObjectURL(url);
|
||
showToast("JSON downloaded", "info");
|
||
});
|
||
|
||
// ── Batch Processing ──
|
||
batchSourceUploadBtn.addEventListener("click", () => {
|
||
state.batchSource = "upload";
|
||
batchSourceUploadBtn.classList.add("active");
|
||
batchSourceFolderBtn.classList.remove("active");
|
||
batchSourceUploadSection.style.display = "block";
|
||
batchSourceFolderSection.style.display = "none";
|
||
});
|
||
|
||
batchSourceFolderBtn.addEventListener("click", () => {
|
||
state.batchSource = "folder";
|
||
batchSourceFolderBtn.classList.add("active");
|
||
batchSourceUploadBtn.classList.remove("active");
|
||
batchSourceUploadSection.style.display = "none";
|
||
batchSourceFolderSection.style.display = "block";
|
||
});
|
||
|
||
batchDropzone.addEventListener("click", () => batchFilesInput.click());
|
||
batchBrowseBtn.addEventListener("click", (e) => {
|
||
e.stopPropagation();
|
||
batchFilesInput.click();
|
||
});
|
||
|
||
batchFilesInput.addEventListener("change", (e) => {
|
||
state.batchFiles = Array.from(e.target.files || []);
|
||
batchFilesCount.textContent = `${state.batchFiles.length} file(s) selected`;
|
||
});
|
||
|
||
batchDropzone.addEventListener("dragover", (e) => {
|
||
e.preventDefault();
|
||
batchDropzone.style.borderColor = "var(--accent)";
|
||
});
|
||
|
||
batchDropzone.addEventListener("dragleave", () => {
|
||
batchDropzone.style.borderColor = "";
|
||
});
|
||
|
||
batchDropzone.addEventListener("drop", (e) => {
|
||
e.preventDefault();
|
||
batchDropzone.style.borderColor = "";
|
||
if (e.dataTransfer.files) {
|
||
state.batchFiles = Array.from(e.dataTransfer.files);
|
||
batchFilesCount.textContent = `${state.batchFiles.length} file(s) selected`;
|
||
}
|
||
});
|
||
|
||
batchModeSelect.addEventListener("change", (e) => {
|
||
batchCustomPromptItem.style.display = e.target.value === "custom" ? "block" : "none";
|
||
});
|
||
|
||
async function startBatchJob() {
|
||
const mode = batchModeSelect.value;
|
||
const customPrompt = batchCustomPromptInput.value.trim();
|
||
const sidecar = batchSidecarCb.checked;
|
||
const skipExisting = batchSkipExistingCb.checked;
|
||
|
||
startBatchBtn.disabled = true;
|
||
|
||
try {
|
||
let resp;
|
||
if (state.batchSource === "upload") {
|
||
if (state.batchFiles.length === 0) {
|
||
showToast("Please select files to process", "error");
|
||
startBatchBtn.disabled = false;
|
||
return;
|
||
}
|
||
|
||
const fd = new FormData();
|
||
state.batchFiles.forEach((file) => fd.append("images", file));
|
||
fd.append("mode", mode);
|
||
fd.append("custom_prompt", customPrompt);
|
||
fd.append("sidecar", sidecar);
|
||
fd.append("skip_existing", skipExisting);
|
||
|
||
resp = await fetch("/api/batch", { method: "POST", body: fd });
|
||
} else {
|
||
const folderPath = batchFolderPathInput.value.trim();
|
||
if (!folderPath) {
|
||
showToast("Please enter a valid folder path", "error");
|
||
startBatchBtn.disabled = false;
|
||
return;
|
||
}
|
||
|
||
resp = await fetch("/api/batch", {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({
|
||
folder_path: folderPath,
|
||
mode,
|
||
custom_prompt: customPrompt,
|
||
recursive: batchRecursiveCb.checked,
|
||
sidecar,
|
||
skip_existing: skipExisting,
|
||
}),
|
||
});
|
||
}
|
||
|
||
if (!resp.ok) {
|
||
const err = await resp.json().catch(() => ({}));
|
||
throw new Error(err.error || `HTTP ${resp.status}`);
|
||
}
|
||
|
||
const resData = await resp.json();
|
||
state.activeBatchJobId = resData.job_id;
|
||
showToast("Batch processing started!", "success");
|
||
|
||
// Setup export links
|
||
exportZipBtn.href = `/api/batch/${resData.job_id}/export-zip`;
|
||
exportJsonBtn.href = `/api/batch/${resData.job_id}/export-json`;
|
||
exportCsvBtn.href = `/api/batch/${resData.job_id}/export-csv`;
|
||
|
||
progressBlock.style.display = "flex";
|
||
batchExportBtns.style.display = "none";
|
||
batchTableBody.innerHTML = `<tr><td colspan="6" style="text-align:center;padding:24px;">Initialising batch queue...</td></tr>`;
|
||
|
||
// Start polling
|
||
if (state.batchPollTimer) clearInterval(state.batchPollTimer);
|
||
state.batchPollTimer = setInterval(pollBatchStatus, 1200);
|
||
} catch (err) {
|
||
console.error("Batch launch failed:", err);
|
||
showToast(`Batch error: ${err.message}`, "error", 5000);
|
||
startBatchBtn.disabled = false;
|
||
}
|
||
}
|
||
|
||
async function pollBatchStatus() {
|
||
if (!state.activeBatchJobId) return;
|
||
|
||
try {
|
||
const resp = await fetch(`/api/batch/${state.activeBatchJobId}/status`);
|
||
if (!resp.ok) return;
|
||
|
||
const job = await resp.json();
|
||
|
||
// Update Progress bar
|
||
progressStatusText.textContent = job.status === "completed" ? "Batch Completed" : "Processing batch...";
|
||
progressNumbers.textContent = `${job.current_index} / ${job.total} (${job.percent}%)`;
|
||
progressBarFill.style.width = `${job.percent}%`;
|
||
progressCurrentFile.textContent = job.current_file || "--";
|
||
|
||
// Update table
|
||
renderBatchResultsTable(job.results || []);
|
||
|
||
if (job.status === "completed" || job.status === "failed") {
|
||
clearInterval(state.batchPollTimer);
|
||
state.batchPollTimer = null;
|
||
startBatchBtn.disabled = false;
|
||
batchExportBtns.style.display = "flex";
|
||
showToast(`Batch finished in ${job.elapsed_seconds}s (${job.processed} processed, ${job.skipped} skipped)`, "success");
|
||
}
|
||
} catch (err) {
|
||
console.warn("Poll status error:", err);
|
||
}
|
||
}
|
||
|
||
function renderBatchResultsTable(items) {
|
||
if (!items || items.length === 0) {
|
||
batchTableBody.innerHTML = `<tr class="empty-row"><td colspan="6">No files processed yet...</td></tr>`;
|
||
return;
|
||
}
|
||
|
||
batchTableBody.innerHTML = items
|
||
.map((item, idx) => {
|
||
const statusClass = item.status === "success" ? "success" : item.status === "skipped" ? "skipped" : "failed";
|
||
const snippet = (item.result || item.error || "").replace(/\n/g, " ");
|
||
const timeStr = item.elapsed_seconds ? `${item.elapsed_seconds}s` : "--";
|
||
|
||
return `
|
||
<tr>
|
||
<td>${idx + 1}</td>
|
||
<td><strong>${escapeHtml(item.filename || item.file)}</strong></td>
|
||
<td><span class="table-status-pill ${statusClass}">${item.status}</span></td>
|
||
<td><div class="table-text-snippet" title="${escapeHtml(item.result || item.error || '')}">${escapeHtml(snippet)}</div></td>
|
||
<td>${timeStr}</td>
|
||
<td>
|
||
<button class="action-btn" onclick="navigator.clipboard.writeText('${escapeJsString(item.result || '')}');" title="Copy text">
|
||
<i class="fa-regular fa-copy"></i>
|
||
</button>
|
||
</td>
|
||
</tr>
|
||
`;
|
||
})
|
||
.join("");
|
||
}
|
||
|
||
startBatchBtn.addEventListener("click", startBatchJob);
|
||
|
||
// ── Presets Tab ──
|
||
function renderPresetsLibrary() {
|
||
presetsCardsGrid.innerHTML = Object.entries(PROMPT_PRESETS)
|
||
.map(([key, prompt]) => {
|
||
const meta = PRESET_METAS[key] || { title: key, icon: "fa-cube", desc: "" };
|
||
return `
|
||
<div class="preset-card">
|
||
<div>
|
||
<div class="preset-header">
|
||
<div class="preset-icon"><i class="fa-solid ${meta.icon}"></i></div>
|
||
<div>
|
||
<div class="preset-title">${meta.title}</div>
|
||
<div style="font-size:11px;color:var(--text-tertiary);">${meta.desc}</div>
|
||
</div>
|
||
</div>
|
||
<div class="preset-instruction" style="margin-top:14px;">${escapeHtml(prompt)}</div>
|
||
</div>
|
||
<button class="primary-btn" style="padding:10px 14px;font-size:12px;" onclick="applyPresetToStudio('${key}')">
|
||
<i class="fa-solid fa-arrow-right"></i>
|
||
<span>Use in Studio</span>
|
||
</button>
|
||
</div>
|
||
`;
|
||
})
|
||
.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 = `
|
||
<div class="history-empty">
|
||
<i class="fa-regular fa-clock"></i>
|
||
<div>No previous generations found.</div>
|
||
</div>
|
||
`;
|
||
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 || "";
|
||
if (imgUrl.startsWith("/")) {
|
||
imgUrl = imgUrl.replace(/^\/+/, "");
|
||
}
|
||
|
||
return `
|
||
<div class="history-card">
|
||
${imgUrl ? `
|
||
<div class="history-thumb-wrap">
|
||
<img src="${imgUrl}" class="history-thumb" alt="Thumbnail" loading="lazy" onerror="this.style.display='none';">
|
||
</div>
|
||
` : ""}
|
||
<div class="history-body">
|
||
<div class="history-meta-row">
|
||
<span class="card-badge">${item.mode}</span>
|
||
<span>${timeAgo} · ${item.elapsed_seconds}s</span>
|
||
</div>
|
||
<div class="history-text">${escapeHtml(snippet)}...</div>
|
||
<div style="display:flex;justify-content:flex-end;gap:8px;">
|
||
<button class="action-btn" onclick="loadHistoryToStudio('${item.id}')" title="Load into Studio">
|
||
<i class="fa-solid fa-arrow-up-right-from-square"></i> Open
|
||
</button>
|
||
<button class="action-btn" onclick="navigator.clipboard.writeText('${escapeJsString(item.result || '')}');showToast('Copied to clipboard','success');" title="Copy">
|
||
<i class="fa-regular fa-copy"></i> Copy
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
`;
|
||
})
|
||
.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;
|
||
setMode(item.mode || "prompt");
|
||
displayGenerationResult(item);
|
||
if (item.image_url) {
|
||
let imgUrl = item.image_url.startsWith("/") ? item.image_url.replace(/^\/+/, "") : item.image_url;
|
||
previewImg.src = imgUrl;
|
||
dropzoneEmpty.style.display = "none";
|
||
dropzoneFilled.style.display = "flex";
|
||
imgDimensionsPill.innerHTML = `<i class="fa-regular fa-image"></i> ${item.width || "--"} × ${item.height || "--"}`;
|
||
imgNamePill.innerHTML = `<i class="fa-solid fa-tag"></i> ${item.image_filename || "history_image.png"}`;
|
||
}
|
||
switchTab("studio");
|
||
showToast("History item loaded 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");
|
||
}
|
||
});
|
||
|
||
// ── VRAM & Model Telemetry ──
|
||
async function updateTelemetry() {
|
||
try {
|
||
const resp = await fetch("/api/model/status");
|
||
if (!resp.ok) return;
|
||
const data = await resp.json();
|
||
|
||
// Status capsule
|
||
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)";
|
||
}
|
||
|
||
// VRAM meter
|
||
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 (_) {}
|
||
}
|
||
|
||
// Modal Events
|
||
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... This may take a few seconds.", "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, """)
|
||
.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");
|
||
updateTelemetry();
|
||
loadHistoryCount();
|
||
setInterval(updateTelemetry, 5000);
|
||
})();
|