File size: 14,693 Bytes
cc65f2f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
const form = document.querySelector("#detectar-emocoes-form");
let resultsContainer = document.querySelector("#detectar-emocoes-results");
let resultsidade = document.querySelector("#detectar-emocoes-idade");
let pontos = document.querySelector("#pontos");
const sourceSwitch = document.getElementById("detectar-emocoes-source-switch");
let stream;
let startCameraButton = document.getElementById("start-camera-button");
let detectEmotionsButton = document.getElementById("detect-emotions-button");
let detectLandmarksButton = document.getElementById("detect-landmarks-button");
let detectAgeButton = document.getElementById("detect-age-button");
let extractPointsButton = document.getElementById("extract-points-button");
let displaySize;
let detections;
let resizedDetections;
let canvas = document.createElement("canvas");  
resultsContainer.appendChild(canvas);

let startCameraInterval;
    detectEmotionsButton.disabled = true;
    detectLandmarksButton.disabled = true;
    detectAgeButton.disabled = true;
    extractPointsButton.disabled = true;
    startCameraButton.addEventListener("change", async (event) => {
    if (event.target.checked) {
        detectEmotionsButton.disabled = false;
        detectLandmarksButton.disabled = false;
        detectAgeButton.disabled = false;
        extractPointsButton.disabled = false;

        detectEmotionsButton.addEventListener("change", detectEmotionsButton);
        detectLandmarksButton.addEventListener("change", detectLandmarksButton);
        detectAgeButton.addEventListener("change", detectAgeButton);
        extractPointsButton.addEventListener("change", extractPointsButton);
        resultsContainer.innerHTML = "";
        video = document.createElement("video");
        video.width = 200;
        video.height = 150;
        video.autoplay = true;
        stream = await navigator.mediaDevices.getUserMedia({
        audio: false,
        video: true,
        });
        canvas.width = video.width;
        canvas.height = video.height;
        canvas.id = "landmarkCanvas";
        video.srcObject = stream;
        resultsContainer.appendChild(video);
        resultsContainer.appendChild(canvas);
    } else {
        detectEmotionsButton.checked = false;
        detectEmotionsButton.disabled = true;
        detectLandmarksButton.checked = false;
        detectLandmarksButton.disabled = true;
        detectAgeButton.checked = false;
        detectAgeButton.disabled = true;
        extractPointsButton.checked = false;
        extractPointsButton.disabled = true;
        detectEmotionsButton.removeEventListener("change", detectEmotionsButton);
        detectLandmarksButton.removeEventListener("change", detectLandmarksButton);
        detectAgeButton.removeEventListener("change", detectAgeButton);
        extractPointsButton.removeEventListener("change", extractPointsButton);
        clearInterval(detectLandmarksInterval);
        clearInterval(detectEmotionsInterval);
        clearInterval(detectAgeInterval);
        clearInterval(extractPointsInterval);
        resultsContainer.innerHTML = "";
        video.srcObject = null;
        if (stream != null) {
        stream.getTracks().forEach((track) => track.stop());
        }
    }
    });

  let detectEmotionsInterval;
  detectEmotionsButton.addEventListener("change", async (event) => {
  if (event.target.checked) {
    detectEmotionsInterval = setInterval(async () => {
        canvas = document.getElementById("landmarkCanvas");
        displaySize = { width: video.width, height: video.height};
        faceapi.matchDimensions(canvas,displaySize);
        detections = await faceapi.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks().withFaceExpressions();
        resizedDetections = faceapi.resizeResults(detections, displaySize);
        resultsContainer.innerHTML = "";
        resultsContainer.appendChild(video);
        resultsContainer.appendChild(canvas);
        detections.forEach((result) => {
            if (result.expressions) {
            const happy = result.expressions.Feliz || 0;
            const sad = result.expressions.Triste || 0;
            const angry = result.expressions.Raiva || 0;
            const disgusted = result.expressions.Nojo || 0;
            const fear = result.expressions.Medo || 0;
            const surprise = result.expressions.Surpreso || 0;
            const neutr = result.expressions.Neutro || 0;
            const card = document.createElement("div");
            card.innerHTML = `<h3>Emoções detectadas:</h3> <ul> 

            <li>Neutro: ${neutr.toFixed(2)}</li> 

            <li>Felicidade: ${happy.toFixed(2)}</li> 

            <li>Tristeza: ${sad.toFixed(2)}</li> 

            <li>Raiva: ${angry.toFixed(2)}</li> 

            <li>Desprezo: ${disgusted.toFixed(2)}</li> 

            <li>Medo: ${fear.toFixed(2)}</li> 

            <li>Surpresa: ${surprise.toFixed(2)}</li> 

            </ul>`;
            resultsContainer.appendChild(card);
            } else {
            console.error("Nenhuma emoção detectada.");
            }
        }); 
          }, 500)
        } else {
        clearInterval(detectEmotionsInterval);
      }
    });
    
        let detectLandmarksInterval;
        function unite(leftEyebrow, rightEyebrow) {
            const united = [];
            for (const point of leftEyebrow) { united.push(point); }
            for (const point of rightEyebrow) {united.push(point); }
            return united;
          }
        detectLandmarksButton.addEventListener("change", async (event) => {
            if (event.target.checked) {
              detectLandmarksInterval = setInterval(async () => {
                canvas = document.getElementById("landmarkCanvas");
                displaySize = { width: video.width, height: video.height};
                faceapi.matchDimensions(canvas,displaySize);
                detections = await faceapi.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks();
                resizedDetections = faceapi.resizeResults(detections, displaySize);
                canvas.getContext('2d').clearRect(0,0,canvas.width, canvas.height);
                for (const detection of resizedDetections) {
                  const landmarks = detection.landmarks;
                  const leftEyebrow = landmarks.getLeftEyeBrow();
                  const rightEyebrow = landmarks.getRightEyeBrow();
                  faceapi.draw.drawFaceLandmarks(canvas, detection, {
                    drawLines: true,
                    color: 'red',
                    landmarkIndices: leftEyebrow.concat(rightEyebrow)
                  });
                  faceapi.draw.drawFaceLandmarks(canvas, detection, {
                    drawLines: true,
                    color: 'yellow',
                    landmarkIndices: leftEyebrow.concat(rightEyebrow)
                  });
                }
                resultsContainer.innerHTML = "";
                resultsContainer.appendChild(video);
                resultsContainer.appendChild(canvas);
              }, 500)
            } else {
              clearInterval(detectLandmarksInterval);
            }
          });
          
    let detectAgeInterval;
    detectAgeButton.addEventListener("change", async (event) => {
      if (event.target.checked) {
        detectAgeInterval = setInterval(async () => {
        canvas = document.getElementById("landmarkCanvas");
        displaySize = { width: video.width, height: video.height};
        faceapi.matchDimensions(canvas,displaySize);
        detections = await faceapi.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions()).withAgeAndGender();
        resizedDetections = faceapi.resizeResults(detections, displaySize);
        resultsidade.innerHTML = "";
        resultsidade.appendChild(video);
        resultsidade.appendChild(canvas);
        detections.forEach((result) => {
          if (result.age) {
              const card = document.createElement("div");
              card.innerHTML = `<h3>Idade detectada:</h3> <p>${result.age.toFixed(0)} anos</p>`;
              resultsidade.appendChild(card);
              } else {
              console.error("Nenhuma idade detectada.");
          }
        });
      }, 500)
    } else {
        clearInterval(detectAgeInterval);
    }
    });

    let extractPointsInterval;
    extractPointsButton.addEventListener("change", async (event) => {
      if (event.target.checked) {
        extractPointsInterval = setInterval(async () => {
        canvas = document.getElementById("landmarkCanvas");
        displaySize = { width: video.width, height: video.height};
        faceapi.matchDimensions(canvas,displaySize);
        detections = await faceapi.detectAllFaces(video, new faceapi.TinyFaceDetectorOptions()).withFaceLandmarks();
        resizedDetections = faceapi.resizeResults(detections, displaySize);
        resultsContainer.appendChild(video);
        resultsContainer.appendChild(canvas);
    function getBoxFromPoints(points) {
        const box = { bottom: -Infinity, left: Infinity, right: -Infinity, top: Infinity,
          get center() {return { x: this.left + this.width / 2, y: this.top + this.height / 2, };
        },
        get height() { return this.bottom - this.top; },
        get width() {  return this.right - this.left; },
        };
        for (const point of points) {
            box.left = Math.min(box.left, point.x);
            box.right = Math.max(box.right, point.x);
            box.bottom = Math.max(box.bottom, point.y);
            box.top = Math.min(box.top, point.y);
        }
        return box;
    }



let tempoDeSelecao = 2000; 
let tempoInicial;
let botaoSelecionado = null;
function calcularPontoDeOlhar(face) {
  const olhoEsquerdo = face.landmarks.positions.slice(36, 42);
  const olhoDireito = face.landmarks.positions.slice(42, 48);

  // Calculando os pontos centrais para cada olho
  const centroEsquerdo = calcularCentro(olhoEsquerdo);
  const centroDireito = calcularCentro(olhoDireito);

  // Calculando um ponto médio entre os centros dos dois olhos
  const pontoFocal = {
      x: (centroEsquerdo.x + centroDireito.x) / 2,
      y: (centroEsquerdo.y + centroDireito.y) / 2
  };

  return pontoFocal;
}

function calcularCentro(pontos) {
  const totalPontos = pontos.length;
  const centro = pontos.reduce((soma, ponto) => {
      soma.x += ponto._x;
      soma.y += ponto._y;
      return soma;
  }, {x: 0, y: 0});

  centro.x /= totalPontos;
  centro.y /= totalPontos;
  return centro;
}
function verificarBotaoSobOlhar(pontoFocal) {
  const botoes = document.querySelectorAll('.eye-button'); 
  for(const botao of botoes) {
      const rect = botao.getBoundingClientRect();
      console.log(rect.left)
      console.log(pontoFocal.x)
      if (
          pontoFocal.x >= rect.left && pontoFocal.x <= rect.right &&
          pontoFocal.y >= rect.top && pontoFocal.y <= rect.bottom
          
      ) {
        console.log(pontoFocal)
          return botao; // Retornará o botão que está sob o olhar
      }
  }
  return null; // Retornará null se nenhum botão estiver sob o olhar
}

    function olhoEstaSobreBotao(pontoFocal, botao) {
      return pontoFocal._x > botao.x && pontoFocal._x < botao.x + botao.width && pontoFocal._y > botao.y && pontoFocal._y < botao.y + botao.height;
    }
   

    document.querySelectorAll('.eye-button').forEach(botao => {
        botao.addEventListener('mouseenter', () => {
            tempoInicial = new Date().getTime();
        });
        botao.addEventListener('mouseleave', () => {
            tempoInicial = null;
        });
    });

    setInterval(() => {
        if(tempoInicial && new Date().getTime() - tempoInicial > tempoDeSelecao) {
            console.log('Botão selecionado!');
            tempoInicial = null;
            // Adicione a lógica para lidar com a seleção do botão aqui
        }
    }, 100); 

    for (const face of resizedDetections) {
      //const pontoFocal = calcularPontoDeOlhar(face);
      
        const features = {
            mandibula: face.landmarks.positions.slice(0, 17),
            sobrancelhaesquerda: face.landmarks.positions.slice(17, 22),
            sobrancelhaDireita: face.landmarks.positions.slice(22, 27),
            Pontenasal: face.landmarks.positions.slice(27, 31),
            nariz: face.landmarks.positions.slice(31, 36),
            olhoEsquerdo: face.landmarks.positions.slice(36, 42),
            olhoDireito: face.landmarks.positions.slice(42, 48),
            labioExterno: face.landmarks.positions.slice(48, 60),
            labiointerno: face.landmarks.positions.slice(60),
        };
        const pre = document.createElement("pre");
        pre.innerText = JSON.stringify(features, null, 2);
        pontos.innerHTML = "";
        pontos.appendChild(pre);
        
        for (const eye of [features.olhoEsquerdo, features.olhoDireito]) {
            const eyeBox = getBoxFromPoints(eye);
            const fontSize = 20;
            const context = canvas.getContext("2d");
            context.lineWidth = 2;
            context.fillStyle = "#FF0000";
            context.beginPath();
            context.fillStyle = "rgba(20,30,22,0.5)";
            context.strokeRect(eyeBox.center.x-10, eyeBox.center.y-10, 30, 20, 30 );
            context.arc(eyeBox.center.x, eyeBox.center.y, 4, 0, 2 * Math.PI);
            context.fillStyle = "rgba(255, 255, 255, 0)";
            context.fill();
            context.closePath();
            let pontoFocal = {
              x: (eyeBox.center.x ) / 2,
              y: (eyeBox.center.y ) / 2
          };
            const botaoSobOlhar = verificarBotaoSobOlhar(pontoFocal);
            console.log(botaoSobOlhar)
          if (botaoSobOlhar) {
            if (botaoSelecionado !== botaoSobOlhar) {
                botaoSelecionado = botaoSobOlhar;
                tempoInicial = new Date().getTime();
            } else if (new Date().getTime() - tempoInicial > tempoDeSelecao) {
                console.log('Botão selecionado:', botaoSelecionado.id);
                // Adicione a lógica para lidar com a seleção do botão aqui...
            }
        } else {
            botaoSelecionado = null;
            tempoInicial = null;
        }
        }
    }
}, 500)
} else {
    clearInterval(extractPointsInterval);
}
});