Skip to content

JavaScript API for estimation of vital signs such as heart rate and respiratory rate from video.

License

Notifications You must be signed in to change notification settings

Rouast-Labs/vitallens.js

Repository files navigation

vitallens.js

Tests NPM Version Website Documentation DOI

Estimate vital signs such as heart rate and respiratory rate from video in JavaScript.

vitallens.js is a JavaScript client for the VitalLens API, which leverages the same inference engine as our free iOS app VitalLens. Furthermore, it includes fast implementations of several other heart rate estimation methods from video such as g, chrom, and pos.

This library works both in browser environments and in Node.js, and comes with a set of examples for file-based processing and real-time webcam streaming.

Using a different language or platform? We also have a Python client.

Features

  • Cross-Platform Compatibility:
    Use vitallens.js in the browser or Node.js.

  • Flexible Input Support: Process video files or live streams from a webcam or any MediaStream.

  • Multiple Estimation Methods: Choose the method that fits your needs:

    • vitallens: Provides heart rate, respiratory rate, pulse waveform, and respiratory waveform estimates with associated confidences. (Requires an API key - get one for free on our website)
    • g, chrom, pos: Offer faster (but less accurate) heart rate and pulse waveform estimates. (No API key required.)
  • Fast Face Detection & ROI Support:
    Perform rapid face detection when required—or optionally, pass a global region of interest (ROI) to skip detection for even faster processing.

  • Event-Driven API:
    Register event listeners to receive real-time updates on estimated vitals.

  • Pre-Built Web Component Widgets:
    In addition to the core API, vitallens.js provides ready-to-use web components. Use the unified widget (supporting both file and webcam modes) or choose the specialized file-only or webcam-only widget for streamlined integration.

  • TypeScript-Ready:
    Written in TypeScript with complete type definitions for enhanced developer experience.

Disclaimer

Important: vitallens.js provides vital sign estimates for general wellness purposes only. It is not intended for medical use. Always consult a healthcare professional for any medical concerns or precise clinical measurements.

Please review our Terms of Service and Privacy Policy for more details.

Installation

Node.js

Install vitallens.js via npm or yarn:

npm install vitallens
# or
yarn add vitallens

Then use it as follows:

import { VitalLens } from 'vitallens';
const vl = new VitalLens({ method: 'vitallens', apiKey: 'YOUR_API_KEY' });
const result = await vl.processVideoFile(myVideoFile);
console.log(result);

Browser

For browser usage, you can either bundle vitallens.js with your project or load it directly from a CDN. In addition to the core API, vitallens.js also provides pre-built web component widgets. We offer three variants:

  • Unified Widget: Supports both file and webcam modes with mode toggles.
  • File-Only Widget: For processing video files only.
  • Webcam-Only Widget: For live webcam streaming only.

For example, using jsDelivr:

<!-- Latest version -->
<script src="https://cdn.jsdelivr.net/npm/vitallens/dist/vitallens.browser.js"></script>

<!-- Or pin a specific version -->
<script src="https://cdn.jsdelivr.net/npm/vitallens@0.0.3/dist/vitallens.browser.js"></script>

<!-- Use with core API -->
<script>
  // vitallens.js is exposed as a global, for example as window.VitalLens.
  const vl = new VitalLens({ method: 'vitallens', apiKey: 'YOUR_API_KEY' });
  // Suppose myMediaStream and myVideoElement are defined:
  vl.addVideoStream(myMediaStream, myVideoElement);
  vl.addEventListener('vitals', (data) => console.log(data));
  vl.startVideoStream();
</script>

<!-- Or use our widget -->
<vitallens-widget api-key="YOUR_API_KEY"></vitallens-widget>

<!-- Or, to use a specialized widget: -->
<!-- File-only widget -->
<vitallens-file-widget api-key="YOUR_API_KEY"></vitallens-file-widget>

<!-- Webcam-only widget -->
<vitallens-webcam-widget api-key="YOUR_API_KEY"></vitallens-webcam-widget>

Alternatively, you can use unpkg:

<script src="https://unpkg.com/vitallens/dist/vitallens.browser.js"></script>

Or Skypack if you prefer ES modules:

<script type="module">
  import { VitalLens } from 'https://cdn.skypack.dev/vitallens';
  // Continue as above…
</script>

Configuration Options

When creating a new VitalLens instance, you can configure various options:

Parameter Description Default
method Inference method: 'vitallens', 'g', 'chrom', or 'pos'. 'vitallens'
apiKey API key for the VitalLens API (required for method 'vitallens'). null
globalRoi Optional region of interest for face detection (object with { x0, y0, x1, y1 }). undefined
waveformMode Optional setting how waveform is returned: 'incremental', 'windowed', or 'complete'. (see below)

The default value for waveformMode is windowed if a stream is being analyzed, and complete if a file is being processed. Additional options (e.g., face detection settings, buffering) are available. See docs for details.

