<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Real-time Emotion Detection</title>
</head>
<body>
    <h1>Real-time Emotion Detection</h1>
    <video id="video" width="640" height="480" autoplay></video>
    <canvas id="canvas" width="640" height="480" style="display: none;"></canvas>
    <h2 id="emotionData">Emotion: </h2>
    <script>
        const video = document.getElementById('video');
        const canvas = document.getElementById('canvas');
        const emotionData = document.getElementById('emotionData');
        const ctx = canvas.getContext('2d');

        // Get access to the webcam
        if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
            navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
                video.srcObject = stream;
                video.play();
            });
        }

        const ws = new WebSocket('ws://localhost:8000/ws/emotion');

        ws.onmessage = function(event) {
            const emotions = JSON.parse(event.data);
            console.log('Emotions:', emotions[0]?.emotion);
            emotionData.innerText = 'Emotions:'+ emotions[0]?.emotion;
        };

        video.addEventListener('play', () => {
            const processVideo = () => {
                if (video.paused || video.ended) {
                    return;
                }
                ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
                canvas.toBlob(blob => {
                    ws.send(blob);
                }, 'image/jpeg');
                setTimeout(processVideo, 100);
            };
            processVideo();
        });
    </script>
</body>
</html>