1.4.0 • Published 9 months ago

@jaak.ai/face-detector v1.4.0

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

FaceDetectorComponent Documentation

The FaceDetectorComponent is a web component built using StencilJs designed to handle video and image inputs for face detection purposes. It can operate in either video camera or file upload mode, depending on configuration.

Installation

To install the package via npm, use the following command:

npm install @jaak.ai/face-detector

Properties

PropertyTypeDescription
configConfigComponentConfiguration for the face detector component (optional)

|

Usage Example

<face-detector
  config={{
    width: '640px',
    height: '480px',
    enableMicrophone: true,
    mode: 'video-camera',
    placeholder: 'Upload your document',
    buttonText: 'Upload',
    documentAccept: 'image/*',
    description: 'Please upload an image file.',
    size: 2048
  }}
  onStatus={(event) => handleStatusChange(event.detail)}
  onComponentError={(event) => handleComponentError(event.detail)}
  onFileResult={(event) => handleFileResult(event.detail)}
></face-detector>

ConfigComponent Interface

Detailed interface for configuring the FaceDetectorComponent:

PropertyTypeDescription
widthstringWidth of the video element. Default: '500px'.
heightstringHeight of the video element. Default: '400px'.
enableMicrophonebooleanIndicates whether the microphone should be enabled. Default: false.
modestringOperational mode, either 'video-camera' or 'upload-file'.
placeholderstringPlaceholder text for file input.
buttonTextstringText displayed on the upload button.
documentAcceptstringSpecifies the types of files that can be uploaded.
descriptionstringDescription displayed near the file input.
sizenumberMaximum file size allowed in kilobytes.
videoDurationnumberDuration for video recording in seconds.
videoMediaTrackConstraintsDuration for video recording in seconds.
cameraSourcestringSpecifies which camera to use for video capture when multiple sources are available, such as 'user' (front camera) or 'environment' (rear camera). This helps in selecting the appropriate camera based on the application's needs.
videoFormatstringDefines the preferred video resolution and frame rate format, such as '1920x1080@30' for 1080p video at 30 frames per second. This setting is used to configure the video output according to the capabilities of the media device and the requirements of the application.
autoRecorderbooleanIf the system detect a face on video-cam mode, it will record a video(videoDuration)
hideFaceTrackerbooleanHides the monitoring shape that overlaps in the face found during video transmission. default: false
disableFaceDetectionbooleanDeactivate the face detection system, the component does not search for faces during the video. default: false
progressiveAutoRecorderbooleanThe component does not stop recording videos after your first recording. Notice: you will need to close the life cycle manually. default: false
muteFaceDetectionMessagesbooleanNo messages from the face detection will be sent during video transmission default: false
hideTimerbooleanThe recording indicator will not be displayed during the processdefault: false
timerStylesTimerStylesDefine the styles of the recording indicator during the process
faceTrackerStylesFaceTrackerStylesDefine the styles of the figure on the face found by the detection system
offlineModelbooleanLoad the faces detection system without making internet requests (local storage)

TimerStyles Interface

Interface detailing the styles of timer recording indicator:

PropertyTypeDescription
colorstringColor of the progress indicator text.
circleColorstringColor of the filled part of the progress circle.
circleColorEmptystringColor of the empty part of the progress circle.
circleColorSuccessstringColor of the progress circle when the task succeeds.
widthnumberWidth of the progress circle in pixels.
heightnumberHeight of the progress circle in pixels.
fontSizenumberFont size of the progress indicator text in pixels.
posXnumberHorizontal position of the progress indicator. It accepts 0 - 100. default: 50
posYnumberVertical position of the progress indicator. It accepts 0 - 100. default: 50
strokeWidthnumberWidth of the stroke of the progress circle in pixels.
dashArraystringStroke dash pattern of the progress circle.

FaceTrackerStyles Interface

Interface detailing the styles of face tracker indicator:

PropertyTypeDescription
validColorstringOptional color used to indicate a valid face detection.
invalidColorstringOptional color used to indicate an invalid face detection.

FileResult Interface

Interface detailing the result of a file operation:

PropertyTypeDescription
base64stringBase64 encoded string of the file content.
typestringMIME type of the file (optional).
namestringOriginal name of the file (optional).
sizenumberSize of the file in bytes (optional).

FaceDetectionMessage Interface

Interface detailing the result of FaceDetection operation:

PropertyTypeDescription
labelstringA label describing the overall result of the face detection.
detailsstringAdditional details about the face detection result.
faceExistbooleanIndicates whether a face was detected or not.
correctPositionbooleanIndicates whether the detected face is in the correct position as required.

