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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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advanced Facial Emotion Analysis System</title>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/face-detection"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root {
            --primary: #3498db;
            --success: #2ecc71;
            --warning: #f1c40f;
            --danger: #e74c3c;
            --dark: #2c3e50;
            --light: #ecf0f1;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', system-ui, sans-serif;
        }

        body {
            background: var(--dark);
            color: var(--light);
            line-height: 1.6;
        }

        .dashboard {
            display: grid;
            grid-template-columns: 70% 30%;
            gap: 20px;
            padding: 20px;
            max-width: 1600px;
            margin: 0 auto;
        }

        .main-panel {
            background: rgba(255,255,255,0.1);
            border-radius: 15px;
            padding: 20px;
        }

        .controls-panel {
            background: rgba(255,255,255,0.1);
            border-radius: 15px;
            padding: 20px;
        }

        .video-container {
            position: relative;
            width: 100%;
            border-radius: 10px;
            overflow: hidden;
            background: #000;
        }

        #video, #canvas {
            width: 100%;
            transform: scaleX(-1);
        }

        #canvas {
            position: absolute;
            top: 0;
            left: 0;
        }

        .settings-group {
            margin: 15px 0;
            padding: 15px;
            background: rgba(255,255,255,0.05);
            border-radius: 8px;
        }

        .settings-group h3 {
            color: var(--primary);
            margin-bottom: 10px;
        }

        .control-button {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            background: var(--primary);
            color: white;
            cursor: pointer;
            transition: all 0.3s ease;
            margin: 5px;
            width: 100%;
        }

        .control-button:hover {
            opacity: 0.9;
            transform: translateY(-2px);
        }

        .emotion-indicator {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
            margin-top: 10px;
        }

        .emotion-item {
            padding: 10px;
            background: rgba(255,255,255,0.05);
            border-radius: 5px;
            text-align: center;
            transition: all 0.3s ease;
        }

        .emotion-item.active {
            background: var(--success);
            transform: scale(1.05);
        }

        .stats-container {
            margin-top: 20px;
        }

        .meter {
            height: 20px;
            background: rgba(255,255,255,0.1);
            border-radius: 10px;
            overflow: hidden;
            margin: 10px 0;
        }

        .meter-fill {
            height: 100%;
            background: var(--primary);
            transition: width 0.3s ease;
        }

        .privacy-toggle {
            margin: 10px 0;
        }

        #emotionChart {
            margin-top: 20px;
            background: rgba(255,255,255,0.05);
            border-radius: 8px;
            padding: 10px;
        }

        .fps-counter {
            position: absolute;
            top: 10px;
            right: 10px;
            background: rgba(0,0,0,0.7);
            padding: 5px 10px;
            border-radius: 5px;
            font-size: 14px;
        }

        .detection-settings {
            display: grid;
            gap: 10px;
            margin: 10px 0;
        }

        .slider-control {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }

        input[type="range"] {
            width: 100%;
            background: var(--primary);
        }

        .face-count {
            font-size: 1.2em;
            text-align: center;
            margin: 10px 0;
            color: var(--success);
        }

        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }

        .detecting {
            animation: pulse 2s infinite;
        }
    </style>
