cltsangwork commited on
Commit
fdf8aad
·
verified ·
1 Parent(s): c29a6fe

Update app.js

Browse files

run both selected models against the same image, show each model’s top predictions in its own panel, update the summary and comparison log

Files changed (1) hide show
  1. app.js +98 -41
app.js CHANGED
@@ -1,8 +1,10 @@
1
  import { MODEL_OPTIONS, classifyImage, getModelOption } from './classifier.js';
2
 
3
  const imageInput = document.querySelector('#image-input');
4
- const modelSelect = document.querySelector('#model-select');
5
- const modelNote = document.querySelector('#model-note');
 
 
6
  const clipControls = document.querySelector('#clip-controls');
7
  const candidateLabels = document.querySelector('#candidate-labels');
8
  const topK = document.querySelector('#top-k');
@@ -14,7 +16,10 @@ const progressBar = document.querySelector('#progress-bar');
14
  const previewWrap = document.querySelector('#preview-wrap');
15
  const previewImage = document.querySelector('#preview-image');
16
  const summary = document.querySelector('#summary');
17
- const tbody = document.querySelector('#predictions-body');
 
 
 
18
  const runtimeBadge = document.querySelector('#runtime-badge');
19
  const sampleGrid = document.querySelector('#sample-grid');
20
  const shuffleButton = document.querySelector('#shuffle-examples');
@@ -24,6 +29,8 @@ const metaImage = document.querySelector('#meta-image');
24
  const metaRuntime = document.querySelector('#meta-runtime');
25
  const historyBody = document.querySelector('#history-body');
26
  const clearHistory = document.querySelector('#clear-history');
 
 
27
 
28
  const state = { dataUrl: null, sourceLabel: null, running: false, history: [] };
29
 
