Spaces:
Runtime error
Runtime error
File size: 7,292 Bytes
e6c1f9a | 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 | let model;
let webcamStream;
let privacyMode = false;
let isModelLoaded = false;
let detectionHistory = [];
// Load encrypted model
async function loadEncryptedModel() {
if (isModelLoaded) return;
try {
const modelJson = await decryptFile("/models/encrypted-model.json");
const weights = await decryptFile("/models/encrypted-weights.bin");
model = await tf.loadLayersModel(tf.io.fromMemory(modelJson, weights));
isModelLoaded = true;
console.log("Model loaded securely");
} catch (error) {
console.error("Model load failed:", error);
}
}
// Toggle privacy mode
function togglePrivacyMode() {
privacyMode = !privacyMode;
const btn = document.getElementById('privacyBtn');
if (privacyMode) {
// Turn off webcam
if (webcamStream) {
webcamStream.getTracks().forEach(track => track.stop());
webcamStream = null;
}
document.getElementById('webcam').srcObject = null;
btn.classList.add('active');
} else {
// Restart webcam
startWebcam();
btn.classList.remove('active');
}
}
// Start webcam
async function startWebcam() {
try {
const video = document.getElementById('webcam');
webcamStream = await navigator.mediaDevices.getUserMedia({ video: true });
video.srcObject = webcamStream;
return new Promise(resolve => {
video.onloadedmetadata = () => {
resolve();
if (!privacyMode) {
processFrame();
}
};
});
} catch (err) {
console.error("Webcam error:", err);
document.getElementById('results').innerHTML = "⚠️ Webcam access denied";
}
}
// Initialize app
async function init() {
await loadEncryptedModel();
await startWebcam();
}
// Process video frames
async function processFrame() {
if (privacyMode || !isModelLoaded) {
requestAnimationFrame(processFrame);
return;
}
try {
const video = document.getElementById('webcam');
const tensor = tf.tidy(() => {
const img = tf.browser.fromPixels(video);
return tf.image.resizeBilinear(img, [256, 256]).expandDims(0);
});
const predictions = model.predict(tensor);
const filtered = filterDetections(predictions);
drawResults(filtered);
} catch (error) {
console.error("Processing error:", error);
}
tf.dispose(tensor);
requestAnimationFrame(processFrame);
}
// Validate API key
function validateKey() {
const apiKey = document.getElementById('apiKey').value;
fetch('/api/validate', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({key: apiKey})
})
.then(response => response.text())
.then(html => {
document.getElementById('login').style.display = 'none';
document.getElementById('app').style.display = 'block';
return init();
})
.catch(err => {
alert("Invalid API key");
console.error("Validation error:", err);
});
}
// Save detection
function saveDetection() {
if (privacyMode) return;
const video = document.getElementById('webcam');
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0);
const dataUrl = canvas.toDataURL('image/png');
// Send to backend
fetch('/api/save', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({image: dataUrl})
})
.then(response => response.json())
.then(result => {
// Add to history
detectionHistory.push({
filename: result.filename,
timestamp: new Date().toLocaleString()
});
// Save history
localStorage.setItem('detectionHistory', JSON.stringify(detectionHistory));
// Refresh history display
displayHistory();
});
}
// Delete detection
function deleteDetection(filename) {
fetch('/api/delete', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({filename: filename})
})
.then(response => response.json())
.then(result => {
// Refresh history
detectionHistory = detectionHistory.filter(item => item.filename !== filename);
localStorage.setItem('detectionHistory', JSON.stringify(detectionHistory));
// Refresh display
displayHistory();
});
}
// Restore detection
function restoreDetection(filename) {
fetch('/api/restore', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({filename: filename})
})
.then(response => response.json())
.then(result => {
// Refresh history
detectionHistory = detectionHistory.filter(item => item.filename !== filename);
detectionHistory.push({
filename: filename,
timestamp: new Date().toLocaleString()
});
localStorage.setItem('detectionHistory', JSON.stringify(detectionHistory));
// Refresh display
displayHistory();
});
}
// Load and display history
function displayHistory() {
fetch('/api/history')
.then(response => response.json())
.then(history => {
const localHistory = JSON.parse(localStorage.getItem('detectionHistory')) || [];
const combinedHistory = [...history, ...localHistory];
const container = document.getElementById('historyList');
container.innerHTML = "";
if (combinedHistory.length === 0) {
container.innerHTML = "<p>No detection history</p>";
return;
}
combinedHistory.forEach(item => {
container.innerHTML += `
<div class="history-item">
<p>📅 ${item.timestamp}</p>
<p>📷 ${item.filename}</p>
<button onclick="deleteDetection('${item.filename}')">🗑️ Delete</button>
<button class="restore" onclick="restoreDetection('${item.filename}')">↩️ Restore</button>
</div>`;
});
});
}
// Decrypt model files
async function decryptFile(url) {
const encryptedResponse = await fetch(url);
const arrayBuffer = await encryptedResponse.arrayBuffer();
const byteArray = new Uint8Array(arrayBuffer);
const iv = byteArray.slice(0, 12);
const data = byteArray.slice(12);
const password = new TextEncoder().encode("SECURE_MODEL_KEY_2023");
const key = await crypto.subtle.importKey(
"raw", password, { name: "AES-GCM" }, false, ["decrypt"]
);
const decrypted = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv }, key, data
);
return JSON.parse(new TextDecoder().decode(decrypted));
}
// Load history on page load
document.addEventListener('DOMContentLoaded', function() {
displayHistory();
}); |