File size: 2,343 Bytes
f201f54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
$(document).ready(function() {
    const video = document.getElementById('videoElement');
    const canvas = document.getElementById('canvas');
    const capturedImage = document.getElementById('capturedImage');
    const hfResult = document.getElementById('hfResult');
    const cameraSelect = document.getElementById('cameraSelect');
    let stream = null;

    // Open camera
    $('#openCamera').click(function() {
        $('#cameraContainer').show();
        startCamera(cameraSelect.value);
    });

    // Switch camera
    cameraSelect.addEventListener('change', function() {
        if (stream) {
            stopCamera();
            startCamera(this.value);
        }
    });

    // Capture image
    $('#captureButton').click(function() {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        canvas.getContext('2d').drawImage(video, 0, 0);
        const dataUrl = canvas.toDataURL('image/jpeg');

        // Send to server
        $.ajax({
            type: 'POST',
            url: '/capture',
            data: { image: dataUrl },
            success: function(response) {
                if (response.status === 'success') {
                    capturedImage.src = response.image_url;
                    capturedImage.style.display = 'block';
                    hfResult.textContent = JSON.stringify(response.hf_result, null, 2);
                    stopCamera();
                    $('#cameraContainer').hide();
                } else {
                    alert('Error: ' + response.message);
                }
            },
            error: function() {
                alert('Failed to capture image.');
            }
        });
    });

    function startCamera(facingMode) {
        const constraints = {
            video: { facingMode: facingMode }
        };
        navigator.mediaDevices.getUserMedia(constraints)
            .then(function(mediaStream) {
                stream = mediaStream;
                video.srcObject = stream;
            })
            .catch(function(err) {
                alert('Error accessing camera: ' + err.message);
            });
    }

    function stopCamera() {
        if (stream) {
            stream.getTracks().forEach(track => track.stop());
            stream = null;
            video.srcObject = null;
        }
    }
});