  <!DOCTYPE html>
  <html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Face Detection</title>
      <script  src="js/face-api.min.js" type="text/javascript"></script>
      <script defer>
           document.addEventListener('DOMContentLoaded', function() {
        const video = document.getElementById("video");
        
        
        Promise.all([
          faceapi.nets.tinyFaceDetector.loadFromUri("js/models"),
          faceapi.nets.faceLandmark68Net.loadFromUri("js/models"),
          faceapi.nets.faceRecognitionNet.loadFromUri("js/models"),
          faceapi.nets.faceExpressionNet.loadFromUri("js/models"),
          faceapi.nets.ageGenderNet.loadFromUri("js/models"),
          faceapi.nets.ssdMobilenetv1.loadFromUri("js/models"),
        ]).then(webCam);
        
        function webCam() {
          navigator.mediaDevices
            .getUserMedia({
              video: true,
              audio: false,
            })
            .then((stream) => {
              video.srcObject = stream;
            })
            .catch((error) => {
              console.log(error);
            });
        }
        
        
        function getLabeledFaceDescriptions() {
          const labels = ["Alan", "DojaCat", "Karabi"];
          return Promise.all(
            labels.map(async (label) => {
              const descriptions = [];
              for (let i = 1; i <= 3; i++) {
                const img = await faceapi.fetchImage(`/js/labels/${label}/${i}.png`);
                const detections = await faceapi
                  .detectSingleFace(img)
                  .withFaceLandmarks()
                  .withFaceDescriptor();
                descriptions.push(detections.descriptor);
              }
              return new faceapi.LabeledFaceDescriptors(label, descriptions);
            })
          );
        }
        
        
        video.addEventListener("play", async () => {
          const labeledFaceDescriptors = await getLabeledFaceDescriptions();
          const faceMatcher = new faceapi.FaceMatcher(labeledFaceDescriptors);
        
          const canvas = faceapi.createCanvasFromMedia(video);
          document.getElementById('vedio-container').appendChild(canvas);
        
          faceapi.matchDimensions(canvas, { height: video.height, width: video.width });
        
          setInterval(async () => {
            const detection = await faceapi
              .detectAllFaces(video, new faceapi.TinyFaceDetectorOptions())
              .withFaceLandmarks()
              .withFaceExpressions().withAgeAndGender().withFaceDescriptors();
            
            const resizedWindow = faceapi.resizeResults(detection, {
              height: video.height,
              width: video.width,
            });
        
            canvas.getContext("2d").clearRect(0, 0, canvas.width, canvas.height);
        
            // Draw face detection overlay
            faceapi.draw.drawDetections(canvas, resizedWindow);
            faceapi.draw.drawFaceLandmarks(canvas, resizedWindow);
            faceapi.draw.drawFaceExpressions(canvas, resizedWindow);
        
            // Draw labeled face
            const results = resizedWindow.map((d) => {
              return faceMatcher.findBestMatch(d.descriptor);
            });
            results.forEach((result, i) => {
              const box = resizedWindow[i].detection.box;
        
              // Positioning for the face detection label
              const drawBox = new faceapi.draw.DrawBox(box, {
                label: result,
              });
              drawBox.draw(canvas);
              const name = result._label;
             
              
                
                
                
                
                 // Redirect based on the user's name
                fetch('/acc-for-face', {
                  
                method: 'POST',
                headers: {
                  'Content-Type': 'application/json'
                },
                body: JSON.stringify({ userName: name })
              })
              .then(response => {
                console.log("Response status:", response.status);
                return response.json();
              })
              .then(data => {
                console.log("Received data:", data);
                console.log("Received redirect URL:", data.redirectUrl);
                console.log("Current URL:", window.location.href);

                if (data.redirectUrl === "/acc_for_face") {
                  // Redirect to the specified URL
                  
                  window.location.href = data.redirectUrl;
                } else {
                  console.log(data);
                }
              })
              .catch(error => {
                console.error('Error:', error);
              });


              // Positioning for the age/gender label
              const ageGenderLabel = Math.round(resizedWindow[i].age) + " year old " + resizedWindow[i].gender;
              const ageGenderX = box.x + 100; // Adjust x position
              const ageGenderY = box.y + box.height + 20; // Adjust y position
              canvas.getContext("2d").fillStyle = 'yellow';
              canvas.getContext("2d").font = '15px Arial';
              canvas.getContext("2d").fillText(ageGenderLabel, ageGenderX, ageGenderY);
            });
        
          }, 100);
        });
      });
            </script>
      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
      <style>
          body{
      margin: 0;
      padding: 0;
      background-image: url(https://images.pexels.com/photos/255379/pexels-photo-255379.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2);
  }
  .vedio-container{
      
      width: 100vw;
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
  }

  canvas{
      position: absolute;
  }
      </style>
      
  </head>
  <body>
      <nav class="navbar bg-warning navbar-expand-lg">
          <div class="container-fluid">
            <a class="navbar-brand" href="#">UTS</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
              <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
              <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                <li class="nav-item">
                  <a class="nav-link active" aria-current="page" href="#">Home</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="#">Maps</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="#">Account</a>
                </li>
                <form class="container-fluid justify-content-start">
                  <button class="btn btn-outline-success me-2" type="button">Login</button>
                  <button class="btn btn-outline-success me-2" type="button">Sign Up</button>
                </form>
              </ul>
            
            </div>
          </div>
        </nav>
        <div class="container text-center">
          <div class="row">
            <div class="col">
            
            </div>
            <div class="col">
            <h1>Face Detection</h1>
            </div>
            <div class="col">
            
            </div>
          </div>
        </div>
      <div id="vedio-container" class="vedio-container">
          <video id="video" width="640" height="480" autoplay muted></video>
      </div>
      
      <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
      
  </body>
  </html>
