| <script type="module"> |
| |
| 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; |
|
|
| |
| 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; |
| } |
| } |
|
|
| |
| btn.onclick = async () => { |
| |
| if (!upload.files[0]) { |
| alert("Please select an image first."); |
| return; |
| } |
|
|
| |
| if (!classifier) { |
| const success = await loadModel(); |
| if (!success) return; |
| } |
|
|
| |
| try { |
| output.textContent = "Analyzing image... please wait."; |
| const result = await classifier(preview.src); |
| |
| |
| 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; |
| } |
| }; |
|
|
| |
| 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> |
|
|