Spaces:
Running
Running
File size: 13,755 Bytes
011f1af | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | import { MODEL_OPTIONS, getModelOption, defaultInstruction, normalizeOptions } from './models.js';
const $ = id => document.getElementById(id);
const ui = Object.fromEntries([
'image-input', 'model-select', 'model-note', 'detail-select', 'detail-note', 'instruction-controls',
'instruction', 'max-tokens', 'token-value', 'run-button', 'stop-button', 'status', 'runtime-badge',
'progress-wrap', 'progress-bar', 'sample-grid', 'shuffle-examples', 'preview-image', 'preview-wrap',
'image-source', 'summary', 'run-meta', 'meta-model', 'meta-image', 'meta-runtime',
'copy-caption', 'download-caption', 'history-body', 'clear-history', 'download-history',
].map(id => [id, $(id)]));
const state = { image: null, running: false, loadingImage: false, selection: 0, request: 0, history: [], result: null, examples: [], visible: [] };
let worker = null;
let watchdog = null;
function badge(text, mode = '') {
ui['runtime-badge'].textContent = text;
ui['runtime-badge'].className = `badge ${mode}`.trim();
}
function refreshControls() {
const busy = state.running || state.loadingImage;
for (const id of ['image-input', 'model-select', 'max-tokens', 'instruction']) ui[id].disabled = busy;
ui['detail-select'].disabled = busy || ui['model-select'].value === 'vit';
ui['shuffle-examples'].disabled = busy || !state.examples.length;
ui['run-button'].disabled = busy || !state.image;
ui['stop-button'].hidden = !state.running;
ui['copy-caption'].disabled = busy || !state.result;
ui['download-caption'].disabled = busy || !state.result;
for (const button of ui['sample-grid'].querySelectorAll('button')) button.disabled = busy;
}
function resetResult() {
state.result = null;
ui.summary.textContent = 'No caption yet.';
ui['run-meta'].hidden = true;
refreshControls();
}
function modelControls(resetPrompt = true) {
const option = getModelOption(ui['model-select'].value);
ui['model-note'].textContent = option.note;
ui['detail-note'].textContent = option.detailNote;
if (option.key === 'vit') ui['detail-select'].value = 'short';
ui['instruction-controls'].hidden = option.key !== 'smol';
if (resetPrompt) ui.instruction.value = defaultInstruction(ui['detail-select'].value);
refreshControls();
}
function downloadFile(filename, content, type) {
const url = URL.createObjectURL(new Blob([content], { type }));
const link = document.createElement('a');
link.href = url; link.download = filename; document.body.append(link); link.click(); link.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
function renderHistory() {
ui['clear-history'].disabled = !state.history.length;
ui['download-history'].disabled = !state.history.length;
ui['history-body'].replaceChildren();
if (!state.history.length) {
const row = document.createElement('tr'); row.className = 'empty-row';
const cell = document.createElement('td'); cell.colSpan = 6; cell.textContent = 'Run two models on the same image to start a comparison.';
row.append(cell); ui['history-body'].append(row); return;
}
for (const item of state.history) {
const row = document.createElement('tr');
for (const value of [item.run, item.image.label, item.model, item.caption, item.config.instruction ? 'Instruction' : item.config.style, `${item.generationSeconds.toFixed(1)}s`]) {
const cell = document.createElement('td'); cell.textContent = value; row.append(cell);
}
ui['history-body'].append(row);
}
}
async function prepareImage(blob) {
if (!['image/png', 'image/jpeg', 'image/webp'].includes(blob.type)) throw new Error('Choose a PNG, JPEG, or WebP image.');
if (blob.size > 12 * 1024 * 1024) throw new Error('Choose an image smaller than 12 MB.');
const url = URL.createObjectURL(blob);
try {
const image = new Image(); image.src = url; await image.decode();
if (!image.naturalWidth || !image.naturalHeight || image.naturalWidth * image.naturalHeight > 40000000) throw new Error('Choose an image with fewer than 40 million pixels.');
const scale = Math.min(1, 1600 / Math.max(image.naturalWidth, image.naturalHeight));
const canvas = document.createElement('canvas');
canvas.width = Math.max(1, Math.round(image.naturalWidth * scale));
canvas.height = Math.max(1, Math.round(image.naturalHeight * scale));
const context = canvas.getContext('2d');
context.fillStyle = '#fff'; context.fillRect(0, 0, canvas.width, canvas.height);
context.drawImage(image, 0, 0, canvas.width, canvas.height);
return { dataUrl: canvas.toDataURL('image/jpeg', .94), width: canvas.width, height: canvas.height, originalWidth: image.naturalWidth, originalHeight: image.naturalHeight };
} finally { URL.revokeObjectURL(url); }
}
async function selectImage(loadBlob, label, source = null, key = null) {
if (state.running) return;
const selection = ++state.selection;
state.loadingImage = true; refreshControls();
ui.status.textContent = `Loading ${label}…`; badge('Loading image', 'running');
try {
const prepared = await prepareImage(await loadBlob());
if (selection !== state.selection) return;
state.image = { ...prepared, label, source, key };
ui['preview-image'].src = prepared.dataUrl;
ui['preview-image'].alt = `${label} selected for captioning`;
ui['preview-wrap'].classList.remove('empty');
ui['image-source'].replaceChildren(); ui['image-source'].hidden = !source;
if (source) {
const link = document.createElement('a'); link.href = source; link.target = '_blank'; link.rel = 'noopener noreferrer';
link.textContent = 'Example source · CC0'; ui['image-source'].append(link);
}
for (const card of ui['sample-grid'].children) {
const selected = card.dataset.src === key;
card.classList.toggle('selected', selected); card.setAttribute('aria-pressed', String(selected));
}
resetResult(); badge('Image ready'); ui.status.textContent = `${label} is ready. Click Run AI Captioning.`;
} catch (error) {
if (selection !== state.selection) return;
ui.status.textContent = `${error.message} ${state.image ? 'Your previous image remains selected.' : 'Try another image.'}`;
badge('Image error', 'error');
} finally {
if (selection === state.selection) { state.loadingImage = false; refreshControls(); }
}
}
function renderExamples(initial = false) {
const available = initial ? state.examples : state.examples.filter(item => !state.visible.includes(item.src));
const shuffled = [...available];
if (!initial) for (let i = shuffled.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]; }
const selection = shuffled.slice(0, 4);
state.visible = selection.map(item => item.src);
ui['sample-grid'].replaceChildren();
for (const example of selection) {
const button = document.createElement('button'); button.type = 'button'; button.className = 'sample-card'; button.dataset.src = example.src;
button.title = `Use sample: ${example.label}`; button.setAttribute('aria-pressed', String(state.image?.key === example.src));
button.classList.toggle('selected', state.image?.key === example.src);
const image = document.createElement('img'); image.src = example.src; image.alt = example.label;
const label = document.createElement('span'); label.textContent = example.label;
const detail = document.createElement('small'); detail.textContent = 'CC0 teaching image';
button.append(image, label, detail);
button.addEventListener('click', () => {
ui['image-input'].value = '';
selectImage(async () => {
const response = await fetch(example.src);
if (!response.ok) throw new Error('This example could not be loaded.');
return response.blob();
}, example.label, example.source, example.src);
});
ui['sample-grid'].append(button);
}
refreshControls();
}
function finishRun() {
clearTimeout(watchdog); watchdog = null;
state.running = false; ui['progress-wrap'].hidden = true; refreshControls();
}
function stopWorker() {
worker?.terminate(); worker = null;
}
function failRun(message) {
stopWorker(); finishRun(); badge('Run failed', 'error');
ui.status.textContent = `Could not generate a caption. ${message} Check the connection or retry with ViT-GPT2.`;
}
function getWorker() {
if (worker) return worker;
worker = new Worker(new URL('./caption-worker.js', import.meta.url), { type: 'module' });
worker.onerror = event => failRun(event.message || 'The inference worker stopped.');
worker.onmessageerror = () => failRun('The model result could not be read.');
worker.onmessage = ({ data }) => {
if (data.id !== state.request || !state.running) return;
if (data.type === 'progress') {
const progress = data.progress;
if (progress.phase === 'library') ui.status.textContent = 'Loading the captioning library…';
if (progress.phase === 'download' && progress.file) {
ui.status.textContent = `Loading model file: ${progress.file}. The first run can take several minutes.`;
if (Number.isFinite(progress.progress)) ui['progress-bar'].style.width = `${Math.max(0, Math.min(100, progress.progress))}%`;
}
if (progress.phase === 'generate') {
badge('Generating', 'running'); ui['progress-wrap'].hidden = true;
ui.status.textContent = 'Generating the caption. You can stop this run if it takes too long.';
}
} else if (data.type === 'error') failRun(data.message);
else if (data.type === 'result') {
const { dataUrl, ...imageInfo } = state.image;
const result = { ...data.result, image: imageInfo, run: state.request, timestamp: new Date().toISOString() };
state.result = result; state.history.unshift(result); state.history = state.history.slice(0, 12);
ui.summary.textContent = result.caption;
ui['meta-model'].textContent = result.model; ui['meta-image'].textContent = imageInfo.label;
ui['meta-runtime'].textContent = `${result.generationSeconds.toFixed(1)}s`; ui['run-meta'].hidden = false;
renderHistory(); finishRun(); badge('Caption ready', 'ready');
ui.status.textContent = `Done. Loading: ${result.loadSeconds.toFixed(1)}s · generation: ${result.generationSeconds.toFixed(1)}s. Check the sentence against the image.`;
}
};
return worker;
}
ui['run-button'].addEventListener('click', () => {
if (!state.image || state.running || state.loadingImage) return;
let options;
try { options = normalizeOptions({ modelKey: ui['model-select'].value, style: ui['detail-select'].value, maxTokens: ui['max-tokens'].value, instruction: ui.instruction.value }); }
catch (error) { ui.status.textContent = error.message; badge('Check settings', 'error'); return; }
state.running = true; state.request++; resetResult(); refreshControls();
badge('Loading model', 'running'); ui.status.textContent = 'Preparing the model. Files are loaded from Hugging Face on the first run.';
ui['progress-wrap'].hidden = false; ui['progress-bar'].style.width = '0%';
watchdog = setTimeout(() => failRun('The run exceeded 10 minutes.'), 600000);
try { getWorker().postMessage({ type: 'caption', id: state.request, image: state.image.dataUrl, options }); }
catch (error) { failRun(error.message); }
});
ui['stop-button'].addEventListener('click', () => {
stopWorker(); finishRun(); badge('Stopped');
ui.status.textContent = 'Run stopped. You can choose another model or try again; cached files can be reused.';
});
ui['image-input'].addEventListener('change', () => {
const file = ui['image-input'].files?.[0]; if (file) selectImage(() => Promise.resolve(file), file.name);
});
ui['shuffle-examples'].addEventListener('click', () => {
renderExamples(); ui.status.textContent = state.image ? 'New examples shown. Your current image remains selected.' : 'Choose an example or upload your own image.';
});
ui['model-select'].addEventListener('change', () => {
modelControls(); resetResult(); badge('Model changed');
ui.status.textContent = 'Run the selected model on your image to compare descriptions.';
});
ui['detail-select'].addEventListener('change', () => { modelControls(); resetResult(); });
ui['max-tokens'].addEventListener('input', () => { ui['token-value'].value = ui['max-tokens'].value; resetResult(); });
ui.instruction.addEventListener('input', resetResult);
ui['clear-history'].addEventListener('click', () => { state.history = []; renderHistory(); });
ui['download-history'].addEventListener('click', () => downloadFile('caption-comparison.json', JSON.stringify({ task: 'image-captioning', exportedAt: new Date().toISOString(), runs: state.history }, null, 2), 'application/json'));
ui['download-caption'].addEventListener('click', () => { if (state.result) downloadFile('caption.txt', state.result.caption + '\n', 'text/plain;charset=utf-8'); });
ui['copy-caption'].addEventListener('click', async () => {
if (!state.result) return;
try { await navigator.clipboard.writeText(state.result.caption); ui.status.textContent = 'Caption copied.'; }
catch { ui.status.textContent = 'Clipboard access is unavailable. Select the caption text or use Save caption.'; }
});
for (const model of MODEL_OPTIONS) { const option = document.createElement('option'); option.value = model.key; option.textContent = model.label; ui['model-select'].append(option); }
modelControls(); renderHistory();
fetch('./examples/manifest.json').then(response => {
if (!response.ok) throw new Error('Example list unavailable'); return response.json();
}).then(examples => { state.examples = examples; renderExamples(true); }).catch(() => {
ui.status.textContent = 'Examples could not be loaded. You can still upload your own image.';
});
|