Yunpeng-26 commited on
Commit
08f906b
·
verified ·
1 Parent(s): e7fcb2b

Upload app.js

Browse files
Files changed (1) hide show
  1. app.js +370 -0
app.js ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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');
9
+ const topKValue = document.querySelector('#top-k-value');
10
+ const runButton = document.querySelector('#run-button');
11
+ const statusEl = document.querySelector('#status');
12
+ const progressWrap = document.querySelector('#progress-wrap');
13
+ 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');
21
+ const runMeta = document.querySelector('#run-meta');
22
+ const metaModel = document.querySelector('#meta-model');
23
+ 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
+
30
+ const EXAMPLES = [
31
+ { src: './examples/chelsea.png', label: 'Cat' },
32
+ { src: './examples/coffee.png', label: 'Coffee' },
33
+ { src: './examples/rocket.jpg', label: 'Rocket' },
34
+ { src: './examples/astronaut.png', label: 'Astronaut' },
35
+ { src: './examples/cheetah.jpg', label: 'Cheetah' },
36
+ { src: './examples/lion.jpg', label: 'Lion' },
37
+ { src: './examples/tower.jpg', label: 'Tower' },
38
+ { src: './examples/bus.png', label: 'Bus illustration' },
39
+ { src: './examples/dog.jpg', label: 'Dog' },
40
+ { src: './examples/horse.jpg', label: 'Horse' },
41
+ { src: './examples/elephant.jpg', label: 'Elephant' },
42
+ { src: './examples/rabbit.jpg', label: 'Rabbit' },
43
+ { src: './examples/bird.jpg', label: 'Parrot' },
44
+ { src: './examples/cow.jpg', label: 'Cow' },
45
+ { src: './examples/airplane.jpg', label: 'Airplane' },
46
+ { src: './examples/car.jpg', label: 'Car' },
47
+ { src: './examples/bicycle.jpg', label: 'Bicycle' },
48
+ { src: './examples/train.jpg', label: 'Train' },
49
+ { src: './examples/motorcycle.jpg', label: 'Motorcycle' },
50
+ { src: './examples/boat.jpg', label: 'Boat' },
51
+ { src: './examples/truck.jpg', label: 'Truck' },
52
+ { src: './examples/pizza.jpg', label: 'Pizza' },
53
+ { src: './examples/hamburger.jpg', label: 'Hamburger' },
54
+ { src: './examples/apple.jpg', label: 'Apple' },
55
+ { src: './examples/banana.jpg', label: 'Banana' },
56
+ { src: './examples/orange.jpg', label: 'Orange' },
57
+ { src: './examples/sandwich.jpg', label: 'Sandwich' },
58
+ { src: './examples/bread.jpg', label: 'Bread' },
59
+ { src: './examples/strawberry.jpg', label: 'Strawberry' },
60
+ { src: './examples/ice_cream.jpg', label: 'Ice cream' },
61
+ ];
62
+
63
+ function chooseRandom(items, count) {
64
+ return [...items]
65
+ .map((item) => ({ item, sort: Math.random() }))
66
+ .sort((a, b) => a.sort - b.sort)
67
+ .slice(0, count)
68
+ .map(({ item }) => item);
69
+ }
70
+
71
+ function resetResults() {
72
+ summary.textContent = 'No predictions yet.';
73
+ tbody.innerHTML = '<tr class="empty-row"><td colspan="3">Run the classifier to see details.</td></tr>';
74
+ runMeta.hidden = true;
75
+ }
76
+
77
+ function setBadge(text, mode = '') {
78
+ runtimeBadge.textContent = text;
79
+ runtimeBadge.className = `badge ${mode}`.trim();
80
+ }
81
+
82
+ function setRunning(running) {
83
+ state.running = running;
84
+ runButton.disabled = running || !state.dataUrl;
85
+ modelSelect.disabled = running;
86
+ imageInput.disabled = running;
87
+ topK.disabled = running;
88
+ candidateLabels.disabled = running;
89
+ shuffleButton.disabled = running;
90
+ document.querySelectorAll('.sample-card').forEach((card) => { card.disabled = running; });
91
+ }
92
+
93
+ function setSelectedImage(dataUrl, label, readyMessage) {
94
+ const image = new Image();
95
+ image.onload = () => {
96
+ state.dataUrl = dataUrl;
97
+ state.sourceLabel = label;
98
+ previewImage.src = dataUrl;
99
+ previewImage.alt = `${label} selected for classification`;
100
+ previewWrap.classList.remove('empty');
101
+ setRunning(false);
102
+ statusEl.textContent = readyMessage;
103
+ setBadge('Image ready');
104
+ resetResults();
105
+ };
106
+ image.onerror = () => {
107
+ statusEl.textContent = 'Could not read that image.';
108
+ setBadge('Image error', 'error');
109
+ };
110
+ image.src = dataUrl;
111
+ }
112
+
113
+ function blobToDataUrl(blob) {
114
+ return new Promise((resolve, reject) => {
115
+ const reader = new FileReader();
116
+ reader.onload = () => resolve(reader.result);
117
+ reader.onerror = reject;
118
+ reader.readAsDataURL(blob);
119
+ });
120
+ }
121
+
122
+ async function loadExample(example, button) {
123
+ try {
124
+ statusEl.textContent = `Loading example: ${example.label}…`;
125
+ setBadge('Loading sample', 'running');
126
+ const response = await fetch(example.src);
127
+ if (!response.ok) throw new Error(`Could not load ${example.src}`);
128
+ const dataUrl = await blobToDataUrl(await response.blob());
129
+ imageInput.value = '';
130
+ document.querySelectorAll('.sample-card').forEach((card) => card.classList.remove('selected'));
131
+ button.classList.add('selected');
132
+ setSelectedImage(dataUrl, example.label, `${example.label} example ready. Click Run AI Classification.`);
133
+ } catch (error) {
134
+ console.error(error);
135
+ statusEl.textContent = 'Could not load that example. Try another image.';
136
+ setBadge('Sample error', 'error');
137
+ }
138
+ }
139
+
140
+ function renderModelChoices() {
141
+ for (const option of MODEL_OPTIONS) {
142
+ const item = document.createElement('option');
143
+ item.value = option.key;
144
+ item.textContent = option.label;
145
+ modelSelect.appendChild(item);
146
+ }
147
+ modelSelect.value = MODEL_OPTIONS[0].key;
148
+ modelNote.textContent = MODEL_OPTIONS[0].note;
149
+ }
150
+
151
+ function renderExampleChoices() {
152
+ sampleGrid.innerHTML = '';
153
+ for (const example of chooseRandom(EXAMPLES, 4)) {
154
+ const button = document.createElement('button');
155
+ button.type = 'button';
156
+ button.className = 'sample-card';
157
+ button.title = `Use sample: ${example.label}`;
158
+
159
+ const image = document.createElement('img');
160
+ image.src = example.src;
161
+ image.alt = example.label;
162
+ image.loading = 'lazy';
163
+
164
+ const label = document.createElement('span');
165
+ label.textContent = example.label;
166
+
167
+ const source = document.createElement('small');
168
+ source.textContent = 'Tested teaching sample';
169
+
170
+ button.append(image, label, source);
171
+ button.addEventListener('click', () => loadExample(example, button));
172
+ sampleGrid.appendChild(button);
173
+ }
174
+ }
175
+
176
+ function setProgress(data) {
177
+ let percent = null;
178
+ if (typeof data?.progress === 'number') percent = data.progress;
179
+ else if (data?.total && typeof data?.loaded === 'number') percent = (data.loaded / data.total) * 100;
180
+
181
+ if (percent !== null && Number.isFinite(percent)) {
182
+ progressWrap.hidden = false;
183
+ progressBar.style.width = `${Math.max(0, Math.min(100, percent))}%`;
184
+ }
185
+ if (data?.status === 'progress' && data?.file) {
186
+ statusEl.textContent = `Downloading model: ${data.file}`;
187
+ }
188
+ }
189
+
190
+ function parseCandidateLabels() {
191
+ return candidateLabels.value.split(/[,\n]/).map((label) => label.trim()).filter(Boolean);
192
+ }
193
+
194
+ function renderPredictions(predictions) {
195
+ tbody.innerHTML = '';
196
+ const option = getModelOption(modelSelect.value);
197
+ const scoreContext = option.task === 'zero-shot-image-classification'
198
+ ? 'Scores compare only the candidate labels supplied above.'
199
+ : 'Scores are calculated over the 1,000 ImageNet classes.';
200
+
201
+ predictions.forEach((prediction, index) => {
202
+ const row = document.createElement('tr');
203
+ const rankCell = document.createElement('td');
204
+ rankCell.textContent = index + 1;
205
+
206
+ const labelCell = document.createElement('td');
207
+ labelCell.textContent = prediction.label;
208
+
209
+ const score = Math.max(0, Math.min(1, Number(prediction.score)));
210
+ const scoreCell = document.createElement('td');
211
+ const scoreWrap = document.createElement('div');
212
+ scoreWrap.className = 'score-wrap';
213
+ const scoreText = document.createElement('span');
214
+ scoreText.textContent = `${(score * 100).toFixed(2)}%`;
215
+ const scoreTrack = document.createElement('span');
216
+ scoreTrack.className = 'score-track';
217
+ const scoreFill = document.createElement('span');
218
+ scoreFill.className = 'score-fill';
219
+ scoreFill.style.width = `${score * 100}%`;
220
+ scoreTrack.appendChild(scoreFill);
221
+ scoreWrap.append(scoreText, scoreTrack);
222
+ scoreCell.appendChild(scoreWrap);
223
+
224
+ row.append(rankCell, labelCell, scoreCell);
225
+ tbody.appendChild(row);
226
+ });
227
+
228
+ const best = predictions[0];
229
+ summary.textContent = best
230
+ ? `${option.label} predicts “${best.label}” at ${(Number(best.score) * 100).toFixed(1)}%. ${scoreContext}`
231
+ : `${option.label} returned no predictions.`;
232
+ }
233
+
234
+ function renderHistory() {
235
+ clearHistory.disabled = state.history.length === 0;
236
+ if (!state.history.length) {
237
+ historyBody.innerHTML = '<tr class="empty-row"><td colspan="6">Run two models on the same image to start a comparison.</td></tr>';
238
+ return;
239
+ }
240
+
241
+ historyBody.innerHTML = '';
242
+ state.history.forEach((item, index) => {
243
+ const row = document.createElement('tr');
244
+ const values = [
245
+ index + 1,
246
+ item.image,
247
+ item.model,
248
+ item.label,
249
+ `${(item.score * 100).toFixed(1)}%`,
250
+ `${item.seconds.toFixed(1)}s`,
251
+ ];
252
+ values.forEach((value) => {
253
+ const cell = document.createElement('td');
254
+ cell.textContent = value;
255
+ row.appendChild(cell);
256
+ });
257
+ historyBody.appendChild(row);
258
+ });
259
+ }
260
+
261
+ function recordRun(option, predictions, seconds) {
262
+ const best = predictions[0];
263
+ if (!best) return;
264
+
265
+ state.history.unshift({
266
+ image: state.sourceLabel || 'Selected image',
267
+ model: option.label,
268
+ label: best.label,
269
+ score: Number(best.score),
270
+ seconds,
271
+ });
272
+ state.history = state.history.slice(0, 12);
273
+ renderHistory();
274
+
275
+ metaModel.textContent = option.label;
276
+ metaImage.textContent = state.sourceLabel || 'Selected image';
277
+ metaRuntime.textContent = `${seconds.toFixed(1)}s`;
278
+ runMeta.hidden = false;
279
+ }
280
+
281
+ topK.addEventListener('input', () => { topKValue.value = topK.value; });
282
+
283
+ modelSelect.addEventListener('change', () => {
284
+ const option = getModelOption(modelSelect.value);
285
+ modelNote.textContent = option.note;
286
+ clipControls.hidden = option.task !== 'zero-shot-image-classification';
287
+ setBadge(`Model: ${option.label}`);
288
+ resetResults();
289
+ if (state.dataUrl) statusEl.textContent = `Model changed to ${option.label}. Run again to compare predictions.`;
290
+ });
291
+
292
+ imageInput.addEventListener('change', () => {
293
+ const file = imageInput.files?.[0];
294
+ if (!file) return;
295
+ if (!file.type.startsWith('image/')) {
296
+ statusEl.textContent = 'Please choose an image file.';
297
+ setBadge('Invalid file', 'error');
298
+ return;
299
+ }
300
+ if (file.size > 12 * 1024 * 1024) {
301
+ statusEl.textContent = 'Please choose an image smaller than 12 MB.';
302
+ setBadge('Image too large', 'error');
303
+ return;
304
+ }
305
+
306
+ document.querySelectorAll('.sample-card').forEach((card) => card.classList.remove('selected'));
307
+ const reader = new FileReader();
308
+ reader.onload = () => setSelectedImage(reader.result, 'Uploaded image', 'Your image is ready. Click Run AI Classification.');
309
+ reader.onerror = () => {
310
+ statusEl.textContent = 'Could not read that image.';
311
+ setBadge('Image error', 'error');
312
+ };
313
+ reader.readAsDataURL(file);
314
+ });
315
+
316
+ clearHistory.addEventListener('click', () => {
317
+ state.history = [];
318
+ renderHistory();
319
+ });
320
+
321
+ shuffleButton.addEventListener('click', () => {
322
+ renderExampleChoices();
323
+ statusEl.textContent = state.dataUrl
324
+ ? 'New examples shown. Your current image is still selected.'
325
+ : 'Choose an example, or upload your own image.';
326
+ });
327
+
328
+ runButton.addEventListener('click', async () => {
329
+ if (!state.dataUrl || state.running) return;
330
+
331
+ const option = getModelOption(modelSelect.value);
332
+ const labels = parseCandidateLabels();
333
+ if (option.task === 'zero-shot-image-classification' && (labels.length < 2 || labels.length > 20)) {
334
+ statusEl.textContent = 'CLIP needs 2–20 candidate labels.';
335
+ setBadge('Check labels', 'error');
336
+ return;
337
+ }
338
+
339
+ setRunning(true);
340
+ setBadge(`Loading ${option.label}`, 'running');
341
+ progressWrap.hidden = false;
342
+ progressBar.style.width = '4%';
343
+ const started = performance.now();
344
+
345
+ try {
346
+ statusEl.textContent = `Preparing ${option.label}. The first run may download model files.`;
347
+ const predictions = await classifyImage(state.dataUrl, {
348
+ modelKey: option.key,
349
+ topK: Number(topK.value),
350
+ candidateLabels: labels,
351
+ progressCallback: setProgress,
352
+ });
353
+ renderPredictions(predictions);
354
+ const seconds = (performance.now() - started) / 1000;
355
+ recordRun(option, predictions, seconds);
356
+ statusEl.textContent = `Done in ${seconds.toFixed(1)}s with ${option.label}. Change the model or image to compare.`;
357
+ setBadge(`${predictions.length} predictions`, 'ready');
358
+ } catch (error) {
359
+ console.error(error);
360
+ statusEl.textContent = `${option.label} failed to run. Check the network connection or try ResNet-18.`;
361
+ setBadge('Error', 'error');
362
+ } finally {
363
+ progressWrap.hidden = true;
364
+ setRunning(false);
365
+ }
366
+ });
367
+
368
+ renderModelChoices();
369
+ renderExampleChoices();
370
+ renderHistory();