StatusFaceDetector Values

This enum represents the various status states that the FaceDetectorComponent can emit during its operation:

StatusDescription
NOT_LOADEDInitial state before any operations have started.
LOADINGThe component is currently loading necessary resources.
LOADEDAll resources are loaded, and the component is ready to be used.
RECORDINGThe component is currently recording video.
ERRORAn error has occurred in one of the processes.
UPLOADINGThe component is uploading a file.
RUNNINGThe component is actively processing input or data.
SNAPSHOTTINGThe component is taking a snapshot or still image.
FINISHEDThe component has completed all processing and recording tasks.

webComponentError Interface

Interface detailing when the component throws Error operation:

PropertyTypeDescription
labelstringA descriptive label summarizing the error.
codestringAn optional code identifying the type of error.
detailsanyOptional additional data or information about the error.

Events

Event NameEmitsDescription
statusStatusFaceDetectorEmits the current status of the component, indicating different operational states.
componentErrorwebComponentErrorEmits an error object containing details about an error that occurred in the component.
fileResultFileResultEmits the result of a file operation, typically after a recording or snapshot has been processed.
faceDetectionMessageFaceDetectionMessageEmits messages related to face detection results, including details about detection status and quality.

Methods

NameParametersResultDescription
turnOffFaceDetectorNonevoidDeactivates the face detector, hides the model shape, and unsubscribes from the detection service.
switchModenewMode: video-cameraor upload-filevoidSwitches the component mode between 'video-camera' and 'upload-file', and either resets or stops as appropriate.
stopComponentNonevoidStops the component's operations by invoking the internal stopCore method.
restartComponentNonevoidResets the component to its initial configured state using resetCore.
getModeNonestringReturns the current mode of the component.
recordVideoNonestringStarts video recording and returns the video in Base64 format if successful.
takeSnapshotNonestringCaptures a snapshot and returns the image in Base64 format if successful.
getVideoElementNoneHTMLVideoElementRetrieves the video element from the video camera component.
getStreamNoneMediaStreamRetrieves the media stream from the video camera component.
toggleCameraNonevoidToggles the video camera between front and back modes, if applicable.
stopVideoStreamNonevoidStops the video stream from the video camera component.
restartVideoStreamNonevoidResumes the video stream from the video camera component.
resetFaceDetectorresetHard: booleanvoidResets the face detector to its default state and optionally performs a hard reset.

Example Usage of FaceDetectorComponent

This example demonstrates how to implement the FaceDetectorComponent in a simple HTML and JavaScript setup. It includes configuration of the component, handling various events, and switching operational modes.

HTML and JavaScript Example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Face Detector Example</title>
</head>
<body>
<!-- Include the Face Detector component -->
<face-detector id="faceDetector"></face-detector>

<script type="module">
  // Select the face-detector component
  const faceDetector = document.getElementById('faceDetector');

  // Configure the component with initial settings
  faceDetector.config = {
    width: '640px',
    height: '480px',
    enableMicrophone: false,
    mode: 'video-camera', // or 'upload-file' for file upload mode
    placeholder: 'Upload your image',
    buttonText: 'Upload File',
    documentAccept: 'image/*',
    description: 'Please upload an image for face detection',
    size: 2048, // Max file size in kilobytes
    videoDuration: 5 // Duration in seconds for video recording
  };

  // Handle the status event
  faceDetector.addEventListener('status', event => {
    console.log('Status event:', event.detail);
    // You can update UI based on status here
  });

  // Handle errors
  faceDetector.addEventListener('componentError', event => {
    console.error('Error event:', event.detail);
    // Display error messages to the user
  });

  // Handle file results
  faceDetector.addEventListener('fileResult', event => {
    console.log('File result event:', event.detail);
    // Process the file result, e.g., display the image or video
  });

  // Example of using a component method to switch modes
  function switchToUploadMode() {
    faceDetector.switchMode('upload-file');
  }

  // Add more functionality or interaction logic as needed
</script>
</body>
</html>

React Implementation Example for FaceDetectorComponent

This section provides an example of how to integrate and use the FaceDetectorComponent within a React application.

import React, { useState, useEffect } from 'react';

