File size: 3,031 Bytes
d0ec19e af88696 d0ec19e af88696 d0ec19e af88696 d0ec19e af88696 d0ec19e af88696 d0ec19e af88696 d0ec19e af88696 d0ec19e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | <script type="module">
// Select UI elements
const progressContainer = document.getElementById('progress-container');
const progressBar = document.getElementById('progress-bar');
const progressText = document.getElementById('progress-text');
const output = document.getElementById('output');
const upload = document.getElementById('upload');
const preview = document.getElementById('preview');
const btn = document.getElementById('process-btn');
let classifier = null;
// The Function that loads the model
async function loadModel() {
try {
output.textContent = "Initializing WebGPU...";
progressContainer.style.display = 'block';
classifier = await window.Transformers.pipeline('image-classification', 'Xenova/vit-gpt2-image-captioning', {
device: 'webgpu',
progress_callback: (data) => {
if (data.status === 'progress') {
const pct = Math.round(data.progress);
progressBar.style.width = pct + '%';
progressText.textContent = `Downloading ${data.file}: ${pct}%`;
} else if (data.status === 'ready') {
progressText.textContent = "Model Loaded!";
setTimeout(() => progressContainer.style.display = 'none', 1500);
}
}
});
return true;
} catch (err) {
console.error(err);
output.textContent = "Error: " + err.message;
progressText.textContent = "WebGPU failed. Check browser compatibility.";
return false;
}
}
// Handle button click
btn.onclick = async () => {
// 1. Check if an image is selected
if (!upload.files[0]) {
alert("Please select an image first.");
return;
}
// 2. Load model if not already loaded
if (!classifier) {
const success = await loadModel();
if (!success) return;
}
// 3. Run Inference
try {
output.textContent = "Analyzing image... please wait.";
const result = await classifier(preview.src);
// Format the result nicely
if (result && result[0]) {
output.textContent = "I see: " + result[0].label;
} else {
output.textContent = "Analysis complete, but no label found.";
}
} catch (err) {
console.error("Inference Error:", err);
output.textContent = "Analysis failed: " + err.message;
}
};
// Update preview when file is picked
upload.onchange = (e) => {
const file = e.target.files[0];
if (file) {
preview.src = URL.createObjectURL(file);
preview.style.display = 'block';
output.textContent = "Image uploaded. Click Analyze.";
}
};
</script>
|