Understanding the Estimation Results

When you process a video or a MediaStream with vitallens.js, the library returns vital sign estimates in a structured object. vitallens.js is designed to process only a single face — so you always receive a single result object with the following structure:

export interface VitalLensResult {
  face: {
    // Detected face coordinates for each frame, formatted as [x0, y0, x1, y1].
    coordinates: Array<[number, number, number, number]>;
    // Confidence values for the face per frame.
    confidence: number[];
    // An explanatory note regarding the face detection.
    note: string;
  };
  vital_signs: {
    // Estimated global heart rate.
    heart_rate: {
      // Estimated heart rate value.
      value: number;
      // Unit of the heart rate value.
      unit: string;
      // Overall confidence of the heart rate estimation.
      confidence: number;
      // An explanatory note regarding the estimation.
      note: string;
    };
    // Estimated global respiratory rate.
    respiratory_rate?: {
      // Estimated respiratory rate value (in breaths per minute).
      value: number;
      // Unit of the respiratory rate value.
      unit: string;
      // Overall confidence of the respiratory rate estimation.
      confidence: number;
      // An explanatory note regarding the estimation.
      note: string;
    };
    // Photoplethysmogram (PPG) waveform estimation.
    ppg_waveform: {
      // Estimated PPG waveform data (one value per processed frame).
      data: number[];
      // Unit of the waveform data.
      unit: string;
      // Confidence values for the waveform estimation per frame.
      confidence: number[];
      // An explanatory note regarding the waveform estimation.
      note: string;
    };
    // Respiratory waveform estimation.
    respiratory_waveform?: {
      // Estimated respiratory waveform data (one value per processed frame).
      data: number[];
      // Unit of the waveform data.
      unit: string;
      // Confidence values for the waveform estimation per frame.
      confidence: number[];
      // An explanatory note regarding the waveform estimation.
      note: string;
    };
  };
  // A list of timestamps (one per processed frame).
  time: number[];
  // The frames per second (fps) of the input video.
  fps: number;
  // The effective fps used for inference.
  estFps: number;
  // A message providing additional information about the estimation.
  message: string;
}

Examples

Before running any of the examples, make sure to build the project by executing:

npm run build

Also, note that each example requires an API key. Replace YOUR_API_KEY with your actual API key when running the examples.

Try opening the HTML examples in your browser or running the Node script to see vitallens.js in action.

Securing your API Key

For security reasons, we recommend that you do not expose your API key directly in client-side code. There are two primary approaches to secure your API key:

1. Run Everything on your Server

If you are building a server-side application using Node.js, your API key remains securely on your server. Simply call the API directly from your backend code without exposing your credentials.

2. Use a Proxy Server for Client-Side Code

If you need to use vitallens.js in a browser, you can set up a proxy server. The proxy server receives requests from the client, attaches your API key (stored securely on the server), and forwards the request to the VitalLens API. This way, the API key is never exposed to the client.

Our client library supports this by accepting a proxyUrl option. For example:

import { VitalLens } from 'vitallens';
const vl = new VitalLens({
  method: 'vitallens',
  proxyUrl: 'https://your-proxy-server.com/api' // URL to your deployed proxy server
});

Or when using one of our widgets:

<vitallens-widget proxy-url="https://your-proxy-server.com/api"></vitallens-widget>

Sample Proxy Server Implementation

Below is a simple Node.js/Express proxy server implementation that you can use as a starting point:

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
const PORT = process.env.PORT || 3000;

// Securely store your API key in an environment variable
const API_KEY = process.env.VITALLENS_API_KEY;
const VITALLENS_ENDPOINT = 'https://api.rouast.com/vitallens-v2';

app.use(bodyParser.json({ limit: '10mb' }));

// Enable CORS for your allowed domain.
app.use(cors({
  origin: 'http://example.com', // Your allowed domain
  methods: ['GET', 'POST', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));

app.post('/', async (req, res) => {
  try {
    const response = await fetch(VITALLENS_ENDPOINT, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': API_KEY,
      },
      body: JSON.stringify(req.body),
    });
    const data = await response.text();
    res.status(response.status).send(data);
  } catch (error) {
    console.error('Proxy error:', error);
    res.status(500).send('Internal server error');
  }
});

app.listen(PORT, () => {
  console.log(`Proxy server listening on port ${PORT}`);
});

You can deploy this proxy server on any Node.js hosting platform (such as Heroku, Vercel, or your own server) and then set the URL as the proxyUrl in your VitalLens client configuration.

Development

Building the Library

To build the project from source, run:

npm run build

This compiles the TypeScript source and bundles the output for Node (both ESM and CommonJS), and the browser.

Running Tests

Execute the test suite with:

npm run test

For environment-specific tests, you can use:

npm run test:browser
npm run test:node
npm run test:browser-integration
npm run test:node-integration

Linting

Lint the code using:

npm run lint

License

This project is licensed under the MIT License.