const FaceDetector = () => {
  const [status, setStatus] = useState('');
  const [error, setError] = useState(null);
  const [fileResult, setFileResult] = useState(null);

  useEffect(() => {
    // Ensure custom elements are defined
    if (!customElements.get('face-detector')) {
      import('@jaak-ai/face-detector');
    }
  }, []);

  const handleStatusChange = (event) => {
    setStatus(event.detail);
  };

  const handleError = (event) => {
    setError(event.detail);
  };

  const handleFileResult = (event) => {
    setFileResult(event.detail);
  };

  return (
    <div>
      <face-detector
        id="faceDetector"
        onStatus={handleStatusChange}
        onComponentError={handleError}
        onFileResult={handleFileResult}
        config={JSON.stringify({
          width: '640px',
          height: '480px',
          enableMicrophone: true,
          mode: 'video-camera',
          placeholder: 'Upload your image',
          buttonText: 'Upload File',
          documentAccept: 'image/*',
          description: 'Please upload an image for face detection',
          size: 2048,
          videoDuration: 5
        })}
      ></face-detector>

      <div>Status: {status}</div>
      <div>Error: {error && error.label}</div>
      <div>File Result: {fileResult && fileResult.base64}</div>
    </div>
  );
};

export default FaceDetector;

Angular Implementation Example for FaceDetectorComponent

This section provides an example of how to integrate and use the FaceDetectorComponent within an Angular application.

import { Component, OnInit } from '@angular/core';

@Component({
 selector: 'app-root',
 template: `
   <face-detector
     (status)="handleStatus($event)"
     (componentError)="handleError($event)"
     (fileResult)="handleFileResult($event)"
     [config]="config">
   </face-detector>

   <div>Status: {{ status }}</div>
   <div>Error: {{ error?.details }}</div>
   <div>File Result: {{ fileResult?.base64 }}</div>
 `
})
export class AppComponent implements OnInit {
 status: string;
 error: any;
 fileResult: any;
 config = {
   width: '640px',
   height: '480px',
   enableMicrophone: true,
   mode: 'video-camera',
   placeholder: 'Upload your image',
   buttonText: 'Upload File',
   documentAccept: 'image/*',
   description: 'Please upload an image for face detection',
   size: 2048,
   videoDuration: 5
 };

 ngOnInit(): void {
   // Custom element registration or any initialization logic
 }

 handleStatus(event: CustomEvent) {
   this.status = event.detail;
 }

 handleError(event: CustomEvent) {
   this.error = event.detail;
 }

 handleFileResult(event: CustomEvent) {
   this.fileResult = event.detail;
 }
}

Additional Info

This package needs library dependencies, if is necessary you can install manually dependencies using this command:

npm install @jaak.ai/video-camera @jaak.ai/file-uploader

This component is designed, developed and owned by JAAK and is their intellectual property. Visit more details in https://jaak.ai

1.4.0-dev.1

9 months ago

1.4.0

9 months ago

1.3.0-dev.4

9 months ago

1.2.0

1 year ago

1.2.0-dev.30

12 months ago

1.2.0-dev.8

12 months ago

1.2.0-dev.31

11 months ago

1.2.0-dev.7

1 year ago

1.2.0-dev.10

12 months ago

1.2.0-dev.11

12 months ago

1.2.0-dev.9

12 months ago

1.2.0-dev.4

1 year ago

1.2.0-dev.3

1 year ago

1.3.0-dev.1

11 months ago

1.2.0-dev.6

1 year ago

1.2.0-dev.5

1 year ago

1.3.0-dev.3

10 months ago

1.3.0-dev.2

10 months ago

1.2.0-dev.2

1 year ago

1.3.0

11 months ago

1.2.0-dev.1

1 year ago

1.1.0-dev.2

1 year ago

1.2.0-dev.12

12 months ago

1.2.0-dev.13

12 months ago

1.2.0-dev.14

12 months ago

1.2.0-dev.15

12 months ago

1.2.0-dev.16

12 months ago

1.2.0-dev.17

12 months ago

1.2.0-dev.18

12 months ago

1.2.0-dev.19

12 months ago

1.2.0-dev.20

12 months ago

1.2.0-dev.21

12 months ago

1.2.0-dev.22

12 months ago

1.2.0-dev.23

12 months ago

1.2.0-dev.24

12 months ago

1.2.0-dev.25

12 months ago

1.2.0-dev.26

12 months ago

1.2.0-dev.27

12 months ago

1.2.0-dev.28

12 months ago

1.2.0-dev.29

12 months ago

1.1.0

1 year ago

1.0.0-dev.5

1 year ago

1.1.0-dev.1

1 year ago

1.0.0

1 year ago

1.0.0-dev.3

1 year ago

1.0.0-dev.4

1 year ago

1.0.0-dev.1

1 year ago

1.0.0-dev.2

1 year ago

0.0.1

1 year ago