Spaces:
Runtime error
Runtime error
Download script.js from opendeveloping/secure-object-detector: direct link, hf CLI and curl.
- Browser
- Download file 7.29 kB
-
https://huggingface.co/spaces/opendeveloping/secure-object-detector/resolve/main/script.js
- Command line
-
hf download hf://spaces/opendeveloping/secure-object-detector/script.js
-
curl -L -o script.js https://huggingface.co/spaces/opendeveloping/secure-object-detector/resolve/main/script.js
7.29 kB
| 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(); | |
| }); |