tplopoltay commited on
Commit
e6c1f9a
·
verified ·
1 Parent(s): 23e1faa

Create script.js

Browse files
Files changed (1) hide show
  1. script.js +247 -0
script.js ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ let model;
2
+ let webcamStream;
3
+ let privacyMode = false;
4
+ let isModelLoaded = false;
5
+ let detectionHistory = [];
6
+
7
+ // Load encrypted model
8
+ async function loadEncryptedModel() {
9
+ if (isModelLoaded) return;
10
+
11
+ try {
12
+ const modelJson = await decryptFile("/models/encrypted-model.json");
13
+ const weights = await decryptFile("/models/encrypted-weights.bin");
14
+
15
+ model = await tf.loadLayersModel(tf.io.fromMemory(modelJson, weights));
16
+ isModelLoaded = true;
17
+ console.log("Model loaded securely");
18
+ } catch (error) {
19
+ console.error("Model load failed:", error);
20
+ }
21
+ }
22
+
23
+ // Toggle privacy mode
24
+ function togglePrivacyMode() {
25
+ privacyMode = !privacyMode;
26
+ const btn = document.getElementById('privacyBtn');
27
+
28
+ if (privacyMode) {
29
+ // Turn off webcam
30
+ if (webcamStream) {
31
+ webcamStream.getTracks().forEach(track => track.stop());
32
+ webcamStream = null;
33
+ }
34
+
35
+ document.getElementById('webcam').srcObject = null;
36
+ btn.classList.add('active');
37
+ } else {
38
+ // Restart webcam
39
+ startWebcam();
40
+ btn.classList.remove('active');
41
+ }
42
+ }
43
+
44
+ // Start webcam
45
+ async function startWebcam() {
46
+ try {
47
+ const video = document.getElementById('webcam');
48
+ webcamStream = await navigator.mediaDevices.getUserMedia({ video: true });
49
+ video.srcObject = webcamStream;
50
+
51
+ return new Promise(resolve => {
52
+ video.onloadedmetadata = () => {
53
+ resolve();
54
+ if (!privacyMode) {
55
+ processFrame();
56
+ }
57
+ };
58
+ });
59
+ } catch (err) {
60
+ console.error("Webcam error:", err);
61
+ document.getElementById('results').innerHTML = "⚠️ Webcam access denied";
62
+ }
63
+ }
64
+
65
+ // Initialize app
66
+ async function init() {
67
+ await loadEncryptedModel();
68
+ await startWebcam();
69
+ }
70
+
71
+ // Process video frames
72
+ async function processFrame() {
73
+ if (privacyMode || !isModelLoaded) {
74
+ requestAnimationFrame(processFrame);
75
+ return;
76
+ }
77
+
78
+ try {
79
+ const video = document.getElementById('webcam');
80
+ const tensor = tf.tidy(() => {
81
+ const img = tf.browser.fromPixels(video);
82
+ return tf.image.resizeBilinear(img, [256, 256]).expandDims(0);
83
+ });
84
+
85
+ const predictions = model.predict(tensor);
86
+ const filtered = filterDetections(predictions);
87
+ drawResults(filtered);
88
+
89
+ } catch (error) {
90
+ console.error("Processing error:", error);
91
+ }
92
+
93
+ tf.dispose(tensor);
94
+ requestAnimationFrame(processFrame);
95
+ }
96
+
97
+ // Validate API key
98
+ function validateKey() {
99
+ const apiKey = document.getElementById('apiKey').value;
100
+ fetch('/api/validate', {
101
+ method: 'POST',
102
+ headers: {'Content-Type': 'application/json'},
103
+ body: JSON.stringify({key: apiKey})
104
+ })
105
+ .then(response => response.text())
106
+ .then(html => {
107
+ document.getElementById('login').style.display = 'none';
108
+ document.getElementById('app').style.display = 'block';
109
+ return init();
110
+ })
111
+ .catch(err => {
112
+ alert("Invalid API key");
113
+ console.error("Validation error:", err);
114
+ });
115
+ }
116
+
117
+ // Save detection
118
+ function saveDetection() {
119
+ if (privacyMode) return;
120
+
121
+ const video = document.getElementById('webcam');
122
+ const canvas = document.createElement('canvas');
123
+ canvas.width = video.videoWidth;
124
+ canvas.height = video.videoHeight;
125
+
126
+ const ctx = canvas.getContext('2d');
127
+ ctx.drawImage(video, 0, 0);
128
+
129
+ const dataUrl = canvas.toDataURL('image/png');
130
+
131
+ // Send to backend
132
+ fetch('/api/save', {
133
+ method: 'POST',
134
+ headers: {'Content-Type': 'application/json'},
135
+ body: JSON.stringify({image: dataUrl})
136
+ })
137
+ .then(response => response.json())
138
+ .then(result => {
139
+ // Add to history
140
+ detectionHistory.push({
141
+ filename: result.filename,
142
+ timestamp: new Date().toLocaleString()
143
+ });
144
+
145
+ // Save history
146
+ localStorage.setItem('detectionHistory', JSON.stringify(detectionHistory));
147
+
148
+ // Refresh history display
149
+ displayHistory();
150
+ });
151
+ }
152
+
153
+ // Delete detection
154
+ function deleteDetection(filename) {
155
+ fetch('/api/delete', {
156
+ method: 'POST',
157
+ headers: {'Content-Type': 'application/json'},
158
+ body: JSON.stringify({filename: filename})
159
+ })
160
+ .then(response => response.json())
161
+ .then(result => {
162
+ // Refresh history
163
+ detectionHistory = detectionHistory.filter(item => item.filename !== filename);
164
+ localStorage.setItem('detectionHistory', JSON.stringify(detectionHistory));
165
+
166
+ // Refresh display
167
+ displayHistory();
168
+ });
169
+ }
170
+
171
+ // Restore detection
172
+ function restoreDetection(filename) {
173
+ fetch('/api/restore', {
174
+ method: 'POST',
175
+ headers: {'Content-Type': 'application/json'},
176
+ body: JSON.stringify({filename: filename})
177
+ })
178
+ .then(response => response.json())
179
+ .then(result => {
180
+ // Refresh history
181
+ detectionHistory = detectionHistory.filter(item => item.filename !== filename);
182
+ detectionHistory.push({
183
+ filename: filename,
184
+ timestamp: new Date().toLocaleString()
185
+ });
186
+
187
+ localStorage.setItem('detectionHistory', JSON.stringify(detectionHistory));
188
+
189
+ // Refresh display
190
+ displayHistory();
191
+ });
192
+ }
193
+
194
+ // Load and display history
195
+ function displayHistory() {
196
+ fetch('/api/history')
197
+ .then(response => response.json())
198
+ .then(history => {
199
+ const localHistory = JSON.parse(localStorage.getItem('detectionHistory')) || [];
200
+ const combinedHistory = [...history, ...localHistory];
201
+
202
+ const container = document.getElementById('historyList');
203
+ container.innerHTML = "";
204
+
205
+ if (combinedHistory.length === 0) {
206
+ container.innerHTML = "<p>No detection history</p>";
207
+ return;
208
+ }
209
+
210
+ combinedHistory.forEach(item => {
211
+ container.innerHTML += `
212
+ <div class="history-item">
213
+ <p>📅 ${item.timestamp}</p>
214
+ <p>📷 ${item.filename}</p>
215
+ <button onclick="deleteDetection('${item.filename}')">🗑️ Delete</button>
216
+ <button class="restore" onclick="restoreDetection('${item.filename}')">↩️ Restore</button>
217
+ </div>`;
218
+ });
219
+ });
220
+ }
221
+
222
+ // Decrypt model files
223
+ async function decryptFile(url) {
224
+ const encryptedResponse = await fetch(url);
225
+ const arrayBuffer = await encryptedResponse.arrayBuffer();
226
+
227
+ const byteArray = new Uint8Array(arrayBuffer);
228
+ const iv = byteArray.slice(0, 12);
229
+ const data = byteArray.slice(12);
230
+
231
+ const password = new TextEncoder().encode("SECURE_MODEL_KEY_2023");
232
+
233
+ const key = await crypto.subtle.importKey(
234
+ "raw", password, { name: "AES-GCM" }, false, ["decrypt"]
235
+ );
236
+
237
+ const decrypted = await crypto.subtle.decrypt(
238
+ { name: "AES-GCM", iv }, key, data
239
+ );
240
+
241
+ return JSON.parse(new TextDecoder().decode(decrypted));
242
+ }
243
+
244
+ // Load history on page load
245
+ document.addEventListener('DOMContentLoaded', function() {
246
+ displayHistory();
247
+ });