Computer-Vision-Lab / make-model.html
YOUSEF2434's picture
Upload make-model.html
2666ddd verified
raw
history blame
11.4 kB
<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>