File size: 11,391 Bytes
2666ddd |
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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 |
<br><br>
<!-- Save as: teachable-machine-widget.html -->
<div class="teachable-machine-widget w-full max-w-2xl mx-auto my-8 font-sans bg-zinc-950 text-zinc-100 rounded-2xl overflow-hidden border border-zinc-800 shadow-2xl">
<!-- Dependencies (Load these in your main page <head> if possible) -->
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.22.0/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet@2.1.1"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/knn-classifier@1.2.6"></script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
body {
background-color: black;
}
/* Scoped styles for the widget */
.teachable-machine-widget { font-family: 'Inter', sans-serif; }
.teachable-machine-widget button { touch-action: manipulation; user-select: none; -webkit-user-select: none; }
.tm-pulse { animation: tm-pulse-ring 1.5s cubic-bezier(0.24, 0, 0.38, 1) infinite; }
@keyframes tm-pulse-ring {
0% { box-shadow: 0 0 0 0 rgba(255, 255, 255, 0.2); }
70% { box-shadow: 0 0 0 6px rgba(255, 255, 255, 0); }
100% { box-shadow: 0 0 0 0 rgba(255, 255, 255, 0); }
}
</style>
<!-- Widget Header -->
<div class="px-5 py-4 bg-zinc-900 border-b border-zinc-800 flex items-center justify-between">
<div class="flex items-center gap-3">
<div class="w-3 h-3 rounded-full bg-indigo-500 shadow-[0_0_10px_rgba(99,102,241,0.5)]"></div>
<h2 class="text-sm font-semibold tracking-wide text-zinc-200 uppercase">Teachable Machine</h2>
</div>
<div id="tm-status-badge" class="flex items-center gap-2 px-2 py-1 bg-zinc-950 rounded text-[10px] font-medium text-zinc-500 border border-zinc-800">
<span class="w-1.5 h-1.5 rounded-full bg-zinc-600"></span>
<span id="tm-status-text">Loading...</span>
</div>
</div>
<!-- Main Content Area -->
<div class="p-5 bg-zinc-950/50">
<!-- Video & Prediction Overlay Wrapper -->
<div class="relative rounded-xl overflow-hidden bg-black border border-zinc-800 aspect-video shadow-inner">
<video id="tm-webcam" class="w-full h-full object-cover transform scale-x-[-1]" autoplay playsinline muted></video>
<!-- Prediction Overlay (Bottom of video) -->
<div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/90 to-transparent pt-12 pb-3 px-4 flex items-end justify-between">
<div>
<div class="text-[10px] text-zinc-400 uppercase tracking-wider mb-0.5">I see</div>
<div id="tm-result" class="text-xl font-bold text-white leading-none">...</div>
</div>
<div class="text-right">
<div class="text-[10px] text-zinc-400 uppercase tracking-wider mb-1">Confidence</div>
<div class="w-24 h-1.5 bg-zinc-800 rounded-full overflow-hidden">
<div id="tm-conf-bar" class="h-full bg-indigo-500 w-0 transition-all duration-300"></div>
</div>
</div>
</div>
</div>
<!-- Controls Compact Grid -->
<div class="mt-4 grid grid-cols-3 gap-3">
<!-- Button A -->
<button id="tm-btn-a" class="group relative flex flex-col items-center justify-center p-3 rounded-xl bg-zinc-900 border border-zinc-800 hover:border-red-500/50 hover:bg-zinc-800 transition-all active:scale-[0.98]">
<div class="absolute inset-0 rounded-xl border-2 border-transparent group-hover:border-red-500/20 pointer-events-none"></div>
<div class="mb-1 text-xs font-medium text-red-400">Class A</div>
<div class="text-[10px] text-zinc-500">Red Object</div>
<div class="mt-2 px-2 py-0.5 bg-zinc-950 rounded text-[10px] text-zinc-300 font-mono border border-zinc-800">
<span id="tm-count-a">0</span> samples
</div>
</button>
<!-- Button B -->
<button id="tm-btn-b" class="group relative flex flex-col items-center justify-center p-3 rounded-xl bg-zinc-900 border border-zinc-800 hover:border-blue-500/50 hover:bg-zinc-800 transition-all active:scale-[0.98]">
<div class="absolute inset-0 rounded-xl border-2 border-transparent group-hover:border-blue-500/20 pointer-events-none"></div>
<div class="mb-1 text-xs font-medium text-blue-400">Class B</div>
<div class="text-[10px] text-zinc-500">Blue Object</div>
<div class="mt-2 px-2 py-0.5 bg-zinc-950 rounded text-[10px] text-zinc-300 font-mono border border-zinc-800">
<span id="tm-count-b">0</span> samples
</div>
</button>
<!-- Button Idle -->
<button id="tm-btn-i" class="group relative flex flex-col items-center justify-center p-3 rounded-xl bg-zinc-900 border border-zinc-800 hover:border-zinc-500/50 hover:bg-zinc-800 transition-all active:scale-[0.98]">
<div class="absolute inset-0 rounded-xl border-2 border-transparent group-hover:border-zinc-500/20 pointer-events-none"></div>
<div class="mb-1 text-xs font-medium text-zinc-400">Background</div>
<div class="text-[10px] text-zinc-500">Idle</div>
<div class="mt-2 px-2 py-0.5 bg-zinc-950 rounded text-[10px] text-zinc-300 font-mono border border-zinc-800">
<span id="tm-count-i">0</span> samples
</div>
</button>
</div>
<!-- Footer / Reset -->
<div class="mt-4 flex items-center justify-between text-[10px] text-zinc-500">
<p>Hold buttons to train</p>
<button id="tm-reset-btn" class="hover:text-red-400 transition-colors underline decoration-zinc-800 hover:decoration-red-900">
Reset Data
</button>
</div>
</div>
<!-- Logic -->
<script>
(function() {
// Namespace variables to avoid conflicts if you have multiple scripts on the page
const TM_LABELS = ["Class A", "Class B", "Background"];
const TM_TOPK = 10;
let tmNet = null;
let tmKnn = null;
let tmIsTraining = false;
let tmTrainingClass = -1;
let tmPredicting = false;
// Elements
const get = (id) => document.getElementById(id);
const els = {
webcam: get('tm-webcam'),
statusText: get('tm-status-text'),
statusBadge: get('tm-status-badge'),
result: get('tm-result'),
confBar: get('tm-conf-bar'),
counts: [get('tm-count-a'), get('tm-count-b'), get('tm-count-i')],
btns: [get('tm-btn-a'), get('tm-btn-b'), get('tm-btn-i')],
reset: get('tm-reset-btn')
};
function setStatus(msg, type="neutral") {
els.statusText.textContent = msg;
if(type === 'ready') els.statusBadge.querySelector('span').className = "w-1.5 h-1.5 rounded-full bg-emerald-500 shadow-[0_0_8px_rgba(16,185,129,0.6)]";
else if(type === 'loading') els.statusBadge.querySelector('span').className = "w-1.5 h-1.5 rounded-full bg-amber-500 animate-pulse";
else els.statusBadge.querySelector('span').className = "w-1.5 h-1.5 rounded-full bg-zinc-600";
}
function updateUI(label, conf) {
if (!label || label === "—") {
els.result.textContent = "...";
els.result.className = "text-xl font-bold text-zinc-500 leading-none";
els.confBar.style.width = "0%";
return;
}
els.result.textContent = label;
let color = "text-white";
let barColor = "bg-indigo-500";
if(label === TM_LABELS[0]) { color = "text-red-400"; barColor = "bg-red-500"; }
if(label === TM_LABELS[1]) { color = "text-blue-400"; barColor = "bg-blue-500"; }
if(label === TM_LABELS[2]) { color = "text-zinc-400"; barColor = "bg-zinc-500"; }
els.result.className = `text-xl font-bold ${color} leading-none transition-colors duration-200`;
els.confBar.className = `h-full ${barColor} transition-all duration-200`;
els.confBar.style.width = `${conf}%`;
}
function updateCounts() {
const counts = tmKnn ? tmKnn.getClassExampleCount() : {};
els.counts.forEach((el, idx) => el.textContent = counts[idx] || 0);
}
async function init() {
try {
setStatus("Camera...", "loading");
// 1. Setup Webcam
const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: false });
els.webcam.srcObject = stream;
await new Promise(r => els.webcam.onloadedmetadata = () => r());
// 2. Load Models
setStatus("Models...", "loading");
tmKnn = knnClassifier.create();
tmNet = await mobilenet.load({ version: 2, alpha: 0.50 });
// 3. Setup Events
els.btns.forEach((btn, idx) => {
const start = (e) => {
if (e.cancelable) e.preventDefault();
tmIsTraining = true;
tmTrainingClass = idx;
btn.classList.add("tm-pulse", "border-white");
};
const stop = (e) => {
if (e.cancelable) e.preventDefault();
tmIsTraining = false;
tmTrainingClass = -1;
btn.classList.remove("tm-pulse", "border-white");
};
btn.addEventListener("mousedown", start);
btn.addEventListener("mouseup", stop);
btn.addEventListener("mouseleave", stop);
btn.addEventListener("touchstart", start, {passive:false});
btn.addEventListener("touchend", stop, {passive:false});
});
els.reset.addEventListener('click', () => {
if(tmKnn) tmKnn.clearAllClasses();
updateCounts();
updateUI(null, 0);
});
setStatus("Ready", "ready");
// 4. Loops
trainLoop();
predictLoop();
tmPredicting = true;
} catch (e) {
console.error(e);
setStatus("Error", "error");
}
}
async function trainLoop() {
while (true) {
if (tmIsTraining && tmTrainingClass !== -1) {
const img = tf.browser.fromPixels(els.webcam);
const activation = tmNet.infer(img, true);
tmKnn.addExample(activation, tmTrainingClass);
img.dispose();
activation.dispose();
updateCounts();
}
await new Promise(r => setTimeout(r, 70)); // Throttle training
}
}
async function predictLoop() {
while (true) {
if (tmPredicting && tmKnn.getNumClasses() > 0) {
const img = tf.browser.fromPixels(els.webcam);
const activation = tmNet.infer(img, true);
try {
const res = await tmKnn.predictClass(activation, TM_TOPK);
const label = TM_LABELS[res.classIndex];
const conf = res.confidences[res.classIndex] * 100;
updateUI(label, conf);
} catch(e) {}
img.dispose();
activation.dispose();
}
await tf.nextFrame();
}
}
init();
})();
</script>
</div>
|