Topic5APIC / app.js
cltsangwork's picture
Upload 6 files
4bbb9ea verified
Raw History Blame Contribute Delete
17.5 kB
import { MODEL_OPTIONS, getModelOption, defaultInstruction, normalizeOptions } from './models.js';
const KEYS = MODEL_OPTIONS.map(model => model.key);
const $ = id => document.getElementById(id);
const ui = Object.fromEntries([
'image-input', 'instruction-smol', 'run-button', 'stop-button', 'status', 'runtime-badge',
'progress-wrap', 'progress-bar', 'sample-grid', 'shuffle-examples', 'preview-image', 'preview-wrap',
'image-source', 'history-body', 'clear-history', 'download-history',
].map(id => [id, $(id)]));
const panels = Object.fromEntries(KEYS.map(key => [key, document.querySelector(`.captioner-panel[data-model="${key}"]`)]));
const part = (key, role) => panels[key].querySelector(`[data-role="${role}"]`);
const state = {
image: null, running: false, loadingImage: false, selection: 0, request: 0,
history: [], results: {}, examples: [], visible: [], pending: null, activeModel: null, runCount: 0,
};
let worker = null;
let watchdog = null;
function badge(text, mode = '') {
ui['runtime-badge'].textContent = text;
ui['runtime-badge'].className = `badge ${mode}`.trim();
}
function panelBadge(key, text, mode = '') {
const node = part(key, 'badge');
node.textContent = text;
node.className = `badge panel-badge ${mode}`.trim();
}
function refreshControls() {
const busy = state.running || state.loadingImage;
ui['image-input'].disabled = busy;
ui['shuffle-examples'].disabled = busy || !state.examples.length;
ui['run-button'].disabled = busy || !state.image;
ui['stop-button'].hidden = !state.running;
for (const button of ui['sample-grid'].querySelectorAll('button')) button.disabled = busy;
for (const key of KEYS) {
part(key, 'style').disabled = busy || key === 'vit';
part(key, 'tokens').disabled = busy;
part(key, 'copy').disabled = busy || !state.results[key];
part(key, 'save').disabled = busy || !state.results[key];
}
ui['instruction-smol'].disabled = busy;
}
function resetResults() {
state.results = {};
for (const key of KEYS) {
part(key, 'caption').textContent = 'No caption yet.';
part(key, 'caption').classList.remove('has-caption');
part(key, 'meta').hidden = true;
part(key, 'meta').textContent = '';
part(key, 'stale').hidden = true;
part(key, 'copy').disabled = true;
part(key, 'save').disabled = true;
panelBadge(key, 'Waiting');
}
refreshControls();
}
function markStale(key) {
if (state.results[key]) part(key, 'stale').hidden = false;
}
function readOptions(key) {
try {
return normalizeOptions({
modelKey: key,
style: part(key, 'style').value,
maxTokens: part(key, 'tokens').value,
instruction: key === 'smol' ? ui['instruction-smol'].value : '',
});
} catch (error) {
throw new Error(`${getModelOption(key).label}: ${error.message}`);
}
}
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 the captioners on an 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));
}
resetResults(); badge('Image ready'); ui.status.textContent = `${label} is ready. Click Run all three captioners.`;
} 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 clearWatchdog() {
clearTimeout(watchdog);
watchdog = null;
}
function armWatchdog() {
clearWatchdog();
watchdog = setTimeout(() => {
const pending = state.pending; state.pending = null;
stopWorker();
pending?.reject(new Error('This captioner exceeded 10 minutes. Try a shorter output limit or another image.'));
}, 600000);
}
function finishRun() {
clearWatchdog();
state.pending = null;
state.running = false;
ui['progress-wrap'].hidden = true;
refreshControls();
}
function stopWorker() {
worker?.terminate(); worker = null;
}
function crashRun(message) {
const pending = state.pending; state.pending = null;
stopWorker();
state.running = false;
pending?.reject(new Error(message));
finishRun();
badge('Run failed', 'error');
ui.status.textContent = `The captioning worker stopped. ${message} Try again; cached files can be reused.`;
}
function getWorker() {
if (worker) return worker;
worker = new Worker(new URL('./caption-worker.js', import.meta.url), { type: 'module' });
worker.onerror = event => crashRun(event.message || 'The inference worker stopped.');
worker.onmessageerror = () => crashRun('The model result could not be read.');
worker.onmessage = ({ data }) => {
if (data.id !== state.request || !state.running) return;
if (data.type === 'progress') { showProgress(data.progress); return; }
const pending = state.pending;
if (!pending) return;
state.pending = null;
if (data.type === 'error') pending.reject(new Error(data.message));
else if (data.type === 'result') pending.resolve(data.result);
};
return worker;
}
function showProgress(progress) {
const option = state.activeModel ? getModelOption(state.activeModel) : null;
const label = option?.label ?? 'The model';
if (progress.phase === 'library') {
ui.status.textContent = 'Loading the captioning library…';
} else if (progress.phase === 'download' && progress.file) {
ui.status.textContent = `Loading ${label}: ${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))}%`;
} else if (progress.phase === 'generate') {
if (state.activeModel) panelBadge(state.activeModel, 'Generating', 'running');
ui['progress-wrap'].hidden = true;
ui.status.textContent = `${label} is generating a caption…`;
}
}
function captionOne(key, options) {
return new Promise((resolve, reject) => {
state.pending = { key, resolve, reject };
try {
getWorker().postMessage({ type: 'caption', id: state.request, image: state.image.dataUrl, options });
} catch (error) {
state.pending = null;
reject(error);
}
});
}
function recordResult(key, result) {
state.results[key] = result;
const { dataUrl, ...imageInfo } = state.image;
const entry = { ...result, image: imageInfo, run: ++state.runCount, timestamp: new Date().toISOString() };
state.history.unshift(entry); state.history = state.history.slice(0, 12);
const caption = part(key, 'caption');
caption.textContent = result.caption;
caption.classList.add('has-caption');
const meta = part(key, 'meta');
meta.textContent = `Loading ${result.loadSeconds.toFixed(1)}s · Generating ${result.generationSeconds.toFixed(1)}s`;
meta.hidden = false;
part(key, 'stale').hidden = true;
panelBadge(key, 'Caption ready', 'ready');
renderHistory();
refreshControls();
}
async function runAll() {
if (!state.image || state.running || state.loadingImage) return;
let plan;
try {
plan = KEYS.map(key => ({ key, options: readOptions(key) }));
} catch (error) {
ui.status.textContent = error.message; badge('Check settings', 'error'); return;
}
state.running = true;
state.request += 1;
state.pending = null;
state.activeModel = null;
resetResults();
badge('Running captioners', 'running');
ui.status.textContent = 'Preparing the three captioners. The first run downloads model files.';
ui['progress-wrap'].hidden = false;
ui['progress-bar'].style.width = '0%';
let stopped = false;
try {
for (let index = 0; index < plan.length; index++) {
if (!state.running) { stopped = true; break; }
const { key, options } = plan[index];
const option = getModelOption(key);
state.activeModel = key;
panelBadge(key, 'Loading model', 'running');
part(key, 'caption').textContent = 'Waiting for this model…';
part(key, 'caption').classList.remove('has-caption');
ui['progress-wrap'].hidden = false;
ui['progress-bar'].style.width = '0%';
ui.status.textContent = `Loading ${option.label} (${index + 1} of ${plan.length})… The first run can take several minutes.`;
armWatchdog();
try {
const result = await captionOne(key, options);
clearWatchdog();
if (!state.running) { stopped = true; break; }
recordResult(key, result);
} catch (error) {
clearWatchdog();
if (!state.running) { stopped = true; break; }
panelBadge(key, 'Run failed', 'error');
part(key, 'caption').textContent = 'This captioner did not return a caption.';
ui.status.textContent = `${option.label}: ${error.message}`;
}
}
} finally {
if (!stopped) {
const completed = KEYS.filter(key => state.results[key]).length;
if (completed === KEYS.length) {
badge('All captions ready', 'ready');
ui.status.textContent = 'All three captions are ready. Compare objects, actions, and relationships against the image.';
} else {
badge('Finished with errors', 'error');
ui.status.textContent = `${completed} of ${KEYS.length} captions generated. Check the message above, then run again.`;
}
}
state.activeModel = null;
finishRun();
}
}
ui['run-button'].addEventListener('click', runAll);
ui['stop-button'].addEventListener('click', () => {
if (!state.running) return;
const pending = state.pending; state.pending = null;
const active = state.activeModel;
state.running = false;
stopWorker();
pending?.reject(new Error('Stopped by the user.'));
if (active) panelBadge(active, 'Stopped');
finishRun();
badge('Stopped');
ui.status.textContent = 'Run stopped. Finished captions are kept; run again to continue.';
});
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['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'));
for (const option of MODEL_OPTIONS) {
const optionPanel = panels[option.key];
optionPanel.querySelector('[data-role="title"]').textContent = option.label;
part(option.key, 'note').textContent = option.note;
part(option.key, 'detail').textContent = option.detailNote;
const tokens = part(option.key, 'tokens');
part(option.key, 'token-value').value = tokens.value;
tokens.addEventListener('input', () => { part(option.key, 'token-value').value = tokens.value; markStale(option.key); });
const style = part(option.key, 'style');
style.addEventListener('change', () => {
if (option.key === 'smol') ui['instruction-smol'].value = defaultInstruction(style.value);
markStale(option.key);
});
part(option.key, 'copy').addEventListener('click', async () => {
const result = state.results[option.key]; if (!result) return;
try { await navigator.clipboard.writeText(result.caption); ui.status.textContent = `${option.label} caption copied.`; }
catch { ui.status.textContent = 'Clipboard access is unavailable. Select the caption text or use Save caption.'; }
});
part(option.key, 'save').addEventListener('click', () => {
const result = state.results[option.key]; if (!result) return;
downloadFile(`${option.key}-caption.txt`, result.caption + '\n', 'text/plain;charset=utf-8');
});
}
ui['instruction-smol'].addEventListener('input', () => markStale('smol'));
part('vit', 'style').value = 'short';
ui['instruction-smol'].value = defaultInstruction('short');
renderHistory();
refreshControls();
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.';
});