Yunpeng-26 commited on
Commit
1ce8d0c
·
verified ·
1 Parent(s): 52d50a1

Delete app.js

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