Spaces:
Running
Running
Upload 6 files
Browse files- README.md +94 -94
- app.js +233 -80
- captioner.js +85 -85
- captioning.css +86 -19
- how-to-start.html +13 -13
- index.html +103 -37
README.md
CHANGED
|
@@ -1,94 +1,94 @@
|
|
| 1 |
-
---
|
| 2 |
-
title: AI-Powered Image Captioning
|
| 3 |
-
emoji: 🖼️
|
| 4 |
-
colorFrom: blue
|
| 5 |
-
colorTo: indigo
|
| 6 |
-
sdk: static
|
| 7 |
-
app_file: index.html
|
| 8 |
-
pinned: false
|
| 9 |
-
models:
|
| 10 |
-
- Xenova/vit-gpt2-image-captioning
|
| 11 |
-
- onnx-community/Florence-2-base-ft
|
| 12 |
-
- HuggingFaceTB/SmolVLM-256M-Instruct
|
| 13 |
-
---
|
| 14 |
-
|
| 15 |
-
# AI-Powered Image Captioning
|
| 16 |
-
|
| 17 |
-
A teaching mini-lab for Creative Technology and introductory computer vision. Choose a picture, generate an English description, and compare the sentence with the visual evidence.
|
| 18 |
-
|
| 19 |
-
## Start with a working example
|
| 20 |
-
|
| 21 |
-
1. Choose an example or upload a PNG, JPEG, or WebP image up to 12 MB.
|
| 22 |
-
2.
|
| 23 |
-
3. Allow the
|
| 24 |
-
4.
|
| 25 |
-
5.
|
| 26 |
-
6. Download the comparison log before reloading to retain the captions and exact settings.
|
| 27 |
-
|
| 28 |
-
The **How to Start** page explains the workflow, file structure, Space duplication, and student submission. No model training or API key is required.
|
| 29 |
-
|
| 30 |
-
## Models and controls
|
| 31 |
-
|
| 32 |
-
| Captioner | Model | What to explore |
|
| 33 |
-
|---|---|---|
|
| 34 |
-
| ViT-GPT2 | [Xenova/vit-gpt2-image-captioning](https://huggingface.co/Xenova/vit-gpt2-image-captioning) | A visual encoder and a language decoder; short captions without a text instruction |
|
| 35 |
-
| Florence-2 Base | [onnx-community/Florence-2-base-ft](https://huggingface.co/onnx-community/Florence-2-base-ft) | Short captions with `<CAPTION>` and detailed descriptions with `<MORE_DETAILED_CAPTION>` |
|
| 36 |
-
| SmolVLM 256M | [HuggingFaceTB/SmolVLM-256M-Instruct](https://huggingface.co/HuggingFaceTB/SmolVLM-256M-Instruct) | An image plus a natural-language instruction; the prompt can change the requested description |
|
| 37 |
-
|
| 38 |
-
The app pins Transformers.js **4.2.0** and model revisions in `models.js`. It uses quantized `q8` ONNX weights, WebAssembly, greedy decoding, and a maximum output of 32–128 new tokens. Graph optimization is disabled specifically for the older ViT-GPT2 quantized decoder to avoid an ONNX Runtime QDQ optimizer incompatibility; other models use the default optimizer. A token limit is not an exact word count; the model may stop earlier or be cut off at the limit. Model outputs are displayed as generated, without replacing them with reference captions.
|
| 39 |
-
|
| 40 |
-
BLIP remains a useful course/Python model, but is not included as an unsupported browser option. This static demo uses the three browser-compatible model families above. A compatible model file is necessary but does not guarantee useful captions for every image.
|
| 41 |
-
|
| 42 |
-
## Application files
|
| 43 |
-
|
| 44 |
-
- `index.html` — course page,
|
| 45 |
-
- `style.css` — the existing image-classification site's shared style, kept unchanged.
|
| 46 |
-
- `captioning.css` —
|
| 47 |
-
- `models.js` — model IDs, revisions, and validated generation settings.
|
| 48 |
-
- `captioner.js` — load → prepare → generate → decode.
|
| 49 |
-
- `caption-worker.js` — inference in a worker; stopping a run terminates that worker.
|
| 50 |
-
- `app.js` — input validation, image selection,
|
| 51 |
-
- `how-to-start.html` — student guide.
|
| 52 |
-
- `examples/manifest.json` — gallery items and their sources.
|
| 53 |
-
- `examples/SOURCES.md` — source and license records for the 86 images.
|
| 54 |
-
|
| 55 |
-
## Runtime and image handling
|
| 56 |
-
|
| 57 |
-
This is a Hugging Face **Static Space**. The library is loaded from jsDelivr; model files are loaded from Hugging Face. Inference runs in the browser, not on an inference server. Images are decoded locally, converted to RGB JPEG on a white background, and resized to a maximum side of 1,600 pixels before the model's own preprocessing. Images exceeding 40 million pixels are rejected to limit memory use.
|
| 58 |
-
|
| 59 |
-
The first run loads roughly a few hundred MB per model
|
| 60 |
-
|
| 61 |
-
The page reports loading and generation separately. Generation time includes preprocessing and decoding after loading; it is a classroom observation, not a hardware-independent speed benchmark. The JSON log includes the model revision, task prompt or instruction, generation settings, library version, image dimensions, and timings. Uploaded image pixels are not included in that exported log.
|
| 62 |
-
|
| 63 |
-
The latest 12 successful runs are held in page memory. The app does not store a user's uploaded images or captions on a server. Reloading clears the comparison log, but may leave downloaded model files in the browser cache.
|
| 64 |
-
|
| 65 |
-
## Example images
|
| 66 |
-
|
| 67 |
-
The 86 CC0 photographs are reused from the course image-classification example bank. Four are shown at a time; **Shuffle** changes the displayed set. Gallery names identify the pictures, not the expected generated sentence. These examples are not a caption benchmark and do not imply measured accuracy. See [image sources](examples/SOURCES.md).
|
| 68 |
-
|
| 69 |
-
## Deploy or preview
|
| 70 |
-
|
| 71 |
-
Create or duplicate a **Static** Hugging Face Space. Upload the files in this folder at the repository root, retaining `examples/` and the README metadata. No build command, Python environment, private token in source, or bundled weights are needed.
|
| 72 |
-
|
| 73 |
-
For a local preview, run the following in this folder:
|
| 74 |
-
|
| 75 |
-
```bash
|
| 76 |
-
python -m http.server 7860
|
| 77 |
-
```
|
| 78 |
-
|
| 79 |
-
Open `http://localhost:7860`. Do not open the HTML directly with `file://`; browser modules and workers need an HTTP origin.
|
| 80 |
-
|
| 81 |
-
## Classroom assignment
|
| 82 |
-
|
| 83 |
-
Build a small application around a pretrained captioner. Submit a working Space URL, explain the model's input and output, show one successful and one difficult example, and compare one controlled change. Retain the actual generated descriptions and cite image sources. Training or fine-tuning is optional.
|
| 84 |
-
|
| 85 |
-
More detail and smoother language do not necessarily mean a more accurate caption. Inspect objects, counts, attributes, actions, and relationships. This app does not report a fabricated confidence percentage or claim a caption is correct automatically.
|
| 86 |
-
|
| 87 |
-
## Reading
|
| 88 |
-
|
| 89 |
-
- [Show and Tell](https://arxiv.org/abs/1411.4555) — an early encoder–decoder captioning model.
|
| 90 |
-
- [Show, Attend and Tell](https://proceedings.mlr.press/v37/xuc15.html) — visual attention.
|
| 91 |
-
- [Florence-2 paper](https://arxiv.org/abs/2311.06242) — unified vision tasks and task prompts.
|
| 92 |
-
- [SmolVLM model card](https://huggingface.co/HuggingFaceTB/SmolVLM-256M-Instruct) — the instruction-following model used here.
|
| 93 |
-
- [Object Hallucination in Image Captioning](https://aclanthology.org/D18-1437/) — why plausible captions can mention unsupported objects.
|
| 94 |
-
- [Transformers.js documentation](https://huggingface.co/docs/transformers.js) — browser inference library.
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: AI-Powered Image Captioning
|
| 3 |
+
emoji: 🖼️
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: indigo
|
| 6 |
+
sdk: static
|
| 7 |
+
app_file: index.html
|
| 8 |
+
pinned: false
|
| 9 |
+
models:
|
| 10 |
+
- Xenova/vit-gpt2-image-captioning
|
| 11 |
+
- onnx-community/Florence-2-base-ft
|
| 12 |
+
- HuggingFaceTB/SmolVLM-256M-Instruct
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
# AI-Powered Image Captioning
|
| 16 |
+
|
| 17 |
+
A teaching mini-lab for Creative Technology and introductory computer vision. Choose a picture, generate an English description, and compare the sentence with the visual evidence.
|
| 18 |
+
|
| 19 |
+
## Start with a working example
|
| 20 |
+
|
| 21 |
+
1. Choose an example or upload a PNG, JPEG, or WebP image up to 12 MB.
|
| 22 |
+
2. Select **Run all three captioners**. One image is shared by all three columns.
|
| 23 |
+
3. Allow the models to load on the first run. Each column shows its caption, timings, and its own options.
|
| 24 |
+
4. Compare objects, attributes, actions, relationships, omissions, and unsupported details side by side.
|
| 25 |
+
5. Keep the image fixed and change one captioner's options, such as Florence-2's description style or SmolVLM's instruction, then run again.
|
| 26 |
+
6. Download the comparison log before reloading to retain the captions and exact settings.
|
| 27 |
+
|
| 28 |
+
The **How to Start** page explains the workflow, file structure, Space duplication, and student submission. No model training or API key is required.
|
| 29 |
+
|
| 30 |
+
## Models and controls
|
| 31 |
+
|
| 32 |
+
| Captioner | Model | What to explore |
|
| 33 |
+
|---|---|---|
|
| 34 |
+
| ViT-GPT2 | [Xenova/vit-gpt2-image-captioning](https://huggingface.co/Xenova/vit-gpt2-image-captioning) | A visual encoder and a language decoder; short captions without a text instruction |
|
| 35 |
+
| Florence-2 Base | [onnx-community/Florence-2-base-ft](https://huggingface.co/onnx-community/Florence-2-base-ft) | Short captions with `<CAPTION>` and detailed descriptions with `<MORE_DETAILED_CAPTION>` |
|
| 36 |
+
| SmolVLM 256M | [HuggingFaceTB/SmolVLM-256M-Instruct](https://huggingface.co/HuggingFaceTB/SmolVLM-256M-Instruct) | An image plus a natural-language instruction; the prompt can change the requested description |
|
| 37 |
+
|
| 38 |
+
The app pins Transformers.js **4.2.0** and model revisions in `models.js`. It uses quantized `q8` ONNX weights, WebAssembly, greedy decoding, and a maximum output of 32–128 new tokens. Graph optimization is disabled specifically for the older ViT-GPT2 quantized decoder to avoid an ONNX Runtime QDQ optimizer incompatibility; other models use the default optimizer. A token limit is not an exact word count; the model may stop earlier or be cut off at the limit. Model outputs are displayed as generated, without replacing them with reference captions.
|
| 39 |
+
|
| 40 |
+
BLIP remains a useful course/Python model, but is not included as an unsupported browser option. This static demo uses the three browser-compatible model families above. A compatible model file is necessary but does not guarantee useful captions for every image.
|
| 41 |
+
|
| 42 |
+
## Application files
|
| 43 |
+
|
| 44 |
+
- `index.html` — course page, shared image, three captioner columns, and comparison table.
|
| 45 |
+
- `style.css` — the existing image-classification site's shared style, kept unchanged.
|
| 46 |
+
- `captioning.css` — the side-by-side captioner layout, caption controls, and guide styles.
|
| 47 |
+
- `models.js` — model IDs, revisions, and validated generation settings.
|
| 48 |
+
- `captioner.js` — load → prepare → generate → decode; loaded models stay cached for reruns.
|
| 49 |
+
- `caption-worker.js` — inference in a worker; stopping a run terminates that worker.
|
| 50 |
+
- `app.js` — input validation, image selection, sequential captioning, and log export.
|
| 51 |
+
- `how-to-start.html` — student guide.
|
| 52 |
+
- `examples/manifest.json` — gallery items and their sources.
|
| 53 |
+
- `examples/SOURCES.md` — source and license records for the 86 images.
|
| 54 |
+
|
| 55 |
+
## Runtime and image handling
|
| 56 |
+
|
| 57 |
+
This is a Hugging Face **Static Space**. The library is loaded from jsDelivr; model files are loaded from Hugging Face. Inference runs in the browser, not on an inference server. Images are decoded locally, converted to RGB JPEG on a white background, and resized to a maximum side of 1,600 pixels before the model's own preprocessing. Images exceeding 40 million pixels are rejected to limit memory use.
|
| 58 |
+
|
| 59 |
+
The first run loads roughly a few hundred MB per model, and the three captioners are generated one after another in the same worker. A loaded model stays cached in memory so a rerun does not reinitialize it; stopping a run terminates the worker and releases every model. Because all three can be resident at once, a recent desktop browser with free memory is recommended. Browser cache availability, memory, device speed, and network access affect runtime. An interrupted or failed captioner can be retried, and a model is stopped if it exceeds ten minutes.
|
| 60 |
+
|
| 61 |
+
The page reports loading and generation separately. Generation time includes preprocessing and decoding after loading; it is a classroom observation, not a hardware-independent speed benchmark. The JSON log includes the model revision, task prompt or instruction, generation settings, library version, image dimensions, and timings. Uploaded image pixels are not included in that exported log.
|
| 62 |
+
|
| 63 |
+
The latest 12 successful runs are held in page memory. The app does not store a user's uploaded images or captions on a server. Reloading clears the comparison log, but may leave downloaded model files in the browser cache.
|
| 64 |
+
|
| 65 |
+
## Example images
|
| 66 |
+
|
| 67 |
+
The 86 CC0 photographs are reused from the course image-classification example bank. Four are shown at a time; **Shuffle** changes the displayed set. Gallery names identify the pictures, not the expected generated sentence. These examples are not a caption benchmark and do not imply measured accuracy. See [image sources](examples/SOURCES.md).
|
| 68 |
+
|
| 69 |
+
## Deploy or preview
|
| 70 |
+
|
| 71 |
+
Create or duplicate a **Static** Hugging Face Space. Upload the files in this folder at the repository root, retaining `examples/` and the README metadata. No build command, Python environment, private token in source, or bundled weights are needed.
|
| 72 |
+
|
| 73 |
+
For a local preview, run the following in this folder:
|
| 74 |
+
|
| 75 |
+
```bash
|
| 76 |
+
python -m http.server 7860
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
Open `http://localhost:7860`. Do not open the HTML directly with `file://`; browser modules and workers need an HTTP origin.
|
| 80 |
+
|
| 81 |
+
## Classroom assignment
|
| 82 |
+
|
| 83 |
+
Build a small application around a pretrained captioner. Submit a working Space URL, explain the model's input and output, show one successful and one difficult example, and compare one controlled change. Retain the actual generated descriptions and cite image sources. Training or fine-tuning is optional.
|
| 84 |
+
|
| 85 |
+
More detail and smoother language do not necessarily mean a more accurate caption. Inspect objects, counts, attributes, actions, and relationships. This app does not report a fabricated confidence percentage or claim a caption is correct automatically.
|
| 86 |
+
|
| 87 |
+
## Reading
|
| 88 |
+
|
| 89 |
+
- [Show and Tell](https://arxiv.org/abs/1411.4555) — an early encoder–decoder captioning model.
|
| 90 |
+
- [Show, Attend and Tell](https://proceedings.mlr.press/v37/xuc15.html) — visual attention.
|
| 91 |
+
- [Florence-2 paper](https://arxiv.org/abs/2311.06242) — unified vision tasks and task prompts.
|
| 92 |
+
- [SmolVLM model card](https://huggingface.co/HuggingFaceTB/SmolVLM-256M-Instruct) — the instruction-following model used here.
|
| 93 |
+
- [Object Hallucination in Image Captioning](https://aclanthology.org/D18-1437/) — why plausible captions can mention unsupported objects.
|
| 94 |
+
- [Transformers.js documentation](https://huggingface.co/docs/transformers.js) — browser inference library.
|
app.js
CHANGED
|
@@ -1,15 +1,20 @@
|
|
| 1 |
import { MODEL_OPTIONS, getModelOption, defaultInstruction, normalizeOptions } from './models.js';
|
| 2 |
|
|
|
|
| 3 |
const $ = id => document.getElementById(id);
|
| 4 |
const ui = Object.fromEntries([
|
| 5 |
-
'image-input', '
|
| 6 |
-
'instruction', 'max-tokens', 'token-value', 'run-button', 'stop-button', 'status', 'runtime-badge',
|
| 7 |
'progress-wrap', 'progress-bar', 'sample-grid', 'shuffle-examples', 'preview-image', 'preview-wrap',
|
| 8 |
-
'image-source', '
|
| 9 |
-
'copy-caption', 'download-caption', 'history-body', 'clear-history', 'download-history',
|
| 10 |
].map(id => [id, $(id)]));
|
| 11 |
|
| 12 |
-
const
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
let worker = null;
|
| 14 |
let watchdog = null;
|
| 15 |
|
|
@@ -18,33 +23,58 @@ function badge(text, mode = '') {
|
|
| 18 |
ui['runtime-badge'].className = `badge ${mode}`.trim();
|
| 19 |
}
|
| 20 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
function refreshControls() {
|
| 22 |
const busy = state.running || state.loadingImage;
|
| 23 |
-
|
| 24 |
-
ui['detail-select'].disabled = busy || ui['model-select'].value === 'vit';
|
| 25 |
ui['shuffle-examples'].disabled = busy || !state.examples.length;
|
| 26 |
ui['run-button'].disabled = busy || !state.image;
|
| 27 |
ui['stop-button'].hidden = !state.running;
|
| 28 |
-
ui['copy-caption'].disabled = busy || !state.result;
|
| 29 |
-
ui['download-caption'].disabled = busy || !state.result;
|
| 30 |
for (const button of ui['sample-grid'].querySelectorAll('button')) button.disabled = busy;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
}
|
| 32 |
|
| 33 |
-
function
|
| 34 |
-
state.
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
refreshControls();
|
| 38 |
}
|
| 39 |
|
| 40 |
-
function
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
}
|
| 49 |
|
| 50 |
function downloadFile(filename, content, type) {
|
|
@@ -60,7 +90,7 @@ function renderHistory() {
|
|
| 60 |
ui['history-body'].replaceChildren();
|
| 61 |
if (!state.history.length) {
|
| 62 |
const row = document.createElement('tr'); row.className = 'empty-row';
|
| 63 |
-
const cell = document.createElement('td'); cell.colSpan = 6; cell.textContent = 'Run
|
| 64 |
row.append(cell); ui['history-body'].append(row); return;
|
| 65 |
}
|
| 66 |
for (const item of state.history) {
|
|
@@ -111,7 +141,7 @@ async function selectImage(loadBlob, label, source = null, key = null) {
|
|
| 111 |
const selected = card.dataset.src === key;
|
| 112 |
card.classList.toggle('selected', selected); card.setAttribute('aria-pressed', String(selected));
|
| 113 |
}
|
| 114 |
-
|
| 115 |
} catch (error) {
|
| 116 |
if (selection !== state.selection) return;
|
| 117 |
ui.status.textContent = `${error.message} ${state.image ? 'Your previous image remains selected.' : 'Try another image.'}`;
|
|
@@ -149,69 +179,178 @@ function renderExamples(initial = false) {
|
|
| 149 |
refreshControls();
|
| 150 |
}
|
| 151 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
function finishRun() {
|
| 153 |
-
|
| 154 |
-
state.
|
|
|
|
|
|
|
|
|
|
| 155 |
}
|
| 156 |
|
| 157 |
function stopWorker() {
|
| 158 |
worker?.terminate(); worker = null;
|
| 159 |
}
|
| 160 |
|
| 161 |
-
function
|
| 162 |
-
|
| 163 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
}
|
| 165 |
|
| 166 |
function getWorker() {
|
| 167 |
if (worker) return worker;
|
| 168 |
worker = new Worker(new URL('./caption-worker.js', import.meta.url), { type: 'module' });
|
| 169 |
-
worker.onerror = event =>
|
| 170 |
-
worker.onmessageerror = () =>
|
| 171 |
worker.onmessage = ({ data }) => {
|
| 172 |
if (data.id !== state.request || !state.running) return;
|
| 173 |
-
if (data.type === 'progress') {
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
}
|
| 180 |
-
if (progress.phase === 'generate') {
|
| 181 |
-
badge('Generating', 'running'); ui['progress-wrap'].hidden = true;
|
| 182 |
-
ui.status.textContent = 'Generating the caption. You can stop this run if it takes too long.';
|
| 183 |
-
}
|
| 184 |
-
} else if (data.type === 'error') failRun(data.message);
|
| 185 |
-
else if (data.type === 'result') {
|
| 186 |
-
const { dataUrl, ...imageInfo } = state.image;
|
| 187 |
-
const result = { ...data.result, image: imageInfo, run: state.request, timestamp: new Date().toISOString() };
|
| 188 |
-
state.result = result; state.history.unshift(result); state.history = state.history.slice(0, 12);
|
| 189 |
-
ui.summary.textContent = result.caption;
|
| 190 |
-
ui['meta-model'].textContent = result.model; ui['meta-image'].textContent = imageInfo.label;
|
| 191 |
-
ui['meta-runtime'].textContent = `${result.generationSeconds.toFixed(1)}s`; ui['run-meta'].hidden = false;
|
| 192 |
-
renderHistory(); finishRun(); badge('Caption ready', 'ready');
|
| 193 |
-
ui.status.textContent = `Done. Loading: ${result.loadSeconds.toFixed(1)}s · generation: ${result.generationSeconds.toFixed(1)}s. Check the sentence against the image.`;
|
| 194 |
-
}
|
| 195 |
};
|
| 196 |
return worker;
|
| 197 |
}
|
| 198 |
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
if (!state.image || state.running || state.loadingImage) return;
|
| 201 |
-
let
|
| 202 |
-
try {
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
|
| 212 |
ui['stop-button'].addEventListener('click', () => {
|
| 213 |
-
|
| 214 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
});
|
| 216 |
ui['image-input'].addEventListener('change', () => {
|
| 217 |
const file = ui['image-input'].files?.[0]; if (file) selectImage(() => Promise.resolve(file), file.name);
|
|
@@ -219,24 +358,38 @@ ui['image-input'].addEventListener('change', () => {
|
|
| 219 |
ui['shuffle-examples'].addEventListener('click', () => {
|
| 220 |
renderExamples(); ui.status.textContent = state.image ? 'New examples shown. Your current image remains selected.' : 'Choose an example or upload your own image.';
|
| 221 |
});
|
| 222 |
-
ui['model-select'].addEventListener('change', () => {
|
| 223 |
-
modelControls(); resetResult(); badge('Model changed');
|
| 224 |
-
ui.status.textContent = 'Run the selected model on your image to compare descriptions.';
|
| 225 |
-
});
|
| 226 |
-
ui['detail-select'].addEventListener('change', () => { modelControls(); resetResult(); });
|
| 227 |
-
ui['max-tokens'].addEventListener('input', () => { ui['token-value'].value = ui['max-tokens'].value; resetResult(); });
|
| 228 |
-
ui.instruction.addEventListener('input', resetResult);
|
| 229 |
ui['clear-history'].addEventListener('click', () => { state.history = []; renderHistory(); });
|
| 230 |
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'));
|
| 231 |
-
ui['download-caption'].addEventListener('click', () => { if (state.result) downloadFile('caption.txt', state.result.caption + '\n', 'text/plain;charset=utf-8'); });
|
| 232 |
-
ui['copy-caption'].addEventListener('click', async () => {
|
| 233 |
-
if (!state.result) return;
|
| 234 |
-
try { await navigator.clipboard.writeText(state.result.caption); ui.status.textContent = 'Caption copied.'; }
|
| 235 |
-
catch { ui.status.textContent = 'Clipboard access is unavailable. Select the caption text or use Save caption.'; }
|
| 236 |
-
});
|
| 237 |
|
| 238 |
-
for (const
|
| 239 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
fetch('./examples/manifest.json').then(response => {
|
| 241 |
if (!response.ok) throw new Error('Example list unavailable'); return response.json();
|
| 242 |
}).then(examples => { state.examples = examples; renderExamples(true); }).catch(() => {
|
|
|
|
| 1 |
import { MODEL_OPTIONS, getModelOption, defaultInstruction, normalizeOptions } from './models.js';
|
| 2 |
|
| 3 |
+
const KEYS = MODEL_OPTIONS.map(model => model.key);
|
| 4 |
const $ = id => document.getElementById(id);
|
| 5 |
const ui = Object.fromEntries([
|
| 6 |
+
'image-input', 'instruction-smol', 'run-button', 'stop-button', 'status', 'runtime-badge',
|
|
|
|
| 7 |
'progress-wrap', 'progress-bar', 'sample-grid', 'shuffle-examples', 'preview-image', 'preview-wrap',
|
| 8 |
+
'image-source', 'history-body', 'clear-history', 'download-history',
|
|
|
|
| 9 |
].map(id => [id, $(id)]));
|
| 10 |
|
| 11 |
+
const panels = Object.fromEntries(KEYS.map(key => [key, document.querySelector(`.captioner-panel[data-model="${key}"]`)]));
|
| 12 |
+
const part = (key, role) => panels[key].querySelector(`[data-role="${role}"]`);
|
| 13 |
+
|
| 14 |
+
const state = {
|
| 15 |
+
image: null, running: false, loadingImage: false, selection: 0, request: 0,
|
| 16 |
+
history: [], results: {}, examples: [], visible: [], pending: null, activeModel: null, runCount: 0,
|
| 17 |
+
};
|
| 18 |
let worker = null;
|
| 19 |
let watchdog = null;
|
| 20 |
|
|
|
|
| 23 |
ui['runtime-badge'].className = `badge ${mode}`.trim();
|
| 24 |
}
|
| 25 |
|
| 26 |
+
function panelBadge(key, text, mode = '') {
|
| 27 |
+
const node = part(key, 'badge');
|
| 28 |
+
node.textContent = text;
|
| 29 |
+
node.className = `badge panel-badge ${mode}`.trim();
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
function refreshControls() {
|
| 33 |
const busy = state.running || state.loadingImage;
|
| 34 |
+
ui['image-input'].disabled = busy;
|
|
|
|
| 35 |
ui['shuffle-examples'].disabled = busy || !state.examples.length;
|
| 36 |
ui['run-button'].disabled = busy || !state.image;
|
| 37 |
ui['stop-button'].hidden = !state.running;
|
|
|
|
|
|
|
| 38 |
for (const button of ui['sample-grid'].querySelectorAll('button')) button.disabled = busy;
|
| 39 |
+
for (const key of KEYS) {
|
| 40 |
+
part(key, 'style').disabled = busy || key === 'vit';
|
| 41 |
+
part(key, 'tokens').disabled = busy;
|
| 42 |
+
part(key, 'copy').disabled = busy || !state.results[key];
|
| 43 |
+
part(key, 'save').disabled = busy || !state.results[key];
|
| 44 |
+
}
|
| 45 |
+
ui['instruction-smol'].disabled = busy;
|
| 46 |
}
|
| 47 |
|
| 48 |
+
function resetResults() {
|
| 49 |
+
state.results = {};
|
| 50 |
+
for (const key of KEYS) {
|
| 51 |
+
part(key, 'caption').textContent = 'No caption yet.';
|
| 52 |
+
part(key, 'caption').classList.remove('has-caption');
|
| 53 |
+
part(key, 'meta').hidden = true;
|
| 54 |
+
part(key, 'meta').textContent = '';
|
| 55 |
+
part(key, 'stale').hidden = true;
|
| 56 |
+
part(key, 'copy').disabled = true;
|
| 57 |
+
part(key, 'save').disabled = true;
|
| 58 |
+
panelBadge(key, 'Waiting');
|
| 59 |
+
}
|
| 60 |
refreshControls();
|
| 61 |
}
|
| 62 |
|
| 63 |
+
function markStale(key) {
|
| 64 |
+
if (state.results[key]) part(key, 'stale').hidden = false;
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
function readOptions(key) {
|
| 68 |
+
try {
|
| 69 |
+
return normalizeOptions({
|
| 70 |
+
modelKey: key,
|
| 71 |
+
style: part(key, 'style').value,
|
| 72 |
+
maxTokens: part(key, 'tokens').value,
|
| 73 |
+
instruction: key === 'smol' ? ui['instruction-smol'].value : '',
|
| 74 |
+
});
|
| 75 |
+
} catch (error) {
|
| 76 |
+
throw new Error(`${getModelOption(key).label}: ${error.message}`);
|
| 77 |
+
}
|
| 78 |
}
|
| 79 |
|
| 80 |
function downloadFile(filename, content, type) {
|
|
|
|
| 90 |
ui['history-body'].replaceChildren();
|
| 91 |
if (!state.history.length) {
|
| 92 |
const row = document.createElement('tr'); row.className = 'empty-row';
|
| 93 |
+
const cell = document.createElement('td'); cell.colSpan = 6; cell.textContent = 'Run the captioners on an image to start a comparison.';
|
| 94 |
row.append(cell); ui['history-body'].append(row); return;
|
| 95 |
}
|
| 96 |
for (const item of state.history) {
|
|
|
|
| 141 |
const selected = card.dataset.src === key;
|
| 142 |
card.classList.toggle('selected', selected); card.setAttribute('aria-pressed', String(selected));
|
| 143 |
}
|
| 144 |
+
resetResults(); badge('Image ready'); ui.status.textContent = `${label} is ready. Click Run all three captioners.`;
|
| 145 |
} catch (error) {
|
| 146 |
if (selection !== state.selection) return;
|
| 147 |
ui.status.textContent = `${error.message} ${state.image ? 'Your previous image remains selected.' : 'Try another image.'}`;
|
|
|
|
| 179 |
refreshControls();
|
| 180 |
}
|
| 181 |
|
| 182 |
+
function clearWatchdog() {
|
| 183 |
+
clearTimeout(watchdog);
|
| 184 |
+
watchdog = null;
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
function armWatchdog() {
|
| 188 |
+
clearWatchdog();
|
| 189 |
+
watchdog = setTimeout(() => {
|
| 190 |
+
const pending = state.pending; state.pending = null;
|
| 191 |
+
stopWorker();
|
| 192 |
+
pending?.reject(new Error('This captioner exceeded 10 minutes. Try a shorter output limit or another image.'));
|
| 193 |
+
}, 600000);
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
function finishRun() {
|
| 197 |
+
clearWatchdog();
|
| 198 |
+
state.pending = null;
|
| 199 |
+
state.running = false;
|
| 200 |
+
ui['progress-wrap'].hidden = true;
|
| 201 |
+
refreshControls();
|
| 202 |
}
|
| 203 |
|
| 204 |
function stopWorker() {
|
| 205 |
worker?.terminate(); worker = null;
|
| 206 |
}
|
| 207 |
|
| 208 |
+
function crashRun(message) {
|
| 209 |
+
const pending = state.pending; state.pending = null;
|
| 210 |
+
stopWorker();
|
| 211 |
+
state.running = false;
|
| 212 |
+
pending?.reject(new Error(message));
|
| 213 |
+
finishRun();
|
| 214 |
+
badge('Run failed', 'error');
|
| 215 |
+
ui.status.textContent = `The captioning worker stopped. ${message} Try again; cached files can be reused.`;
|
| 216 |
}
|
| 217 |
|
| 218 |
function getWorker() {
|
| 219 |
if (worker) return worker;
|
| 220 |
worker = new Worker(new URL('./caption-worker.js', import.meta.url), { type: 'module' });
|
| 221 |
+
worker.onerror = event => crashRun(event.message || 'The inference worker stopped.');
|
| 222 |
+
worker.onmessageerror = () => crashRun('The model result could not be read.');
|
| 223 |
worker.onmessage = ({ data }) => {
|
| 224 |
if (data.id !== state.request || !state.running) return;
|
| 225 |
+
if (data.type === 'progress') { showProgress(data.progress); return; }
|
| 226 |
+
const pending = state.pending;
|
| 227 |
+
if (!pending) return;
|
| 228 |
+
state.pending = null;
|
| 229 |
+
if (data.type === 'error') pending.reject(new Error(data.message));
|
| 230 |
+
else if (data.type === 'result') pending.resolve(data.result);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 231 |
};
|
| 232 |
return worker;
|
| 233 |
}
|
| 234 |
|
| 235 |
+
function showProgress(progress) {
|
| 236 |
+
const option = state.activeModel ? getModelOption(state.activeModel) : null;
|
| 237 |
+
const label = option?.label ?? 'The model';
|
| 238 |
+
if (progress.phase === 'library') {
|
| 239 |
+
ui.status.textContent = 'Loading the captioning library…';
|
| 240 |
+
} else if (progress.phase === 'download' && progress.file) {
|
| 241 |
+
ui.status.textContent = `Loading ${label}: ${progress.file}. The first run can take several minutes.`;
|
| 242 |
+
if (Number.isFinite(progress.progress)) ui['progress-bar'].style.width = `${Math.max(0, Math.min(100, progress.progress))}%`;
|
| 243 |
+
} else if (progress.phase === 'generate') {
|
| 244 |
+
if (state.activeModel) panelBadge(state.activeModel, 'Generating', 'running');
|
| 245 |
+
ui['progress-wrap'].hidden = true;
|
| 246 |
+
ui.status.textContent = `${label} is generating a caption…`;
|
| 247 |
+
}
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
function captionOne(key, options) {
|
| 251 |
+
return new Promise((resolve, reject) => {
|
| 252 |
+
state.pending = { key, resolve, reject };
|
| 253 |
+
try {
|
| 254 |
+
getWorker().postMessage({ type: 'caption', id: state.request, image: state.image.dataUrl, options });
|
| 255 |
+
} catch (error) {
|
| 256 |
+
state.pending = null;
|
| 257 |
+
reject(error);
|
| 258 |
+
}
|
| 259 |
+
});
|
| 260 |
+
}
|
| 261 |
+
|
| 262 |
+
function recordResult(key, result) {
|
| 263 |
+
state.results[key] = result;
|
| 264 |
+
const { dataUrl, ...imageInfo } = state.image;
|
| 265 |
+
const entry = { ...result, image: imageInfo, run: ++state.runCount, timestamp: new Date().toISOString() };
|
| 266 |
+
state.history.unshift(entry); state.history = state.history.slice(0, 12);
|
| 267 |
+
const caption = part(key, 'caption');
|
| 268 |
+
caption.textContent = result.caption;
|
| 269 |
+
caption.classList.add('has-caption');
|
| 270 |
+
const meta = part(key, 'meta');
|
| 271 |
+
meta.textContent = `Loading ${result.loadSeconds.toFixed(1)}s · Generating ${result.generationSeconds.toFixed(1)}s`;
|
| 272 |
+
meta.hidden = false;
|
| 273 |
+
part(key, 'stale').hidden = true;
|
| 274 |
+
panelBadge(key, 'Caption ready', 'ready');
|
| 275 |
+
renderHistory();
|
| 276 |
+
refreshControls();
|
| 277 |
+
}
|
| 278 |
+
|
| 279 |
+
async function runAll() {
|
| 280 |
if (!state.image || state.running || state.loadingImage) return;
|
| 281 |
+
let plan;
|
| 282 |
+
try {
|
| 283 |
+
plan = KEYS.map(key => ({ key, options: readOptions(key) }));
|
| 284 |
+
} catch (error) {
|
| 285 |
+
ui.status.textContent = error.message; badge('Check settings', 'error'); return;
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
state.running = true;
|
| 289 |
+
state.request += 1;
|
| 290 |
+
state.pending = null;
|
| 291 |
+
state.activeModel = null;
|
| 292 |
+
resetResults();
|
| 293 |
+
badge('Running captioners', 'running');
|
| 294 |
+
ui.status.textContent = 'Preparing the three captioners. The first run downloads model files.';
|
| 295 |
+
ui['progress-wrap'].hidden = false;
|
| 296 |
+
ui['progress-bar'].style.width = '0%';
|
| 297 |
+
|
| 298 |
+
let stopped = false;
|
| 299 |
+
try {
|
| 300 |
+
for (let index = 0; index < plan.length; index++) {
|
| 301 |
+
if (!state.running) { stopped = true; break; }
|
| 302 |
+
const { key, options } = plan[index];
|
| 303 |
+
const option = getModelOption(key);
|
| 304 |
+
state.activeModel = key;
|
| 305 |
+
panelBadge(key, 'Loading model', 'running');
|
| 306 |
+
part(key, 'caption').textContent = 'Waiting for this model…';
|
| 307 |
+
part(key, 'caption').classList.remove('has-caption');
|
| 308 |
+
ui['progress-wrap'].hidden = false;
|
| 309 |
+
ui['progress-bar'].style.width = '0%';
|
| 310 |
+
ui.status.textContent = `Loading ${option.label} (${index + 1} of ${plan.length})… The first run can take several minutes.`;
|
| 311 |
+
armWatchdog();
|
| 312 |
+
try {
|
| 313 |
+
const result = await captionOne(key, options);
|
| 314 |
+
clearWatchdog();
|
| 315 |
+
if (!state.running) { stopped = true; break; }
|
| 316 |
+
recordResult(key, result);
|
| 317 |
+
} catch (error) {
|
| 318 |
+
clearWatchdog();
|
| 319 |
+
if (!state.running) { stopped = true; break; }
|
| 320 |
+
panelBadge(key, 'Run failed', 'error');
|
| 321 |
+
part(key, 'caption').textContent = 'This captioner did not return a caption.';
|
| 322 |
+
ui.status.textContent = `${option.label}: ${error.message}`;
|
| 323 |
+
}
|
| 324 |
+
}
|
| 325 |
+
} finally {
|
| 326 |
+
if (!stopped) {
|
| 327 |
+
const completed = KEYS.filter(key => state.results[key]).length;
|
| 328 |
+
if (completed === KEYS.length) {
|
| 329 |
+
badge('All captions ready', 'ready');
|
| 330 |
+
ui.status.textContent = 'All three captions are ready. Compare objects, actions, and relationships against the image.';
|
| 331 |
+
} else {
|
| 332 |
+
badge('Finished with errors', 'error');
|
| 333 |
+
ui.status.textContent = `${completed} of ${KEYS.length} captions generated. Check the message above, then run again.`;
|
| 334 |
+
}
|
| 335 |
+
}
|
| 336 |
+
state.activeModel = null;
|
| 337 |
+
finishRun();
|
| 338 |
+
}
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
ui['run-button'].addEventListener('click', runAll);
|
| 342 |
|
| 343 |
ui['stop-button'].addEventListener('click', () => {
|
| 344 |
+
if (!state.running) return;
|
| 345 |
+
const pending = state.pending; state.pending = null;
|
| 346 |
+
const active = state.activeModel;
|
| 347 |
+
state.running = false;
|
| 348 |
+
stopWorker();
|
| 349 |
+
pending?.reject(new Error('Stopped by the user.'));
|
| 350 |
+
if (active) panelBadge(active, 'Stopped');
|
| 351 |
+
finishRun();
|
| 352 |
+
badge('Stopped');
|
| 353 |
+
ui.status.textContent = 'Run stopped. Finished captions are kept; run again to continue.';
|
| 354 |
});
|
| 355 |
ui['image-input'].addEventListener('change', () => {
|
| 356 |
const file = ui['image-input'].files?.[0]; if (file) selectImage(() => Promise.resolve(file), file.name);
|
|
|
|
| 358 |
ui['shuffle-examples'].addEventListener('click', () => {
|
| 359 |
renderExamples(); ui.status.textContent = state.image ? 'New examples shown. Your current image remains selected.' : 'Choose an example or upload your own image.';
|
| 360 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
ui['clear-history'].addEventListener('click', () => { state.history = []; renderHistory(); });
|
| 362 |
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'));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
|
| 364 |
+
for (const option of MODEL_OPTIONS) {
|
| 365 |
+
const optionPanel = panels[option.key];
|
| 366 |
+
optionPanel.querySelector('[data-role="title"]').textContent = option.label;
|
| 367 |
+
part(option.key, 'note').textContent = option.note;
|
| 368 |
+
part(option.key, 'detail').textContent = option.detailNote;
|
| 369 |
+
const tokens = part(option.key, 'tokens');
|
| 370 |
+
part(option.key, 'token-value').value = tokens.value;
|
| 371 |
+
tokens.addEventListener('input', () => { part(option.key, 'token-value').value = tokens.value; markStale(option.key); });
|
| 372 |
+
const style = part(option.key, 'style');
|
| 373 |
+
style.addEventListener('change', () => {
|
| 374 |
+
if (option.key === 'smol') ui['instruction-smol'].value = defaultInstruction(style.value);
|
| 375 |
+
markStale(option.key);
|
| 376 |
+
});
|
| 377 |
+
part(option.key, 'copy').addEventListener('click', async () => {
|
| 378 |
+
const result = state.results[option.key]; if (!result) return;
|
| 379 |
+
try { await navigator.clipboard.writeText(result.caption); ui.status.textContent = `${option.label} caption copied.`; }
|
| 380 |
+
catch { ui.status.textContent = 'Clipboard access is unavailable. Select the caption text or use Save caption.'; }
|
| 381 |
+
});
|
| 382 |
+
part(option.key, 'save').addEventListener('click', () => {
|
| 383 |
+
const result = state.results[option.key]; if (!result) return;
|
| 384 |
+
downloadFile(`${option.key}-caption.txt`, result.caption + '\n', 'text/plain;charset=utf-8');
|
| 385 |
+
});
|
| 386 |
+
}
|
| 387 |
+
ui['instruction-smol'].addEventListener('input', () => markStale('smol'));
|
| 388 |
+
|
| 389 |
+
part('vit', 'style').value = 'short';
|
| 390 |
+
ui['instruction-smol'].value = defaultInstruction('short');
|
| 391 |
+
renderHistory();
|
| 392 |
+
refreshControls();
|
| 393 |
fetch('./examples/manifest.json').then(response => {
|
| 394 |
if (!response.ok) throw new Error('Example list unavailable'); return response.json();
|
| 395 |
}).then(examples => { state.examples = examples; renderExamples(true); }).catch(() => {
|
captioner.js
CHANGED
|
@@ -1,85 +1,85 @@
|
|
| 1 |
-
import { getModelOption, normalizeOptions, TRANSFORMERS_VERSION } from './models.js';
|
| 2 |
-
|
| 3 |
-
let libraryPromise;
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
library
|
| 13 |
-
library.env.
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
const
|
| 38 |
-
const
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
return
|
| 43 |
-
}
|
| 44 |
-
|
| 45 |
-
export async function captionImage(imageUrl, options, report = () => {}) {
|
| 46 |
-
const config = normalizeOptions(options);
|
| 47 |
-
const option = getModelOption(config.modelKey);
|
| 48 |
-
const began = performance.now();
|
| 49 |
-
const engine = await loadCaptioner(option, report);
|
| 50 |
-
const loaded = performance.now();
|
| 51 |
-
report({ phase: 'generate' });
|
| 52 |
-
const generation = { max_new_tokens: config.maxTokens, do_sample: false, num_beams: 1 };
|
| 53 |
-
let text;
|
| 54 |
-
if (option.key === 'vit') {
|
| 55 |
-
const output = await engine.pipeline(imageUrl, generation);
|
| 56 |
-
text = output[0]?.generated_text;
|
| 57 |
-
} else {
|
| 58 |
-
const image = await engine.lib.RawImage.read(imageUrl);
|
| 59 |
-
if (option.key === 'florence') {
|
| 60 |
-
const prompts = engine.processor.construct_prompts(config.task);
|
| 61 |
-
const inputs = await engine.processor(image, prompts);
|
| 62 |
-
const ids = await engine.model.generate({ ...inputs, ...generation });
|
| 63 |
-
const raw = engine.processor.batch_decode(ids, { skip_special_tokens: false })[0];
|
| 64 |
-
const parsed = engine.processor.post_process_generation(raw, config.task, image.size);
|
| 65 |
-
text = parsed[config.task];
|
| 66 |
-
} else {
|
| 67 |
-
const messages = [{ role: 'user', content: [{ type: 'image' }, { type: 'text', text: config.instruction }] }];
|
| 68 |
-
const prompt = engine.processor.apply_chat_template(messages, { add_generation_prompt: true, tokenize: false });
|
| 69 |
-
const inputs = await engine.processor(prompt, image);
|
| 70 |
-
const ids = await engine.model.generate({ ...inputs, ...generation });
|
| 71 |
-
// Decoder-only output contains the input prompt; export only newly generated tokens.
|
| 72 |
-
const generated = ids.tolist()[0].slice(inputs.input_ids.dims[1]);
|
| 73 |
-
text = engine.processor.batch_decode([generated], { skip_special_tokens: true })[0];
|
| 74 |
-
}
|
| 75 |
-
}
|
| 76 |
-
if (typeof text !== 'string' || !text.trim()) throw new Error('The model returned an empty caption. Try another image or a higher token limit.');
|
| 77 |
-
const ended = performance.now();
|
| 78 |
-
return {
|
| 79 |
-
caption: text.trim(), model: option.label, modelId: option.modelId, revision: option.revision,
|
| 80 |
-
library: `Transformers.js ${TRANSFORMERS_VERSION}`, device: 'wasm', dtype: 'q8',
|
| 81 |
-
graphOptimization: option.key === 'vit' ? 'disabled' : 'default',
|
| 82 |
-
config, generation, loadSeconds: (loaded - began) / 1000,
|
| 83 |
-
generationSeconds: (ended - loaded) / 1000, totalSeconds: (ended - began) / 1000,
|
| 84 |
-
};
|
| 85 |
-
}
|
|
|
|
| 1 |
+
import { getModelOption, normalizeOptions, TRANSFORMERS_VERSION } from './models.js';
|
| 2 |
+
|
| 3 |
+
let libraryPromise;
|
| 4 |
+
// Keep every captioner loaded so the side-by-side view can rerun one column
|
| 5 |
+
// without re-initializing a model. Stopping the worker releases them all.
|
| 6 |
+
const captioners = new Map();
|
| 7 |
+
|
| 8 |
+
async function getLibrary() {
|
| 9 |
+
// Lazy loading keeps the page usable even when the model CDN cannot be reached.
|
| 10 |
+
libraryPromise ??= import('https://cdn.jsdelivr.net/npm/@huggingface/transformers@4.2.0')
|
| 11 |
+
.catch(error => { libraryPromise = null; throw error; });
|
| 12 |
+
const library = await libraryPromise;
|
| 13 |
+
library.env.allowLocalModels = false;
|
| 14 |
+
library.env.useBrowserCache = true;
|
| 15 |
+
library.env.backends.onnx.wasm.numThreads = 1;
|
| 16 |
+
return library;
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
async function loadCaptioner(option, report) {
|
| 20 |
+
if (captioners.has(option.key)) return captioners.get(option.key);
|
| 21 |
+
report({ phase: 'library' });
|
| 22 |
+
const lib = await getLibrary();
|
| 23 |
+
const settings = {
|
| 24 |
+
revision: option.revision, dtype: 'q8', device: 'wasm',
|
| 25 |
+
// The old ViT-GPT2 quantized decoder hits an ORT 1.26 QDQ optimizer error.
|
| 26 |
+
// Keep its original graph; other models use the default optimizer.
|
| 27 |
+
...(option.key === 'vit' ? { session_options: { graphOptimizationLevel: 'disabled' } } : {}),
|
| 28 |
+
progress_callback: progress => report({ phase: 'download', ...progress }),
|
| 29 |
+
};
|
| 30 |
+
let engine;
|
| 31 |
+
if (option.key === 'vit') {
|
| 32 |
+
const pipeline = await lib.pipeline('image-to-text', option.modelId, settings);
|
| 33 |
+
engine = { key: option.key, pipeline, lib };
|
| 34 |
+
} else {
|
| 35 |
+
// Load sequentially so a processor failure does not leave a large model allocated.
|
| 36 |
+
const processor = await lib.AutoProcessor.from_pretrained(option.modelId, { revision: option.revision });
|
| 37 |
+
const Model = option.key === 'florence' ? lib.Florence2ForConditionalGeneration : lib.AutoModelForImageTextToText;
|
| 38 |
+
const model = await Model.from_pretrained(option.modelId, settings);
|
| 39 |
+
engine = { key: option.key, processor, model, lib };
|
| 40 |
+
}
|
| 41 |
+
captioners.set(option.key, engine);
|
| 42 |
+
return engine;
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
export async function captionImage(imageUrl, options, report = () => {}) {
|
| 46 |
+
const config = normalizeOptions(options);
|
| 47 |
+
const option = getModelOption(config.modelKey);
|
| 48 |
+
const began = performance.now();
|
| 49 |
+
const engine = await loadCaptioner(option, report);
|
| 50 |
+
const loaded = performance.now();
|
| 51 |
+
report({ phase: 'generate' });
|
| 52 |
+
const generation = { max_new_tokens: config.maxTokens, do_sample: false, num_beams: 1 };
|
| 53 |
+
let text;
|
| 54 |
+
if (option.key === 'vit') {
|
| 55 |
+
const output = await engine.pipeline(imageUrl, generation);
|
| 56 |
+
text = output[0]?.generated_text;
|
| 57 |
+
} else {
|
| 58 |
+
const image = await engine.lib.RawImage.read(imageUrl);
|
| 59 |
+
if (option.key === 'florence') {
|
| 60 |
+
const prompts = engine.processor.construct_prompts(config.task);
|
| 61 |
+
const inputs = await engine.processor(image, prompts);
|
| 62 |
+
const ids = await engine.model.generate({ ...inputs, ...generation });
|
| 63 |
+
const raw = engine.processor.batch_decode(ids, { skip_special_tokens: false })[0];
|
| 64 |
+
const parsed = engine.processor.post_process_generation(raw, config.task, image.size);
|
| 65 |
+
text = parsed[config.task];
|
| 66 |
+
} else {
|
| 67 |
+
const messages = [{ role: 'user', content: [{ type: 'image' }, { type: 'text', text: config.instruction }] }];
|
| 68 |
+
const prompt = engine.processor.apply_chat_template(messages, { add_generation_prompt: true, tokenize: false });
|
| 69 |
+
const inputs = await engine.processor(prompt, image);
|
| 70 |
+
const ids = await engine.model.generate({ ...inputs, ...generation });
|
| 71 |
+
// Decoder-only output contains the input prompt; export only newly generated tokens.
|
| 72 |
+
const generated = ids.tolist()[0].slice(inputs.input_ids.dims[1]);
|
| 73 |
+
text = engine.processor.batch_decode([generated], { skip_special_tokens: true })[0];
|
| 74 |
+
}
|
| 75 |
+
}
|
| 76 |
+
if (typeof text !== 'string' || !text.trim()) throw new Error('The model returned an empty caption. Try another image or a higher token limit.');
|
| 77 |
+
const ended = performance.now();
|
| 78 |
+
return {
|
| 79 |
+
caption: text.trim(), model: option.label, modelId: option.modelId, revision: option.revision,
|
| 80 |
+
library: `Transformers.js ${TRANSFORMERS_VERSION}`, device: 'wasm', dtype: 'q8',
|
| 81 |
+
graphOptimization: option.key === 'vit' ? 'disabled' : 'default',
|
| 82 |
+
config, generation, loadSeconds: (loaded - began) / 1000,
|
| 83 |
+
generationSeconds: (ended - loaded) / 1000, totalSeconds: (ended - began) / 1000,
|
| 84 |
+
};
|
| 85 |
+
}
|
captioning.css
CHANGED
|
@@ -1,19 +1,86 @@
|
|
| 1 |
-
/* Caption-specific controls. The shared course style.css is unchanged. */
|
| 2 |
-
[hidden] { display: none !important; }
|
| 3 |
-
.token-controls { margin-top: 18px; }
|
| 4 |
-
#token-value { min-width: 48px; text-align: right; color: #334155; font-variant-numeric: tabular-nums; }
|
| 5 |
-
#max-tokens { width: 100%; margin-top: 13px; accent-color: #111827; }
|
| 6 |
-
.caption-output { font-size: 1.1rem; white-space: pre-wrap; overflow-wrap: anywhere; }
|
| 7 |
-
.caption-actions { display: flex; flex-wrap: wrap; gap: 10px; margin: 0 0 16px; }
|
| 8 |
-
.history-actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
| 9 |
-
.stop-button { width: 100%; margin-top: 10px; }
|
| 10 |
-
#image-source { font-size: .78rem; }
|
| 11 |
-
#image-source a { color: #52627a; }
|
| 12 |
-
#history-body td:nth-child(4) { min-width: 230px; line-height: 1.5; overflow-wrap: anywhere; }
|
| 13 |
-
button:focus-visible { outline: 3px solid #52627a; outline-offset: 3px; }
|
| 14 |
-
.guide-section { margin-top: 20px; padding: 24px; }
|
| 15 |
-
.guide-section h2 { margin-top: 0; }
|
| 16 |
-
.guide-section p, .guide-section li { color: #475569; line-height: 1.65; }
|
| 17 |
-
.guide-section code { overflow-wrap: anywhere; }
|
| 18 |
-
.guide-section a { color: #174f9e; }
|
| 19 |
-
.guide-section pre { padding: 16px; background: #f7f8fa; overflow-x: auto; border-radius: 12px; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* Caption-specific controls. The shared course style.css is unchanged. */
|
| 2 |
+
[hidden] { display: none !important; }
|
| 3 |
+
.token-controls { margin-top: 18px; }
|
| 4 |
+
#token-value { min-width: 48px; text-align: right; color: #334155; font-variant-numeric: tabular-nums; }
|
| 5 |
+
#max-tokens { width: 100%; margin-top: 13px; accent-color: #111827; }
|
| 6 |
+
.caption-output { font-size: 1.1rem; white-space: pre-wrap; overflow-wrap: anywhere; }
|
| 7 |
+
.caption-actions { display: flex; flex-wrap: wrap; gap: 10px; margin: 0 0 16px; }
|
| 8 |
+
.history-actions { display: flex; flex-wrap: wrap; gap: 8px; }
|
| 9 |
+
.stop-button { width: 100%; margin-top: 10px; }
|
| 10 |
+
#image-source { font-size: .78rem; }
|
| 11 |
+
#image-source a { color: #52627a; }
|
| 12 |
+
#history-body td:nth-child(4) { min-width: 230px; line-height: 1.5; overflow-wrap: anywhere; }
|
| 13 |
+
button:focus-visible { outline: 3px solid #52627a; outline-offset: 3px; }
|
| 14 |
+
.guide-section { margin-top: 20px; padding: 24px; }
|
| 15 |
+
.guide-section h2 { margin-top: 0; }
|
| 16 |
+
.guide-section p, .guide-section li { color: #475569; line-height: 1.65; }
|
| 17 |
+
.guide-section code { overflow-wrap: anywhere; }
|
| 18 |
+
.guide-section a { color: #174f9e; }
|
| 19 |
+
.guide-section pre { padding: 16px; background: #f7f8fa; overflow-x: auto; border-radius: 12px; }
|
| 20 |
+
|
| 21 |
+
/* Three captioners side by side under one shared image. */
|
| 22 |
+
.workspace { grid-template-columns: 1fr; }
|
| 23 |
+
.result { position: static; }
|
| 24 |
+
.controls .sample-grid { grid-template-columns: repeat(4, minmax(0, 1fr)); }
|
| 25 |
+
.file-input { max-width: 560px; }
|
| 26 |
+
#preview-wrap { min-height: 220px; }
|
| 27 |
+
#preview-image { max-height: 420px; }
|
| 28 |
+
|
| 29 |
+
.captioner-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px; margin-top: 18px; }
|
| 30 |
+
.captioner-panel {
|
| 31 |
+
display: flex;
|
| 32 |
+
flex-direction: column;
|
| 33 |
+
min-width: 0;
|
| 34 |
+
padding: 15px;
|
| 35 |
+
border: 1px solid #e0e5ed;
|
| 36 |
+
border-radius: 16px;
|
| 37 |
+
background: #fff;
|
| 38 |
+
}
|
| 39 |
+
.panel-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 8px; }
|
| 40 |
+
.panel-kicker { margin: 0 0 3px; color: #7a8595; font-size: .66rem; font-weight: 800; letter-spacing: .07em; text-transform: uppercase; }
|
| 41 |
+
.panel-title { margin: 0; font-size: 1.03rem; letter-spacing: -.01em; }
|
| 42 |
+
.panel-badge { padding: 5px 8px; font-size: .7rem; }
|
| 43 |
+
.panel-note { margin: 7px 0 10px; font-size: .78rem; line-height: 1.45; }
|
| 44 |
+
.panel-caption {
|
| 45 |
+
flex: none;
|
| 46 |
+
height: 170px;
|
| 47 |
+
overflow-y: auto;
|
| 48 |
+
margin: 0;
|
| 49 |
+
padding: 11px 12px;
|
| 50 |
+
border-radius: 11px;
|
| 51 |
+
background: #f7f8fa;
|
| 52 |
+
color: #52627a;
|
| 53 |
+
font-size: .92rem;
|
| 54 |
+
font-weight: 650;
|
| 55 |
+
line-height: 1.5;
|
| 56 |
+
white-space: pre-wrap;
|
| 57 |
+
overflow-wrap: anywhere;
|
| 58 |
+
}
|
| 59 |
+
.panel-caption.has-caption { color: #1f2937; }
|
| 60 |
+
.panel-meta { margin: 7px 0 0; color: #7a8595; font-size: .72rem; line-height: 1.4; }
|
| 61 |
+
.panel-actions { display: flex; flex-wrap: wrap; gap: 7px; margin: 9px 0 13px; }
|
| 62 |
+
.panel-actions .secondary-button { flex: 0 1 auto; margin-top: 0; padding: 6px 9px; font-size: .76rem; }
|
| 63 |
+
.captioner-panel .panel-options { padding-top: 13px; border-top: 1px solid #eceff4; }
|
| 64 |
+
.panel-options-title { margin: 0 0 8px; color: #52627a; font-size: .66rem; font-weight: 800; letter-spacing: .06em; text-transform: uppercase; }
|
| 65 |
+
.captioner-panel .control-label { font-size: .8rem; }
|
| 66 |
+
.captioner-panel .model-select { margin-top: 6px; padding: 8px 10px; font-size: .85rem; }
|
| 67 |
+
.captioner-panel .model-select:disabled { background: #f5f6f8; color: #667085; }
|
| 68 |
+
.captioner-panel .helper { margin-top: 5px; font-size: .74rem; line-height: 1.4; }
|
| 69 |
+
.captioner-panel .token-controls { margin-top: 13px; }
|
| 70 |
+
.captioner-panel .slider-row { gap: 8px; }
|
| 71 |
+
.captioner-panel .token-value { min-width: 32px; text-align: right; color: #334155; font-variant-numeric: tabular-nums; }
|
| 72 |
+
.captioner-panel .token-slider { width: 100%; margin-top: 9px; accent-color: #111827; }
|
| 73 |
+
.captioner-panel .clip-controls { margin-top: 13px; }
|
| 74 |
+
.captioner-panel textarea { margin-top: 6px; padding: 8px 9px; border-radius: 10px; font-size: .8rem; }
|
| 75 |
+
.panel-stale { color: #8a5a00; font-weight: 650; }
|
| 76 |
+
|
| 77 |
+
@media (max-width: 1000px) {
|
| 78 |
+
.captioner-grid { grid-template-columns: 1fr; }
|
| 79 |
+
.controls .sample-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
| 80 |
+
}
|
| 81 |
+
@media (max-width: 820px) {
|
| 82 |
+
#preview-image { max-height: 340px; }
|
| 83 |
+
}
|
| 84 |
+
@media (max-width: 520px) {
|
| 85 |
+
.captioner-panel { padding: 13px; }
|
| 86 |
+
}
|
how-to-start.html
CHANGED
|
@@ -1,13 +1,13 @@
|
|
| 1 |
-
<!doctype html>
|
| 2 |
-
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>How to Start · Image Captioning</title><link rel="stylesheet" href="./style.css"><link rel="stylesheet" href="./captioning.css"></head>
|
| 3 |
-
<body><main class="page-shell">
|
| 4 |
-
<nav class="guide-linkbar"><span>Image Captioning · Student guide</span><a href="./index.html">← Back to the demo</a></nav>
|
| 5 |
-
<header class="hero"><p class="eyebrow">Creative Technology · Build your own AI mini app</p><h1>How to Start</h1><p class="lede">Run a pretrained captioner, understand its output, and build one useful improvement.</p></header>
|
| 6 |
-
<section class="card guide-section"><h2>1. Explore the demo</h2><ol><li>Choose one of the example images or upload a PNG, JPEG, or WebP image.</li><li>
|
| 7 |
-
<section class="card guide-section"><h2>2. Change one thing</h2><p>Florence-2 supports short and detailed captioning tasks. SmolVLM accepts a description instruction. ViT-GPT2 produces a short caption without an instruction. The output-token limit is not a target word count.</p><p>Choose one experiment: compare models, change
|
| 8 |
-
<section class="card guide-section"><h2>3. Make your own Hugging Face Space</h2><ol><li>Sign in to Hugging Face and open this project's Space page.</li><li>Use the Space menu to duplicate it into your own account. Alternatively, create a new <strong>Static</strong> Space and upload this folder's files with their subfolders.</li><li>Keep <code>sdk: static</code> and <code>app_file: index.html</code> in the README metadata.</li><li>Wait for the Space to build, open its App tab, and test one example and one uploaded image.</li></ol><p>This project needs no API key, paid inference endpoint, or training job. Internet access is required to obtain the library and model files.</p></section>
|
| 9 |
-
<section class="card guide-section"><h2>4. Find the code that matters</h2><div class="table-wrap"><table><thead><tr><th>File</th><th>What to change</th></tr></thead><tbody><tr><td>index.html</td><td>The task explanation and page structure.</td></tr><tr><td>app.js</td><td>Image selection, result display, and comparison records.</td></tr><tr><td>models.js</td><td>Model IDs, pinned revisions, and task settings.</td></tr><tr><td>captioner.js</td><td>Load the model, prepare inputs, generate tokens, decode the caption.</td></tr><tr><td>caption-worker.js</td><td>Run inference separately so the page stays responsive.</td></tr><tr><td>examples/</td><td>Teaching images, manifest, and source records.</td></tr></tbody></table></div><p>When changing a model, check its Transformers.js support and input format. A Python model ID cannot always be substituted directly.</p></section>
|
| 10 |
-
<section class="card guide-section"><h2>5. Explain and submit</h2><ul><li>A working public Space URL and a short explanation of the app's purpose.</li><li>The model ID and an explanation of the image → features → text process.</li><li>At least one successful example and one difficult or incorrect description.</li><li>One controlled comparison with its images, settings, and unchanged generated captions.</li><li>Image sources and a note on limitations. Training a model is optional.</li></ul></section>
|
| 11 |
-
<section class="card guide-section"><h2>If something does not work</h2><p><strong>Model download fails:</strong> check access to Hugging Face and jsDelivr, then retry. The first run loads roughly a few hundred MB per model.</p><p><strong>Generation is slow:</strong> use a recent desktop browser, close memory-heavy tabs, choose a shorter output limit, or stop the run. Loading time is shown separately from generation time.</p><p><strong>The sentence is wrong:</strong> save the actual output and identify the unsupported detail. Try another model or a clearer image; a fluent sentence is not a guarantee of correctness.</p><p><strong>Local files do not load:</strong> serve the folder over HTTP instead of opening index.html with file://.</p><pre><code>python -m http.server 7860</code></pre><p>Open <code>http://localhost:7860</code>. Uploaded images are processed in your browser. They are not sent to an inference server.</p><p><a href="./examples/SOURCES.md">Example image sources</a> · <a href="https://huggingface.co/docs/transformers.js">Transformers.js documentation</a></p></section>
|
| 12 |
-
<footer>AI-Powered Image Captioning · Student guide</footer>
|
| 13 |
-
</main></body></html>
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>How to Start · Image Captioning</title><link rel="stylesheet" href="./style.css"><link rel="stylesheet" href="./captioning.css"></head>
|
| 3 |
+
<body><main class="page-shell">
|
| 4 |
+
<nav class="guide-linkbar"><span>Image Captioning · Student guide</span><a href="./index.html">← Back to the demo</a></nav>
|
| 5 |
+
<header class="hero"><p class="eyebrow">Creative Technology · Build your own AI mini app</p><h1>How to Start</h1><p class="lede">Run a pretrained captioner, understand its output, and build one useful improvement.</p></header>
|
| 6 |
+
<section class="card guide-section"><h2>1. Explore the demo</h2><ol><li>Choose one of the example images or upload a PNG, JPEG, or WebP image.</li><li>Select <strong>Run all three captioners</strong>. One image is shared, so the three descriptions appear side by side.</li><li>Allow time for the first model downloads. Subsequent runs can reuse cached files. Use <strong>Stop this run</strong> if needed.</li><li>Read each caption and check its objects, actions, and relationships against the image.</li><li>Each captioner has its own options below its result. Change one option, run again, and compare the actual sentences in the log.</li></ol></section>
|
| 7 |
+
<section class="card guide-section"><h2>2. Change one thing</h2><p>Florence-2 supports short and detailed captioning tasks. SmolVLM accepts a description instruction. ViT-GPT2 produces a short caption without an instruction. These options sit below each captioner's result, so you can change one column without changing the others. The output-token limit is not a target word count.</p><p>Choose one experiment: compare the three models, change one model's requested detail, or crop an image. Record both successes and failures. Download the comparison log before reloading the page.</p></section>
|
| 8 |
+
<section class="card guide-section"><h2>3. Make your own Hugging Face Space</h2><ol><li>Sign in to Hugging Face and open this project's Space page.</li><li>Use the Space menu to duplicate it into your own account. Alternatively, create a new <strong>Static</strong> Space and upload this folder's files with their subfolders.</li><li>Keep <code>sdk: static</code> and <code>app_file: index.html</code> in the README metadata.</li><li>Wait for the Space to build, open its App tab, and test one example and one uploaded image.</li></ol><p>This project needs no API key, paid inference endpoint, or training job. Internet access is required to obtain the library and model files.</p></section>
|
| 9 |
+
<section class="card guide-section"><h2>4. Find the code that matters</h2><div class="table-wrap"><table><thead><tr><th>File</th><th>What to change</th></tr></thead><tbody><tr><td>index.html</td><td>The task explanation and page structure.</td></tr><tr><td>app.js</td><td>Image selection, result display, and comparison records.</td></tr><tr><td>models.js</td><td>Model IDs, pinned revisions, and task settings.</td></tr><tr><td>captioner.js</td><td>Load the model, prepare inputs, generate tokens, decode the caption.</td></tr><tr><td>caption-worker.js</td><td>Run inference separately so the page stays responsive.</td></tr><tr><td>examples/</td><td>Teaching images, manifest, and source records.</td></tr></tbody></table></div><p>When changing a model, check its Transformers.js support and input format. A Python model ID cannot always be substituted directly.</p></section>
|
| 10 |
+
<section class="card guide-section"><h2>5. Explain and submit</h2><ul><li>A working public Space URL and a short explanation of the app's purpose.</li><li>The model ID and an explanation of the image → features → text process.</li><li>At least one successful example and one difficult or incorrect description.</li><li>One controlled comparison with its images, settings, and unchanged generated captions.</li><li>Image sources and a note on limitations. Training a model is optional.</li></ul></section>
|
| 11 |
+
<section class="card guide-section"><h2>If something does not work</h2><p><strong>Model download fails:</strong> check access to Hugging Face and jsDelivr, then retry. The first run loads roughly a few hundred MB per model.</p><p><strong>Generation is slow:</strong> use a recent desktop browser, close memory-heavy tabs, choose a shorter output limit, or stop the run. Loading time is shown separately from generation time.</p><p><strong>The sentence is wrong:</strong> save the actual output and identify the unsupported detail. Try another model or a clearer image; a fluent sentence is not a guarantee of correctness.</p><p><strong>Local files do not load:</strong> serve the folder over HTTP instead of opening index.html with file://.</p><pre><code>python -m http.server 7860</code></pre><p>Open <code>http://localhost:7860</code>. Uploaded images are processed in your browser. They are not sent to an inference server.</p><p><a href="./examples/SOURCES.md">Example image sources</a> · <a href="https://huggingface.co/docs/transformers.js">Transformers.js documentation</a></p></section>
|
| 12 |
+
<footer>AI-Powered Image Captioning · Student guide</footer>
|
| 13 |
+
</main></body></html>
|
index.html
CHANGED
|
@@ -3,7 +3,7 @@
|
|
| 3 |
<head>
|
| 4 |
<meta charset="utf-8">
|
| 5 |
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
-
<meta name="description" content="An image captioning mini-lab
|
| 7 |
<title>AI-Powered Image Captioning</title>
|
| 8 |
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🖼️</text></svg>">
|
| 9 |
<link rel="stylesheet" href="./style.css">
|
|
@@ -18,10 +18,10 @@
|
|
| 18 |
<header class="hero">
|
| 19 |
<p class="eyebrow">Creative Technology · Computer Vision</p>
|
| 20 |
<h1>AI-Powered Image Captioning</h1>
|
| 21 |
-
<p class="lede">Choose an example or upload your own image
|
| 22 |
<div class="lesson-strip" aria-label="Mini-lab overview">
|
| 23 |
<span><b>Task</b> Image captioning</span>
|
| 24 |
-
<span><b>Output</b>
|
| 25 |
<span><b>Models</b> ViT-GPT2 · Florence-2 · SmolVLM</span>
|
| 26 |
</div>
|
| 27 |
</header>
|
|
@@ -42,46 +42,112 @@
|
|
| 42 |
<input id="image-input" class="file-input" type="file" accept="image/png,image/jpeg,image/webp">
|
| 43 |
<div class="divider"></div>
|
| 44 |
<div class="step"><span class="step-number">2</span><div class="grow">
|
| 45 |
-
<
|
| 46 |
-
<
|
| 47 |
-
<p id="model-note" class="helper"></p>
|
| 48 |
</div></div>
|
| 49 |
-
<
|
| 50 |
-
<div class="step"><span class="step-number">3</span><div class="grow">
|
| 51 |
-
<label class="control-label" for="detail-select">Description style</label>
|
| 52 |
-
<select id="detail-select" class="model-select"><option value="short">Short caption</option><option value="detailed">Detailed description</option></select>
|
| 53 |
-
<p id="detail-note" class="helper"></p>
|
| 54 |
-
<div id="instruction-controls" class="clip-controls" hidden>
|
| 55 |
-
<label class="control-label" for="instruction">Description instruction</label>
|
| 56 |
-
<textarea id="instruction" rows="3" maxlength="400" spellcheck="false">Describe this image in one short sentence.</textarea>
|
| 57 |
-
<p class="helper">Keep the image fixed and change the instruction to compare.</p>
|
| 58 |
-
</div>
|
| 59 |
-
<div class="token-controls">
|
| 60 |
-
<div class="slider-row"><label class="control-label" for="max-tokens">Maximum new tokens</label><output id="token-value" for="max-tokens">64</output></div>
|
| 61 |
-
<input id="max-tokens" type="range" min="32" max="128" value="64" step="16">
|
| 62 |
-
<p class="helper">An output limit, not an exact word count. A low limit may cut a sentence short.</p>
|
| 63 |
-
</div>
|
| 64 |
-
</div></div>
|
| 65 |
-
<button id="run-button" class="run-button" type="button" disabled>Run AI Captioning</button>
|
| 66 |
<button id="stop-button" class="secondary-button stop-button" type="button" hidden>Stop this run</button>
|
| 67 |
<p id="status" class="status" role="status" aria-live="polite">Choose an example or upload your own image.</p>
|
| 68 |
<div id="progress-wrap" class="progress-wrap" hidden><div id="progress-bar" class="progress-bar"></div></div>
|
| 69 |
</div>
|
| 70 |
<div class="result card">
|
| 71 |
-
<div class="result-head"><div><p class="section-kicker">AI
|
| 72 |
<div id="preview-wrap" class="preview-wrap empty"><img id="preview-image" alt="Selected image"><p id="preview-placeholder">Choose an image first. It will appear here before captioning.</p></div>
|
| 73 |
<p id="image-source" class="helper" hidden></p>
|
| 74 |
-
<div id="
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
</div>
|
| 80 |
-
<div class="
|
| 81 |
-
<div class="table-wrap"><table><thead><tr><th>Check the description</th><th>Look for visual evidence</th></tr></thead><tbody>
|
| 82 |
<tr><td>Objects and attributes</td><td>Are the named objects and their details visible?</td></tr>
|
| 83 |
-
<tr><td>Actions and relationships</td><td>Does
|
| 84 |
-
<tr><td>Missing or added details</td><td>
|
| 85 |
</tbody></table></div>
|
| 86 |
</div>
|
| 87 |
</section>
|
|
@@ -89,12 +155,12 @@
|
|
| 89 |
<p class="section-kicker">What you are doing</p>
|
| 90 |
<h2 class="explain-title">Use a learned AI capability instead of rebuilding the traditional task from scratch.</h2>
|
| 91 |
<p class="explain-copy">A visual encoder represents the image. A language decoder generates a description. Different models may describe different details, and a fluent sentence can still be wrong.</p>
|
| 92 |
-
<div class="flow" aria-label="Image captioning flow"><span>
|
| 93 |
-
<p class="extension-note"><strong>Compare models:</strong>
|
| 94 |
</section>
|
| 95 |
<section class="history card" aria-labelledby="history-title">
|
| 96 |
-
<div class="history-head"><div><p class="section-kicker">Comparison log</p><h2 id="history-title" class="explain-title">Keep one image fixed and compare descriptions.</h2><p class="history-copy">The latest 12 successful
|
| 97 |
-
<div class="table-wrap"><table><thead><tr><th>Run</th><th>Image</th><th>Model</th><th>Caption</th><th>Style</th><th>Time</th></tr></thead><tbody id="history-body"><tr class="empty-row"><td colspan="6">Run
|
| 98 |
</section>
|
| 99 |
<footer>Hosted as a Hugging Face Static Space · Powered by Transformers.js</footer>
|
| 100 |
</main>
|
|
|
|
| 3 |
<head>
|
| 4 |
<meta charset="utf-8">
|
| 5 |
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 6 |
+
<meta name="description" content="An image captioning mini-lab comparing three pretrained Hugging Face models side by side.">
|
| 7 |
<title>AI-Powered Image Captioning</title>
|
| 8 |
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🖼️</text></svg>">
|
| 9 |
<link rel="stylesheet" href="./style.css">
|
|
|
|
| 18 |
<header class="hero">
|
| 19 |
<p class="eyebrow">Creative Technology · Computer Vision</p>
|
| 20 |
<h1>AI-Powered Image Captioning</h1>
|
| 21 |
+
<p class="lede">Choose an example or upload your own image, then run all three pretrained captioners and compare how each one answers: <strong>what is happening in this image?</strong></p>
|
| 22 |
<div class="lesson-strip" aria-label="Mini-lab overview">
|
| 23 |
<span><b>Task</b> Image captioning</span>
|
| 24 |
+
<span><b>Output</b> Three descriptions in English</span>
|
| 25 |
<span><b>Models</b> ViT-GPT2 · Florence-2 · SmolVLM</span>
|
| 26 |
</div>
|
| 27 |
</header>
|
|
|
|
| 42 |
<input id="image-input" class="file-input" type="file" accept="image/png,image/jpeg,image/webp">
|
| 43 |
<div class="divider"></div>
|
| 44 |
<div class="step"><span class="step-number">2</span><div class="grow">
|
| 45 |
+
<p class="control-label">Run all three captioners</p>
|
| 46 |
+
<p class="helper">They share the same image, so their descriptions can be compared directly. Each captioner keeps its own options below its result.</p>
|
|
|
|
| 47 |
</div></div>
|
| 48 |
+
<button id="run-button" class="run-button" type="button" disabled>Run all three captioners</button>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
<button id="stop-button" class="secondary-button stop-button" type="button" hidden>Stop this run</button>
|
| 50 |
<p id="status" class="status" role="status" aria-live="polite">Choose an example or upload your own image.</p>
|
| 51 |
<div id="progress-wrap" class="progress-wrap" hidden><div id="progress-bar" class="progress-bar"></div></div>
|
| 52 |
</div>
|
| 53 |
<div class="result card">
|
| 54 |
+
<div class="result-head"><div><p class="section-kicker">AI descriptions</p><h2>How does each model describe it?</h2></div><span id="runtime-badge" class="badge">Waiting</span></div>
|
| 55 |
<div id="preview-wrap" class="preview-wrap empty"><img id="preview-image" alt="Selected image"><p id="preview-placeholder">Choose an image first. It will appear here before captioning.</p></div>
|
| 56 |
<p id="image-source" class="helper" hidden></p>
|
| 57 |
+
<div id="captioner-grid" class="captioner-grid">
|
| 58 |
+
<article class="captioner-panel" data-model="vit" aria-labelledby="title-vit">
|
| 59 |
+
<div class="panel-head">
|
| 60 |
+
<div><p class="panel-kicker">Captioner 1</p><h3 id="title-vit" class="panel-title" data-role="title"></h3></div>
|
| 61 |
+
<span class="badge panel-badge" data-role="badge">Waiting</span>
|
| 62 |
+
</div>
|
| 63 |
+
<p class="panel-note helper" data-role="note"></p>
|
| 64 |
+
<div class="panel-caption" data-role="caption">No caption yet.</div>
|
| 65 |
+
<p class="panel-meta" data-role="meta" hidden></p>
|
| 66 |
+
<div class="panel-actions">
|
| 67 |
+
<button class="secondary-button" type="button" data-role="copy" disabled>Copy caption</button>
|
| 68 |
+
<button class="secondary-button" type="button" data-role="save" disabled>Save caption</button>
|
| 69 |
+
</div>
|
| 70 |
+
<div class="panel-options">
|
| 71 |
+
<p class="panel-options-title">Options for this captioner</p>
|
| 72 |
+
<label class="control-label" for="style-vit">Description style</label>
|
| 73 |
+
<select id="style-vit" class="model-select" data-role="style" disabled>
|
| 74 |
+
<option value="short">Short caption (fixed)</option>
|
| 75 |
+
</select>
|
| 76 |
+
<p class="helper" data-role="detail"></p>
|
| 77 |
+
<div class="token-controls">
|
| 78 |
+
<div class="slider-row"><label class="control-label" for="tokens-vit">Maximum new tokens</label><output class="token-value" data-role="token-value" for="tokens-vit">64</output></div>
|
| 79 |
+
<input id="tokens-vit" class="token-slider" data-role="tokens" type="range" min="32" max="128" value="64" step="16">
|
| 80 |
+
<p class="helper">An output limit, not an exact word count.</p>
|
| 81 |
+
</div>
|
| 82 |
+
<p class="panel-stale helper" data-role="stale" hidden>Settings changed — run again to update this caption.</p>
|
| 83 |
+
</div>
|
| 84 |
+
</article>
|
| 85 |
+
<article class="captioner-panel" data-model="florence" aria-labelledby="title-florence">
|
| 86 |
+
<div class="panel-head">
|
| 87 |
+
<div><p class="panel-kicker">Captioner 2</p><h3 id="title-florence" class="panel-title" data-role="title"></h3></div>
|
| 88 |
+
<span class="badge panel-badge" data-role="badge">Waiting</span>
|
| 89 |
+
</div>
|
| 90 |
+
<p class="panel-note helper" data-role="note"></p>
|
| 91 |
+
<div class="panel-caption" data-role="caption">No caption yet.</div>
|
| 92 |
+
<p class="panel-meta" data-role="meta" hidden></p>
|
| 93 |
+
<div class="panel-actions">
|
| 94 |
+
<button class="secondary-button" type="button" data-role="copy" disabled>Copy caption</button>
|
| 95 |
+
<button class="secondary-button" type="button" data-role="save" disabled>Save caption</button>
|
| 96 |
+
</div>
|
| 97 |
+
<div class="panel-options">
|
| 98 |
+
<p class="panel-options-title">Options for this captioner</p>
|
| 99 |
+
<label class="control-label" for="style-florence">Description style</label>
|
| 100 |
+
<select id="style-florence" class="model-select" data-role="style">
|
| 101 |
+
<option value="short">Short caption</option>
|
| 102 |
+
<option value="detailed">Detailed description</option>
|
| 103 |
+
</select>
|
| 104 |
+
<p class="helper" data-role="detail"></p>
|
| 105 |
+
<div class="token-controls">
|
| 106 |
+
<div class="slider-row"><label class="control-label" for="tokens-florence">Maximum new tokens</label><output class="token-value" data-role="token-value" for="tokens-florence">64</output></div>
|
| 107 |
+
<input id="tokens-florence" class="token-slider" data-role="tokens" type="range" min="32" max="128" value="64" step="16">
|
| 108 |
+
<p class="helper">An output limit, not an exact word count.</p>
|
| 109 |
+
</div>
|
| 110 |
+
<p class="panel-stale helper" data-role="stale" hidden>Settings changed — run again to update this caption.</p>
|
| 111 |
+
</div>
|
| 112 |
+
</article>
|
| 113 |
+
<article class="captioner-panel" data-model="smol" aria-labelledby="title-smol">
|
| 114 |
+
<div class="panel-head">
|
| 115 |
+
<div><p class="panel-kicker">Captioner 3</p><h3 id="title-smol" class="panel-title" data-role="title"></h3></div>
|
| 116 |
+
<span class="badge panel-badge" data-role="badge">Waiting</span>
|
| 117 |
+
</div>
|
| 118 |
+
<p class="panel-note helper" data-role="note"></p>
|
| 119 |
+
<div class="panel-caption" data-role="caption">No caption yet.</div>
|
| 120 |
+
<p class="panel-meta" data-role="meta" hidden></p>
|
| 121 |
+
<div class="panel-actions">
|
| 122 |
+
<button class="secondary-button" type="button" data-role="copy" disabled>Copy caption</button>
|
| 123 |
+
<button class="secondary-button" type="button" data-role="save" disabled>Save caption</button>
|
| 124 |
+
</div>
|
| 125 |
+
<div class="panel-options">
|
| 126 |
+
<p class="panel-options-title">Options for this captioner</p>
|
| 127 |
+
<label class="control-label" for="style-smol">Description style</label>
|
| 128 |
+
<select id="style-smol" class="model-select" data-role="style">
|
| 129 |
+
<option value="short">Short caption</option>
|
| 130 |
+
<option value="detailed">Detailed description</option>
|
| 131 |
+
</select>
|
| 132 |
+
<p class="helper" data-role="detail"></p>
|
| 133 |
+
<div class="clip-controls">
|
| 134 |
+
<label class="control-label" for="instruction-smol">Description instruction</label>
|
| 135 |
+
<textarea id="instruction-smol" rows="3" maxlength="400" spellcheck="false">Describe this image in one short sentence.</textarea>
|
| 136 |
+
<p class="helper">Keep the image fixed and change the instruction to compare.</p>
|
| 137 |
+
</div>
|
| 138 |
+
<div class="token-controls">
|
| 139 |
+
<div class="slider-row"><label class="control-label" for="tokens-smol">Maximum new tokens</label><output class="token-value" data-role="token-value" for="tokens-smol">64</output></div>
|
| 140 |
+
<input id="tokens-smol" class="token-slider" data-role="tokens" type="range" min="32" max="128" value="64" step="16">
|
| 141 |
+
<p class="helper">An output limit, not an exact word count.</p>
|
| 142 |
+
</div>
|
| 143 |
+
<p class="panel-stale helper" data-role="stale" hidden>Settings changed — run again to update this caption.</p>
|
| 144 |
+
</div>
|
| 145 |
+
</article>
|
| 146 |
</div>
|
| 147 |
+
<div class="table-wrap"><table><thead><tr><th>Check the descriptions</th><th>Look for visual evidence</th></tr></thead><tbody>
|
|
|
|
| 148 |
<tr><td>Objects and attributes</td><td>Are the named objects and their details visible?</td></tr>
|
| 149 |
+
<tr><td>Actions and relationships</td><td>Does each sentence explain what is actually happening?</td></tr>
|
| 150 |
+
<tr><td>Missing or added details</td><td>Which model omits something? Which adds details without evidence?</td></tr>
|
| 151 |
</tbody></table></div>
|
| 152 |
</div>
|
| 153 |
</section>
|
|
|
|
| 155 |
<p class="section-kicker">What you are doing</p>
|
| 156 |
<h2 class="explain-title">Use a learned AI capability instead of rebuilding the traditional task from scratch.</h2>
|
| 157 |
<p class="explain-copy">A visual encoder represents the image. A language decoder generates a description. Different models may describe different details, and a fluent sentence can still be wrong.</p>
|
| 158 |
+
<div class="flow" aria-label="Image captioning flow"><span>One example or your image</span><span class="arrow">→</span><span>Three pretrained captioners, side by side</span><span class="arrow">→</span><span>Three descriptions in words</span></div>
|
| 159 |
+
<p class="extension-note"><strong>Compare models:</strong> all three see the same image. Check which objects, actions, and relationships each sentence captures—or invents—and adjust one captioner's options to test a controlled change.</p>
|
| 160 |
</section>
|
| 161 |
<section class="history card" aria-labelledby="history-title">
|
| 162 |
+
<div class="history-head"><div><p class="section-kicker">Comparison log</p><h2 id="history-title" class="explain-title">Keep one image fixed and compare descriptions.</h2><p class="history-copy">The latest 12 successful captions stay here until you clear the log or reload. Generation time excludes model loading; download the log to keep the full settings.</p></div><div class="history-actions"><button id="download-history" class="secondary-button" disabled>Download log</button><button id="clear-history" class="secondary-button" disabled>Clear log</button></div></div>
|
| 163 |
+
<div class="table-wrap"><table><thead><tr><th>Run</th><th>Image</th><th>Model</th><th>Caption</th><th>Style</th><th>Time</th></tr></thead><tbody id="history-body"><tr class="empty-row"><td colspan="6">Run the captioners on an image to start a comparison.</td></tr></tbody></table></div>
|
| 164 |
</section>
|
| 165 |
<footer>Hosted as a Hugging Face Static Space · Powered by Transformers.js</footer>
|
| 166 |
</main>
|