-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathghostati-tensorflow-478.html
More file actions
304 lines (259 loc) · 13.5 KB
/
ghostati-tensorflow-478.html
File metadata and controls
304 lines (259 loc) · 13.5 KB
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AR Adversarial Makeup & Biometrics</title>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.10.0"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/mobilenet@2.1.1"></script>
<style>
body { margin: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: #121212; color: #fff; display: flex; flex-direction: column; height: 100vh; overflow: hidden; }
header { padding: 15px 20px; background-color: #1a1a1a; border-bottom: 1px solid #333; text-align: center; z-index: 10; }
header h1 { margin: 0; font-size: 1.5rem; text-transform: uppercase; letter-spacing: 2px; }
header p { margin: 5px 0 0; font-size: 0.9rem; color: #aaa; }
.container { display: flex; flex: 1; height: calc(100vh - 70px); }
.col-comandi, .col-makeup { width: 16.666%; background-color: #222; padding: 20px; box-sizing: border-box; display: flex; flex-direction: column; gap: 12px; z-index: 10; }
.col-comandi { border-right: 1px solid #333; }
.col-makeup { border-left: 1px solid #333; }
.col-immagine { width: 66.666%; display: flex; flex-direction: column; position: relative; background-color: #000; overflow: hidden; }
.media-container { flex: 1; position: relative; display: flex; justify-content: center; align-items: center; }
video { display: none; /* Nascosto, usiamo il canvas per il rendering */ }
canvas { position: absolute; width: 100%; height: 100%; object-fit: cover; transform: scaleX(-1); /* Specchio */ }
.log-box { height: 60px; background-color: #111; color: #00ff00; font-family: monospace; display: flex; align-items: center; justify-content: center; border-top: 1px solid #333; font-size: 1rem; padding: 0 10px; text-align: center; z-index: 10; }
button { padding: 12px; background-color: #007acc; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 0.95rem; font-weight: 600; transition: 0.2s; text-transform: uppercase; }
button:hover { background-color: #005999; }
button:active { transform: scale(0.95); }
.makeup-btn { background-color: #9c27b0; }
.makeup-btn:hover { background-color: #7b1fa2; }
.active-btn { border: 2px solid #fff; background-color: #e91e63 !important; }
.section-title { font-size: 0.8rem; color: #888; margin-bottom: 10px; border-bottom: 1px solid #444; padding-bottom: 5px; text-transform: uppercase; letter-spacing: 1px; }
</style>
</head>
<body>
<header>
<h1>Adversarial AR Performance</h1>
<p>MediaPipe FaceLandmarker + TFJS Embeddings + Live ART Defense</p>
</header>
<div class="container">
<div class="col-comandi">
<div class="section-title">Riconoscimento</div>
<button onclick="toggleScansione()" id="btn-scan">Scansiona faccia</button>
<button onclick="salvaFaccia()">Salva faccia</button>
<button onclick="trovaFaccia()">Trova faccia</button>
</div>
<div class="col-immagine">
<div class="media-container">
<video id="webcam" autoplay muted playsinline></video>
<canvas id="output-canvas"></canvas>
</div>
<div class="log-box" id="log-message">Inizializzazione MediaPipe e TFJS...</div>
</div>
<div class="col-makeup">
<div class="section-title">Live Adv-Makeup</div>
<button class="makeup-btn" id="btn-adv" onclick="impostaMakeup('Adv-Makeup', this)">Adv-Makeup (Orbital)</button>
<button class="makeup-btn" id="btn-patch" onclick="impostaMakeup('Adversarial Patch', this)">Adv Patch (Forehead)</button>
<button class="makeup-btn" id="btn-dpatch" onclick="impostaMakeup('DPatch', this)">DPatch (Noise Block)</button>
</div>
</div>
<script type="module">
import { FaceLandmarker, FilesetResolver } from "https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.3";
const video = document.getElementById('webcam');
const canvas = document.getElementById('output-canvas');
const ctx = canvas.getContext('2d');
const logBox = document.getElementById('log-message');
let faceLandmarker;
let embeddingModel;
let isScanning = false;
let activeMakeup = null;
let lastVideoTime = -1;
let savedFaces = [];
let faceCounter = 0;
// Pattern di rumore pre-calcolati per performance
const noisePattern = createNoisePattern(50, 50);
function log(msg) { logBox.innerText = msg; }
async function init() {
try {
// 1. Inizializza MediaPipe FaceLandmarker
const vision = await FilesetResolver.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.3/wasm");
faceLandmarker = await FaceLandmarker.createFromOptions(vision, {
baseOptions: {
modelAssetPath: `https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task`,
delegate: "GPU"
},
outputFaceBlendshapes: false,
runningMode: "VIDEO",
numFaces: 1
});
// 2. Inizializza MobileNet per gli embeddings biometrici
log("Caricamento modello di Estrazione Feature...");
embeddingModel = await mobilenet.load({version: 2, alpha: 1.0});
// 3. Avvia Webcam
const stream = await navigator.mediaDevices.getUserMedia({ video: { width: 1280, height: 720 } });
video.srcObject = stream;
video.addEventListener("loadeddata", () => {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
renderLoop();
log("Sistema AR Pronto. In attesa di comandi.");
});
} catch (err) {
log("Errore critico durante l'inizializzazione.");
console.error(err);
}
}
function renderLoop() {
requestAnimationFrame(renderLoop);
if (video.currentTime === lastVideoTime) return;
lastVideoTime = video.currentTime;
// Disegna il frame video sul canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
const results = faceLandmarker.detectForVideo(video, performance.now());
if (results.faceLandmarks && results.faceLandmarks.length > 0) {
const landmarks = results.faceLandmarks[0];
if (isScanning) drawMesh(landmarks);
if (activeMakeup) applyMakeupAR(landmarks, activeMakeup);
}
}
// --- SISTEMA DI MAKEUP AVVERSARIALE (AR) ---
function applyMakeupAR(landmarks, type) {
const w = canvas.width;
const h = canvas.height;
if (type === 'Adv-Makeup') {
// Disegna ombretto avversariale (paper 2105.03162) sulle orbite
// Indici approssimativi per occhio SX e DX espansi
const leftEye = [33, 160, 158, 133, 153, 144];
const rightEye = [362, 385, 387, 263, 373, 380];
ctx.fillStyle = "rgba(106, 27, 154, 0.6)"; // Viola scuro semi-trasparente
ctx.shadowBlur = 15;
ctx.shadowColor = "rgba(106, 27, 154, 0.8)";
[leftEye, rightEye].forEach(eye => {
ctx.beginPath();
eye.forEach((idx, i) => {
const x = landmarks[idx].x * w;
const y = landmarks[idx].y * h;
if (i === 0) ctx.moveTo(x, y - 10);
else ctx.lineTo(x, y - 10);
});
ctx.closePath();
ctx.fill();
});
ctx.shadowBlur = 0;
}
else if (type === 'Adversarial Patch') {
// Patch sulla fronte (landmark 151)
const fh = landmarks[151];
const x = fh.x * w;
const y = fh.y * h;
const size = 80;
ctx.save();
ctx.translate(x, y);
// Disegna un cerchio stile "target" colorato ad alto contrasto
for (let i = 4; i > 0; i--) {
ctx.beginPath();
ctx.arc(0, 0, i * 10, 0, Math.PI * 2);
ctx.fillStyle = i % 2 === 0 ? "#ffeb3b" : "#d50000";
ctx.fill();
}
ctx.restore();
}
else if (type === 'DPatch') {
// DPatch applica blocchi di rumore casuale
const nose = landmarks[1];
const x = nose.x * w - 50;
const y = nose.y * h + 20;
ctx.putImageData(noisePattern, x, y);
}
}
function createNoisePattern(w, h) {
const tempCanvas = document.createElement('canvas');
tempCanvas.width = w; tempCanvas.height = h;
const tCtx = tempCanvas.getContext('2d');
const imgData = tCtx.createImageData(w, h);
for (let i = 0; i < imgData.data.length; i += 4) {
const val = Math.random() > 0.5 ? 255 : 0;
imgData.data[i] = imgData.data[i+1] = imgData.data[i+2] = val; // RGB
imgData.data[i+3] = 255; // Alpha
}
return imgData;
}
function drawMesh(landmarks) {
ctx.fillStyle = "#00ff00";
for (let point of landmarks) {
ctx.beginPath();
ctx.arc(point.x * canvas.width, point.y * canvas.height, 1.5, 0, 2 * Math.PI);
ctx.fill();
}
log("Rilevamento topologia facciale in corso (478 punti).");
}
// --- SISTEMA BIOMETRICO (TFJS) ---
async function getFaceEmbedding() {
// Estrae il vettore 1024-D usando MobileNet sul canvas attuale
const tensor = tf.browser.fromPixels(canvas);
const resized = tf.image.resizeBilinear(tensor, [224, 224]);
const normalized = resized.div(255.0).expandDims(0);
const embeddingTensor = embeddingModel.infer(normalized, true); // true = get embedding
const embedding = await embeddingTensor.data();
tf.dispose([tensor, resized, normalized, embeddingTensor]);
return Array.from(embedding);
}
function cosineSimilarity(vecA, vecB) {
let dot = 0, normA = 0, normB = 0;
for (let i = 0; i < vecA.length; i++) {
dot += vecA[i] * vecB[i];
normA += vecA[i] ** 2;
normB += vecB[i] ** 2;
}
return dot / (Math.sqrt(normA) * Math.sqrt(normB));
}
// --- AZIONI BOTTONI ---
window.toggleScansione = () => {
isScanning = !isScanning;
document.getElementById('btn-scan').classList.toggle('active-btn');
if(!isScanning) log("Scansione mesh disattivata.");
};
window.impostaMakeup = (type, btn) => {
document.querySelectorAll('.makeup-btn').forEach(b => b.classList.remove('active-btn'));
if (activeMakeup === type) {
activeMakeup = null;
log("Makeup AR disattivato.");
} else {
activeMakeup = type;
btn.classList.add('active-btn');
log(`Applicazione AR: ${type}. Questo altera i vettori biometrici estratti.`);
}
};
window.salvaFaccia = async () => {
if (!embeddingModel) return log("Modello non pronto.");
log("Estrazione vettore biometrico...");
const embedding = await getFaceEmbedding();
savedFaces.push({ id: faceCounter, vector: embedding });
log(`Impronta facciale [ID: ${faceCounter}] salvata con successo nel registro locale.`);
faceCounter++;
};
window.trovaFaccia = async () => {
if (!embeddingModel || savedFaces.length === 0) return log("Database vuoto o modello non pronto.");
log("Confronto in corso...");
const currentEmbedding = await getFaceEmbedding();
let bestMatch = null;
let highestSim = -1;
savedFaces.forEach(face => {
const sim = cosineSimilarity(currentEmbedding, face.vector);
if (sim > highestSim) {
highestSim = sim;
bestMatch = face.id;
}
});
// MobileNet non è addestrato specificamente sui volti, quindi la soglia di tolleranza
// deve essere più alta (es. 0.85) rispetto a FaceNet, soprattutto con background simili.
if (highestSim > 0.85) {
log(`Trovata corrispondenza: ID ${bestMatch} (Affinità: ${(highestSim*100).toFixed(1)}%)`);
} else {
log(`Nessuna corrispondenza. Max affinità: ${(highestSim*100).toFixed(1)}%`);
}
};
// Avvio automatico all'apertura
init();
</script>
</body>
</html>