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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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
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.';
});