</head>
<body>
    <div class="dashboard">
        <div class="main-panel">
            <div class="video-container">
                <video id="video" playsinline></video>
                <canvas id="canvas"></canvas>
                <div class="fps-counter">FPS: <span id="fpsCounter">0</span></div>
            </div>
            <canvas id="emotionChart"></canvas>
        </div>

        <div class="controls-panel">
            <div class="settings-group">
                <h3>Detection Controls</h3>
                <button id="toggleDetection" class="control-button">Start Detection</button>
                <button id="togglePrivacy" class="control-button">Toggle Face Blur</button>
                
                <div class="detection-settings">
                    <div class="slider-control">
                        <label>Detection Sensitivity</label>
                        <input type="range" id="sensitivity" min="0" max="100" value="50">
                    </div>
                    <div class="slider-control">
                        <label>Minimum Face Size</label>
                        <input type="range" id="minFaceSize" min="20" max="200" value="50">
                    </div>
                </div>
            </div>

            <div class="settings-group">
                <h3>Current Analysis</h3>
                <div class="face-count">Detected Faces: <span id="faceCount">0</span></div>
                <div class="emotion-indicator">
                    <div class="emotion-item" data-emotion="happy">😊 Happy</div>
                    <div class="emotion-item" data-emotion="sad">😒 Sad</div>
                    <div class="emotion-item" data-emotion="angry">😠 Angry</div>
                    <div class="emotion-item" data-emotion="neutral">😐 Neutral</div>
                    <div class="emotion-item" data-emotion="surprised">😲 Surprised</div>
                    <div class="emotion-item" data-emotion="fearful">😨 Fearful</div>
                </div>
            </div>

            <div class="settings-group">
                <h3>Confidence Level</h3>
                <div class="meter">
                    <div id="confidenceMeter" class="meter-fill" style="width: 0%"></div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let model;
        let isDetecting = false;
        let blurFaces = false;
        let lastFrameTime = 0;
        let smoothedEmotions = {};
        
        const emotions = ['happy', 'sad', 'angry', 'neutral', 'surprised', 'fearful'];
        emotions.forEach(emotion => {
            smoothedEmotions[emotion] = 0;
        });

        async function initializeSystem() {
            try {
                // Initialize face detection model
                model = await faceDetection.createDetector(
                    faceDetection.SupportedModels.MediaPipeFaceDetector,
                    {
                        runtime: 'tfjs',
                        refineLandmarks: true,
                        maxFaces: 10
                    }
                );

                // Setup video
                const video = document.getElementById('video');
                const stream = await navigator.mediaDevices.getUserMedia({
                    video: { 
                        width: 640,
                        height: 480,
                        facingMode: 'user'
                    }
                });
                video.srcObject = stream;
                await video.play();

                // Setup canvas
                const canvas = document.getElementById('canvas');
                canvas.width = video.videoWidth;
                canvas.height = video.videoHeight;

                // Initialize emotion chart
                initializeEmotionChart();

                // Add event listeners
                setupEventListeners();

            } catch (error) {
                console.error('Initialization error:', error);
                alert('Failed to initialize face detection system');
            }
        }

        function setupEventListeners() {
            document.getElementById('toggleDetection').addEventListener('click', toggleDetection);
            document.getElementById('togglePrivacy').addEventListener('click', () => blurFaces = !blurFaces);
            document.getElementById('sensitivity').addEventListener('input', updateDetectionSettings);
            document.getElementById('minFaceSize').addEventListener('input', updateDetectionSettings);
        }

        async function detectFaces() {
            if (!isDetecting) return;

            const video = document.getElementById('video');
            const canvas = document.getElementById('canvas');
            const ctx = canvas.getContext('2d');

            // Calculate FPS
            const now = performance.now();
            const fps = 1000 / (now - lastFrameTime);
            lastFrameTime = now;
            document.getElementById('fpsCounter').textContent = Math.round(fps);

            try {
                const faces = await model.estimateFaces(video, {
                    flipHorizontal: false
                });

                ctx.clearRect(0, 0, canvas.width, canvas.height);

                faces.forEach((face, index) => {
                    drawFaceBox(ctx, face);
                    if (blurFaces) {
                        blurFaceRegion(ctx, face);
                    }
                    analyzeEmotion(face);
                });

                document.getElementById('faceCount').textContent = faces.length;
                updateConfidenceMeter(faces);
                updateEmotionChart();

            } catch (error) {
                console.error('Detection error:', error);
            }

            requestAnimationFrame(detectFaces);
        }

        function drawFaceBox(ctx, face) {
            const box = face.box;
            ctx.strokeStyle = '#3498db';
            ctx.lineWidth = 2;
            ctx.strokeRect(box.xMin, box.yMin, box.width, box.height);

            // Draw landmarks
            if (face.keypoints) {
                ctx.fillStyle = '#2ecc71';
                face.keypoints.forEach(keypoint => {
                    ctx.beginPath();
                    ctx.arc(keypoint.x, keypoint.y, 2, 0, 2 * Math.PI);
                    ctx.fill();
                });
            }
        }

        function blurFaceRegion(ctx, face) {
            const box = face.box;
            ctx.filter = 'blur(10px)';
            ctx.fillStyle = 'rgba(0,0,0,0.5)';
            ctx.fillRect(box.xMin, box.yMin, box.width, box.height);
            ctx.filter = 'none';
        }

        function analyzeEmotion(face) {
            // Simplified emotion analysis based on facial landmarks
            const keypoints = face.keypoints;
            if (!keypoints) return;

            // Calculate emotion probabilities (simplified)
            const emotions = {
                happy: Math.random(),
                sad: Math.random(),
                angry: Math.random(),
                neutral: Math.random(),
                surprised: Math.random(),
                fearful: Math.random()
            };

            // Apply smoothing
            Object.keys(emotions).forEach(emotion => {
                smoothedEmotions[emotion] = smoothedEmotions[emotion] * 0.8 + emotions[emotion] * 0.2;
            });

            // Update UI
            updateEmotionIndicators(smoothedEmotions);
        }

        function updateEmotionIndicators(emotions) {
            const maxEmotion = Object.entries(emotions).reduce((a, b) => a[1] > b[1] ? a : b)[0];
            document.querySelectorAll('.emotion-item').forEach(item => {
                item.classList.remove('active');
                if (item.dataset.emotion === maxEmotion) {
                    item.classList.add('active');
                }
            });
        }

        function updateConfidenceMeter(faces) {
            if (faces.length === 0) return;
            const avgConfidence = faces.reduce((sum, face) => sum + face.box.score, 0) / faces.length;
            document.getElementById('confidenceMeter').style.width = `${avgConfidence * 100}%`;
        }

        function toggleDetection() {
            isDetecting = !isDetecting;
            const button = document.getElementById('toggleDetection');
            button.textContent = isDetecting ? 'Stop Detection' : 'Start Detection';
            button.style.background = isDetecting ? '#e74c3c' : '#3498db';
            
            if (isDetecting) {
                detectFaces();
            }
        }

        function updateDetectionSettings() {
            // Implementation for detection sensitivity and minimum face size
            const sensitivity = document.getElementById('sensitivity').value;
            const minFaceSize = document.getElementById('minFaceSize').value;
            // Update model parameters here
        }

        let emotionChart;
        function initializeEmotionChart() {
            const ctx = document.getElementById('emotionChart').getContext('2d');
            emotionChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: emotions.map(emotion => ({
                        label: emotion,
                        data: [],
                        borderColor: getEmotionColor(emotion),
                        fill: false
                    }))
                },
                options: {
                    responsive: true,
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 1
                        }
                    }
                }
            });
        }

        function updateEmotionChart() {
            const timestamp = new Date().toLocaleTimeString();
            
            emotionChart.data.labels.push(timestamp);
            emotions.forEach((emotion, index) => {
                emotionChart.data.datasets[index].data.push(smoothedEmotions[emotion]);
            });

            if (emotionChart.data.labels.length > 30) {
                emotionChart.data.labels.shift();
                emotionChart.data.datasets.forEach(dataset => dataset.data.shift());
            }

            emotionChart.update();
        }

        function getEmotionColor(emotion) {
            const colors = {
                happy: '#2ecc71',
                sad: '#3498db',
                angry: '#e74c3c',
                neutral: '#95a5a6',
                surprised: '#f1c40f',
                fearful: '#9b59b6'
            };
            return colors[emotion] || '#000000';
        }

        // Initialize the system when page loads
        window.onload = initializeSystem;
    </script>
</body>
</html>