Model trained and environment fixed

This commit is contained in:
2026-05-26 15:47:05 +00:00
commit 69a874469c
12 changed files with 1392 additions and 0 deletions
+111
View File
@@ -0,0 +1,111 @@
// Configuración: Reemplaza esta URL con tu enlace de Teachable Machine
const URL = "./model/";
let model, webcam, labelContainer, maxPredictions;
let isStopped = false;
// Cargar el modelo e iniciar la cámara
async function init() {
document.getElementById("status").innerText = "Cargando modelo...";
document.getElementById("start-btn").disabled = true;
try {
const modelURL = URL + "model.json";
const metadataURL = URL + "metadata.json";
// Cargar el modelo
model = await tmImage.load(modelURL, metadataURL);
maxPredictions = model.getTotalClasses();
// Configurar la webcam
const flip = true; // girar la cámara
webcam = new tmImage.Webcam(300, 300, flip);
await webcam.setup(); // pedir permiso
await webcam.play();
window.requestAnimationFrame(loop);
// UI Updates
document.getElementById("webcam-container").appendChild(webcam.canvas);
labelContainer = document.getElementById("label-container");
document.getElementById("status").innerText = "Modelo cargado. Escaneando...";
document.getElementById("stop-btn").disabled = false;
loadHistory();
} catch (e) {
console.error(e);
document.getElementById("status").innerText = "Error al cargar. Asegúrate de que los archivos del modelo estén en public/model/";
document.getElementById("start-btn").disabled = false;
}
}
async function loop() {
if (isStopped) return;
webcam.update(); // actualizar frame de la webcam
await predict();
window.requestAnimationFrame(loop);
}
// Realizar predicción
async function predict() {
const prediction = await model.predict(webcam.canvas);
// Encontrar la predicción con mayor confianza
let highest = { className: "", probability: 0 };
for (let i = 0; i < maxPredictions; i++) {
if (prediction[i].probability > highest.probability) {
highest = prediction[i];
}
}
labelContainer.innerText = `${highest.className}: ${(highest.probability * 100).toFixed(2)}%`;
// Si la confianza es alta (> 90%), enviar al backend (cada 5 segundos para no saturar)
if (highest.probability > 0.90 && !window.lastSent) {
sendToBackend(highest.className, highest.probability);
window.lastSent = true;
setTimeout(() => window.lastSent = false, 5000);
}
}
// Enviar datos al Backend
async function sendToBackend(label, confidence) {
try {
const response = await fetch('/api/detections', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ label, confidence })
});
if (response.ok) {
console.log("Detección guardada en backend");
loadHistory();
}
} catch (error) {
console.error("Error al conectar con backend", error);
}
}
// Cargar historial del Backend
async function loadHistory() {
try {
const response = await fetch('/api/detections');
const data = await response.json();
const list = document.getElementById("history-list");
list.innerHTML = "";
data.reverse().slice(0, 10).forEach(item => {
const li = document.createElement("li");
const date = new Date(item.timestamp).toLocaleTimeString();
li.innerText = `[${date}] ${item.label} (${(item.confidence * 100).toFixed(1)}%)`;
list.appendChild(li);
});
} catch (error) {
console.error("Error cargando historial", error);
}
}
function stopWebcam() {
isStopped = true;
if (webcam) webcam.stop();
document.getElementById("status").innerText = "Cámara detenida.";
document.getElementById("stop-btn").disabled = true;
document.getElementById("start-btn").disabled = false;
}
+41
View File
@@ -0,0 +1,41 @@
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Clasificador de Aves - AI</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>Clasificador de Aves</h1>
<p class="subtitle">Desarrollado con Teachable Machine & TensorFlow.js</p>
<div class="main-content">
<div class="camera-section">
<div id="webcam-container"></div>
<div class="controls">
<button id="start-btn" onclick="init()">Iniciar Cámara</button>
<button id="stop-btn" onclick="stopWebcam()" disabled>Detener</button>
</div>
</div>
<div class="info-section">
<h2>Resultado</h2>
<div id="label-container"></div>
<div id="status">Esperando inicio...</div>
<div class="history-section">
<h3>Historial Reciente</h3>
<ul id="history-list"></ul>
</div>
</div>
</div>
</div>
<!-- Scripts de TensorFlow -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@teachablemachine/image@latest/dist/teachablemachine-image.min.js"></script>
<script src="app.js"></script>
</body>
</html>
+115
View File
@@ -0,0 +1,115 @@
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background-color: #f4f7f6;
margin: 0;
padding: 20px;
display: flex;
justify-content: center;
}
.container {
background: white;
padding: 30px;
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0,0,0,0.1);
max-width: 900px;
width: 100%;
}
h1 {
color: #2c3e50;
text-align: center;
margin-bottom: 5px;
}
.subtitle {
text-align: center;
color: #7f8c8d;
margin-bottom: 30px;
}
.main-content {
display: flex;
gap: 30px;
flex-wrap: wrap;
}
.camera-section, .info-section {
flex: 1;
min-width: 300px;
}
#webcam-container {
background: #000;
border-radius: 8px;
overflow: hidden;
height: 300px;
display: flex;
justify-content: center;
align-items: center;
}
.controls {
margin-top: 15px;
display: flex;
gap: 10px;
}
button {
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
font-weight: bold;
transition: background 0.3s;
}
#start-btn {
background: #27ae60;
color: white;
flex: 2;
}
#start-btn:hover { background: #219150; }
#stop-btn {
background: #e74c3c;
color: white;
flex: 1;
}
#stop-btn:disabled { background: #bdc3c7; cursor: not-allowed; }
#label-container {
font-size: 1.5rem;
font-weight: bold;
color: #2980b9;
margin-bottom: 10px;
}
#status {
padding: 10px;
background: #ebf5fb;
border-radius: 5px;
color: #2c3e50;
margin-bottom: 20px;
}
.history-section h3 {
border-bottom: 2px solid #ecf0f1;
padding-bottom: 10px;
margin-top: 20px;
}
#history-list {
list-style: none;
padding: 0;
max-height: 200px;
overflow-y: auto;
}
#history-list li {
padding: 8px;
border-bottom: 1px solid #f1f1f1;
font-size: 0.9rem;
}