@@ -140,7 +147,10 @@ function chooseRandom(items, count) {
140
 
141
  function resetResults() {
142
  summary.textContent = 'No predictions yet.';
143
- tbody.innerHTML = '<tr class="empty-row"><td colspan="3">Run the classifier to see details.</td></tr>';
 
 
 
144
  runMeta.hidden = true;
145
  }
146
 
@@ -153,6 +163,7 @@ function setRunning(running) {
153
  state.running = running;
154
  runButton.disabled = running || !state.dataUrl;
155
  modelSelect.disabled = running;
 
156
  imageInput.disabled = running;
157
  topK.disabled = running;
158
  candidateLabels.disabled = running;
@@ -199,7 +210,7 @@ async function loadExample(example, button) {
199
  imageInput.value = '';
200
  document.querySelectorAll('.sample-card').forEach((card) => card.classList.remove('selected'));
201
  button.classList.add('selected');
202
- setSelectedImage(dataUrl, example.label, `${example.label} example ready. Click Run AI Classification.`);
203
  } catch (error) {
204
  console.error(error);
205
  statusEl.textContent = 'Could not load that example. Try another image.';
@@ -207,15 +218,17 @@ async function loadExample(example, button) {
207
  }
208
  }
209
 
210
- function renderModelChoices() {
 
211
  for (const option of MODEL_OPTIONS) {
212
  const item = document.createElement('option');
213
  item.value = option.key;
214
  item.textContent = option.label;
215
- modelSelect.appendChild(item);
216
  }
217
- modelSelect.value = MODEL_OPTIONS[0].key;
218
- modelNote.textContent = MODEL_OPTIONS[0].note;
 
219
  }
220
 
221
  function renderExampleChoices() {
@@ -261,9 +274,8 @@ function parseCandidateLabels() {
261
  return candidateLabels.value.split(/[,\n]/).map((label) => label.trim()).filter(Boolean);
262
  }
263
 
264
- function renderPredictions(predictions) {
265
- tbody.innerHTML = '';
266
- const option = getModelOption(modelSelect.value);
267
  const scoreContext = option.task === 'zero-shot-image-classification'
268
  ? 'Scores compare only the candidate labels supplied above.'
269
  : 'Scores are calculated over the 1,000 ImageNet classes.';
@@ -292,13 +304,37 @@ function renderPredictions(predictions) {
292
  scoreCell.appendChild(scoreWrap);
293
 
294
  row.append(rankCell, labelCell, scoreCell);
295
- tbody.appendChild(row);
296
  });
297
 
298
  const best = predictions[0];
299
- summary.textContent = best
300
- ? `${option.label} predicts “${best.label}” at ${(Number(best.score) * 100).toFixed(1)}%. ${scoreContext}`
301
- : `${option.label} returned no predictions.`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
302
  }
303
 
304
  function renderHistory() {
@@ -350,14 +386,21 @@ function recordRun(option, predictions, seconds) {
350
 
351
  topK.addEventListener('input', () => { topKValue.value = topK.value; });
352
 
353
- modelSelect.addEventListener('change', () => {
354
- const option = getModelOption(modelSelect.value);
355
- modelNote.textContent = option.note;
356
- clipControls.hidden = option.task !== 'zero-shot-image-classification';
357
- setBadge(`Model: ${option.label}`);
 
 
 
 
358
  resetResults();
359
- if (state.dataUrl) statusEl.textContent = `Model changed to ${option.label}. Run again to compare predictions.`;
360
- });
 
 
 
361
 
362
  imageInput.addEventListener('change', () => {
363
  const file = imageInput.files?.[0];
@@ -375,7 +418,7 @@ imageInput.addEventListener('change', () => {
375
 
376
  document.querySelectorAll('.sample-card').forEach((card) => card.classList.remove('selected'));
377
  const reader = new FileReader();
378
- reader.onload = () => setSelectedImage(reader.result, 'Uploaded image', 'Your image is ready. Click Run AI Classification.');
379
  reader.onerror = () => {
380
  statusEl.textContent = 'Could not read that image.';
381
  setBadge('Image error', 'error');
@@ -398,36 +441,48 @@ shuffleButton.addEventListener('click', () => {
398
  runButton.addEventListener('click', async () => {
399
  if (!state.dataUrl || state.running) return;
400
 
401
- const option = getModelOption(modelSelect.value);
 
402
  const labels = parseCandidateLabels();
403
- if (option.task === 'zero-shot-image-classification' && (labels.length < 2 || labels.length > 20)) {
 
 
404
  statusEl.textContent = 'CLIP needs 2–20 candidate labels.';
405
  setBadge('Check labels', 'error');
406
  return;
407
  }
408
 
409
  setRunning(true);
410
- setBadge(`Loading ${option.label}`, 'running');
411
  progressWrap.hidden = false;
412
  progressBar.style.width = '4%';
413
  const started = performance.now();
414
 
415
  try {
416
- statusEl.textContent = `Preparing ${option.label}. The first run may download model files.`;
417
- const predictions = await classifyImage(state.dataUrl, {
418
- modelKey: option.key,
419
- topK: Number(topK.value),
420
- candidateLabels: labels,
421
- progressCallback: setProgress,
422
- });
423
- renderPredictions(predictions);
424
- const seconds = (performance.now() - started) / 1000;
425
- recordRun(option, predictions, seconds);
426
- statusEl.textContent = `Done in ${seconds.toFixed(1)}s with ${option.label}. Change the model or image to compare.`;
427
- setBadge(`${predictions.length} predictions`, 'ready');
 
 
 
 
 
 
 
 
 
428
  } catch (error) {
429
  console.error(error);
430
- statusEl.textContent = `${option.label} failed to run. Check the network connection or try ResNet-18.`;
431
  setBadge('Error', 'error');
432
  } finally {
433
  progressWrap.hidden = true;
@@ -435,6 +490,8 @@ runButton.addEventListener('click', async () => {
435
  }
436
  });
437
 
438
- renderModelChoices();
 
 
439
  renderExampleChoices();
440
  renderHistory();
 
1
  import { MODEL_OPTIONS, classifyImage, getModelOption } from './classifier.js';
2
 
3
  const imageInput = document.querySelector('#image-input');
4
+ const modelSelect = document.querySelector('#model-select-a');
5
+ const modelSelectAlt = document.querySelector('#model-select-b');
6
+ const modelNote = document.querySelector('#model-note-a');
7
+ const modelNoteAlt = document.querySelector('#model-note-b');
8
  const clipControls = document.querySelector('#clip-controls');
9
  const candidateLabels = document.querySelector('#candidate-labels');
10
  const topK = document.querySelector('#top-k');
 
16
  const previewWrap = document.querySelector('#preview-wrap');
17
  const previewImage = document.querySelector('#preview-image');
18
  const summary = document.querySelector('#summary');
19
+ const summaryA = document.querySelector('#summary-a');
20
+ const summaryB = document.querySelector('#summary-b');
21
+ const tbody = document.querySelector('#predictions-body-a');
22
+ const tbodyAlt = document.querySelector('#predictions-body-b');
23
  const runtimeBadge = document.querySelector('#runtime-badge');
24
  const sampleGrid = document.querySelector('#sample-grid');
25
  const shuffleButton = document.querySelector('#shuffle-examples');
 
29
  const metaRuntime = document.querySelector('#meta-runtime');
30
  const historyBody = document.querySelector('#history-body');
31
  const clearHistory = document.querySelector('#clear-history');
32
+ const modelAName = document.querySelector('#model-a-name');
33
+ const modelBName = document.querySelector('#model-b-name');
34
 
35
  const state = { dataUrl: null, sourceLabel: null, running: false, history: [] };
36
 
 
147
 
148
  function resetResults() {
149
  summary.textContent = 'No predictions yet.';
150
+ summaryA.textContent = 'No predictions yet.';
151
+ summaryB.textContent = 'No predictions yet.';
152
+ tbody.innerHTML = '<tr class="empty-row"><td colspan="3">Run both models to compare details.</td></tr>';
153
+ tbodyAlt.innerHTML = '<tr class="empty-row"><td colspan="3">Run both models to compare details.</td></tr>';
154
  runMeta.hidden = true;
155
  }
156
 
 
163
  state.running = running;
164
  runButton.disabled = running || !state.dataUrl;
165
  modelSelect.disabled = running;
166
+ modelSelectAlt.disabled = running;
167
  imageInput.disabled = running;
168
  topK.disabled = running;
169
  candidateLabels.disabled = running;
 
210
  imageInput.value = '';
211
  document.querySelectorAll('.sample-card').forEach((card) => card.classList.remove('selected'));
212
  button.classList.add('selected');
213
+ setSelectedImage(dataUrl, example.label, `${example.label} example ready. Click Run 2-Model Comparison.`);
214
  } catch (error) {
215
  console.error(error);
216
  statusEl.textContent = 'Could not load that example. Try another image.';
 
218
  }
219
  }
220
 
221
+ function renderModelChoices(select, noteEl, fallbackKey) {
222
+ select.innerHTML = '';
223
  for (const option of MODEL_OPTIONS) {
224
  const item = document.createElement('option');
225
  item.value = option.key;
226
  item.textContent = option.label;
227
+ select.appendChild(item);
228
  }
229
+ select.value = fallbackKey;
230
+ const selected = getModelOption(select.value);
231
+ noteEl.textContent = selected.note;
232
  }
233
 
234
  function renderExampleChoices() {
 
274
  return candidateLabels.value.split(/[,\n]/).map((label) => label.trim()).filter(Boolean);
275
  }
276
 
277
+ function renderPredictions(predictions, option, targetBody, targetSummary) {
278
+ targetBody.innerHTML = '';
 
279
  const scoreContext = option.task === 'zero-shot-image-classification'
280
  ? 'Scores compare only the candidate labels supplied above.'
281
  : 'Scores are calculated over the 1,000 ImageNet classes.';
 
304
  scoreCell.appendChild(scoreWrap);
305
 
306
  row.append(rankCell, labelCell, scoreCell);
307
+ targetBody.appendChild(row);
308
  });
309
 
310
  const best = predictions[0];
311
+ if (targetSummary) {
312
+ targetSummary.textContent = best
313
+ ? `${option.label} predicts “${best.label}” at ${(Number(best.score) * 100).toFixed(1)}%. ${scoreContext}`
314
+ : `${option.label} returned no predictions.`;
315
+ }
316
+ }
317
+
318
+ function renderComparison(results) {
319
+ const [firstResult, secondResult] = results;
320
+ if (!firstResult || !secondResult) return;
321
+
322
+ renderPredictions(firstResult.predictions, firstResult.option, tbody, summaryA);
323
+ renderPredictions(secondResult.predictions, secondResult.option, tbodyAlt, summaryB);
324
+
325
+ const firstBest = firstResult.predictions[0];
326
+ const secondBest = secondResult.predictions[0];
327
+ summary.textContent = [
328
+ firstBest ? `${firstResult.option.label} predicts “${firstBest.label}” at ${(Number(firstBest.score) * 100).toFixed(1)}%.` : `${firstResult.option.label} returned no predictions.`,
329
+ secondBest ? `${secondResult.option.label} predicts “${secondBest.label}” at ${(Number(secondBest.score) * 100).toFixed(1)}%.` : `${secondResult.option.label} returned no predictions.`,
330
+ ].join(' ');
331
+
332
+ modelAName.textContent = firstResult.option.label;
333
+ modelBName.textContent = secondResult.option.label;
334
+ metaModel.textContent = `${firstResult.option.label} + ${secondResult.option.label}`;
335
+ metaImage.textContent = state.sourceLabel || 'Selected image';
336
+ metaRuntime.textContent = `${results.reduce((total, item) => total + item.seconds, 0).toFixed(1)}s`;
337
+ runMeta.hidden = false;
338
  }
339
 
340
  function renderHistory() {
 
386
 
387
  topK.addEventListener('input', () => { topKValue.value = topK.value; });
388
 
389
+ function syncModelNotes() {
390
+ const optionA = getModelOption(modelSelect.value);
391
+ const optionB = getModelOption(modelSelectAlt.value);
392
+ modelNote.textContent = optionA.note;
393
+ modelNoteAlt.textContent = optionB.note;
394
+ modelAName.textContent = optionA.label;
395
+ modelBName.textContent = optionB.label;
396
+ clipControls.hidden = !(optionA.task === 'zero-shot-image-classification' || optionB.task === 'zero-shot-image-classification');
397
+ setBadge(`Models: ${optionA.label} + ${optionB.label}`);
398
  resetResults();
399
+ if (state.dataUrl) statusEl.textContent = `Models updated. Run both to compare predictions.`;
400
+ }
401
+
402
+ modelSelect.addEventListener('change', syncModelNotes);
403
+ modelSelectAlt.addEventListener('change', syncModelNotes);
404
 
405
  imageInput.addEventListener('change', () => {
406
  const file = imageInput.files?.[0];
 
418
 
419
  document.querySelectorAll('.sample-card').forEach((card) => card.classList.remove('selected'));
420
  const reader = new FileReader();
421
+ reader.onload = () => setSelectedImage(reader.result, 'Uploaded image', 'Your image is ready. Click Run 2-Model Comparison.');
422
  reader.onerror = () => {
423
  statusEl.textContent = 'Could not read that image.';
424
  setBadge('Image error', 'error');
 
441
  runButton.addEventListener('click', async () => {
442
  if (!state.dataUrl || state.running) return;
443
 
444
+ const optionA = getModelOption(modelSelect.value);
445
+ const optionB = getModelOption(modelSelectAlt.value);
446
  const labels = parseCandidateLabels();
447
+ const selectedModels = [optionA, optionB];
448
+
449
+ if (selectedModels.some((option) => option.task === 'zero-shot-image-classification') && (labels.length < 2 || labels.length > 20)) {
450
  statusEl.textContent = 'CLIP needs 2–20 candidate labels.';
451
  setBadge('Check labels', 'error');
452
  return;
453
  }
454
 
455
  setRunning(true);
456
+ setBadge('Comparing models', 'running');
457
  progressWrap.hidden = false;
458
  progressBar.style.width = '4%';
459
  const started = performance.now();
460
 
461
  try {
462
+ statusEl.textContent = `Running ${optionA.label} and ${optionB.label} on the same image.`;
463
+ const results = await Promise.all(selectedModels.map(async (option) => {
464
+ const runStarted = performance.now();
465
+ const predictions = await classifyImage(state.dataUrl, {
466
+ modelKey: option.key,
467
+ topK: Number(topK.value),
468
+ candidateLabels: labels,
469
+ progressCallback: setProgress,
470
+ });
471
+ return {
472
+ option,
473
+ predictions,
474
+ seconds: (performance.now() - runStarted) / 1000,
475
+ };
476
+ }));
477
+
478
+ results.forEach(({ option, predictions, seconds }) => recordRun(option, predictions, seconds));
479
+ renderComparison(results);
480
+ const totalSeconds = (performance.now() - started) / 1000;
481
+ statusEl.textContent = `Comparison complete in ${totalSeconds.toFixed(1)}s. ${optionA.label} and ${optionB.label} are ready to compare.`;
482
+ setBadge(`${results.length} models`, 'ready');
483
  } catch (error) {
484
  console.error(error);
485
+ statusEl.textContent = `${optionA.label} and ${optionB.label} failed to run. Check the network connection or try ResNet-18.`;
486
  setBadge('Error', 'error');
487
  } finally {
488
  progressWrap.hidden = true;
 
490
  }
491
  });
492
 
493
+ renderModelChoices(modelSelect, modelNote, MODEL_OPTIONS[0].key);
494
+ renderModelChoices(modelSelectAlt, modelNoteAlt, MODEL_OPTIONS[1].key);
495
+ syncModelNotes();
496
  renderExampleChoices();
497
  renderHistory();