### Minimal Browser Setup with CDN
Source: https://github.com/rouast-labs/vitallens.js/blob/main/examples/README.md
Quickest way to start using VitalLens in the browser without a build step. This example uses the raw VitalLens class to analyze a webcam feed via CDN.
```html
```
--------------------------------
### Build and Run Vitallens.js Examples
Source: https://github.com/rouast-labs/vitallens.js/blob/main/examples/README.md
Instructions for building the Vitallens.js library and running included examples locally. Replace YOUR_KEY with your actual API Key.
```bash
npm install
npm run build
```
```bash
API_KEY=YOUR_KEY npm run start:scan
```
```bash
API_KEY=YOUR_KEY npm run start:monitor
```
```bash
API_KEY=YOUR_KEY npm run start:file
```
```bash
API_KEY=YOUR_KEY npm run start:widget
```
```bash
API_KEY=YOUR_KEY npm run start:webcam-minimal
```
```bash
API_KEY=YOUR_KEY npm run start:file-node
```
--------------------------------
### Clone and Install Dependencies
Source: https://github.com/rouast-labs/vitallens.js/blob/main/CONTRIBUTING.md
Clone the repository and install project dependencies using npm. Ensure Node.js version 20 or higher is used.
```bash
git clone https://github.com/Rouast-Labs/vitallens.js.git
cd vitallens.js
npm install
```
--------------------------------
### Start Video Stream (Browser)
Source: https://github.com/rouast-labs/vitallens.js/blob/main/docs/ref.md
Initiates the camera stream and begins processing. If no stream is set, it attempts to acquire the user's webcam automatically.
```javascript
vl.startVideoStream();
```
--------------------------------
### Install Vitallens via NPM or Yarn
Source: https://github.com/rouast-labs/vitallens.js/blob/main/README.md
Install the Vitallens package using npm or yarn for use in Node.js projects or with bundlers.
```bash
npm install vitallens
# or
yarn add vitallens
```
--------------------------------
### startVideoStream
Source: https://github.com/rouast-labs/vitallens.js/blob/main/docs/ref.md
Starts the camera stream and begins processing. If a stream hasn't been set via `setVideoStream`, it attempts to acquire the user's webcam automatically. This method is browser-only.
```APIDOC
### `startVideoStream()`
*(Browser Only)*
Starts the camera stream and begins processing. If a stream hasn't been set via `setVideoStream`, it attempts to acquire the user's webcam automatically.
```javascript
vl.startVideoStream();
```
```
--------------------------------
### Start Real-Time Inference with `startVideoStream()`
Source: https://context7.com/rouast-labs/vitallens.js/llms.txt
Initiates continuous vital sign estimation from the active webcam. If no stream is set, it attempts to acquire the user's webcam. Emits 'vitals' events as results become available.
```javascript
import { VitalLens } from 'vitallens';
const vl = new VitalLens({ method: 'vitallens', apiKey: 'YOUR_API_KEY' });
async function startMonitoring() {
const videoEl = document.getElementById('video');
const stream = await navigator.mediaDevices.getUserMedia({ video: true });
videoEl.srcObject = stream;
await vl.setVideoStream(stream, videoEl);
vl.addEventListener('vitals', (result) => {
const hr = result.vitals.heart_rate;
if (hr) {
document.getElementById('hr-display').textContent =
`Heart Rate: ${hr.value.toFixed(1)} ${hr.unit} (confidence: ${(hr.confidence * 100).toFixed(0)}%)`;
}
});
vl.startVideoStream(); // Start inference loop
}
startMonitoring();
```
--------------------------------
### Stream Lifecycle Management (Pause/Resume)
Source: https://github.com/rouast-labs/vitallens.js/blob/main/examples/README.md
Manage the stream lifecycle by toggling processing to save bandwidth when results are not actively being viewed. This example shows how to pause and resume the video stream.
```javascript
let isProcessing = true;
const btn = document.getElementById('toggle-btn');
btn.onclick = () => {
if (isProcessing) {
// Pauses API calls, but keeps the webcam active
vl.pauseVideoStream();
btn.textContent = 'Resume';
} else {
// Resumes API calls
vl.startVideoStream();
btn.textContent = 'Pause';
}
isProcessing = !isProcessing;
};
// Cleanup when leaving the page
window.onbeforeunload = () => {
vl.stopVideoStream();
};
```
--------------------------------
### Node.js/Express Proxy Implementation
Source: https://github.com/rouast-labs/vitallens.js/blob/main/docs/proxies.md
A production-ready example of a proxy server using Node.js and Express. It handles model resolution and video stream forwarding, securely using an API key from environment variables.
```javascript
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 API_BASE = 'https://api.rouast.com/vitallens-v3';
// Increase limit for video file uploads if necessary
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.raw({ type: 'application/octet-stream', limit: '50mb' }));
// Enable CORS for your allowed domain
app.use(cors({
origin: 'http://example.com', // Your allowed domain
methods: ['GET', 'POST', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Encoding', 'X-State', 'X-Model', 'X-Origin']
}));
// 1. Forward Model Resolution
app.get('/resolve-model', async (req, res) => {
try {
const upstreamUrl = new URL(`${API_BASE}/resolve-model`);
upstreamUrl.search = new URLSearchParams(req.query).toString();
const response = await fetch(upstreamUrl, {
method: 'GET',
headers: { 'x-api-key': API_KEY },
});
const data = await response.json();
res.status(response.status).json(data);
} catch (error) {
console.error('Proxy Resolve error:', error);
res.status(500).send('Internal server error');
}
});
// 2. Forward Stream/Inference
app.post(['/stream', '/file'], async (req, res) => {
try {
// Forward to the exact same path on the upstream API
const upstreamUrl = `${API_BASE}${req.path}`;
const response = await fetch(upstreamUrl, {
method: 'POST',
headers: {
'Content-Type': req.headers['content-type'] || 'application/json',
'x-api-key': API_KEY,
// Forward custom headers used by the client
'X-Encoding': req.headers['x-encoding'] || '',
'X-State': req.headers['x-state'] || '',
'X-Model': req.headers['x-model'] || '',
'X-Origin': req.headers['x-origin'] || ''
},
body: req.headers['content-type'] === 'application/json'
? JSON.stringify(req.body)
: req.body
});
const data = await response.text();
res.status(response.status).send(data);
} catch (error) {
console.error('Proxy Inference error:', error);
res.status(500).send('Internal server error');
}
});
app.listen(PORT, () => {
console.log(`Proxy server listening on port ${PORT}`);
});
```
--------------------------------
### Example VitalLensResult Object
Source: https://context7.com/rouast-labs/vitallens.js/llms.txt
An example of a `VitalLensResult` object obtained after processing a video file. It demonstrates the structure and typical values for face coordinates, vital signs, and waveform data.
```typescript
const exampleResult = {
face: {
coordinates: [[247, 52, 444, 332], /* ...per frame */],
confidence: [0.6115, 0.9207, 0.9183],
note: "Face detection coordinates (x0,y0,x1,y1)"
},
vitals: {
heart_rate: { value: 60.21, unit: "bpm", confidence: 0.9205, note: "Global HR estimate" },
respiratory_rate: { value: 12.08, unit: "bpm", confidence: 0.9969, note: "Global RR estimate" },
hrv_sdnn: { value: 45.3, unit: "ms", confidence: 0.85, note: "HRV SDNN" },
hrv_rmssd: { value: 38.1, unit: "ms", confidence: 0.82, note: "HRV RMSSD" },
},
waveforms: {
ppg_waveform: { data: [0.12, 0.15, 0.18], confidence: [0.99, 0.99], unit: "unitless", note: "" },
respiratory_waveform: { data: [0.01, 0.02, 0.03], confidence: [0.95, 0.95], unit: "unitless", note: "" },
},
fps: 30.0,
model_used: "vitallens-2.0",
message: "The provided values are estimates for general wellness only."
};
```
--------------------------------
### Node.js File Processing
Source: https://github.com/rouast-labs/vitallens.js/blob/main/examples/README.md
Process a video file server-side using Node.js. This example demonstrates initializing VitalLens, listening for progress updates, and processing a video file.
```javascript
import { VitalLens } from 'vitallens';
const vl = new VitalLens({
method: 'vitallens',
apiKey: process.env.VITALLENS_API_KEY
});
// Listen for progress updates
vl.addEventListener('fileProgress', (msg) => console.log(msg));
async function run() {
try {
const result = await vl.processVideoFile('./examples/sample_video_1.mp4');
console.log('Result:', JSON.stringify(result, null, 2));
} catch (error) {
console.error('Processing failed:', error);
} finally {
await vl.close();
}
}
run();
```
--------------------------------
### Initialize and Start VitalLens Webcam Stream
Source: https://github.com/rouast-labs/vitallens.js/blob/main/examples/browser/webcam_minimal.html
This code initializes VitalLens with your API key, sets up the webcam stream, and begins processing video for vital sign detection. It logs detected vitals to the console and automatically stops after 30 seconds. Ensure you replace 'YOUR_API_KEY' with your actual key.
```javascript
import { VitalLens } from '../vitallens.browser.js';
const options = {
method: 'vitallens',
apiKey: 'YOUR_API_KEY', // Replace with actual API key
};
const vitallens = new VitalLens(options);
async function detectVitals() {
// Set up webcam
const video = document.getElementById('video');
const stream = await navigator.mediaDevices.getUserMedia({
audio: false,
video: { facingMode: 'user' },
});
video.srcObject = stream;
await vitallens.setVideoStream(stream, video);
// Listen for vitals events
vitallens.addEventListener('vitals', (result) => {
console.log(result); // Log detected vitals
});
// Start VitalLens
vitallens.startVideoStream();
// Stop detection after 30 seconds
setTimeout(() => vitallens.stop(), 30000);
}
// Initialize and start VitalLens
window.onload = async () => {
console.log('Initializing VitalLens...');
await detectVitals();
};
```
--------------------------------
### Basic Usage of vitallens-scan Component
Source: https://github.com/rouast-labs/vitallens.js/blob/main/docs/components.md
Use the `` tag to embed a guided 30-second measurement process. Requires an API key for authentication.
```html
```
--------------------------------
### Attach Media Stream to VitalLens (Browser)
Source: https://context7.com/rouast-labs/vitallens.js/llms.txt
Manually attach an existing MediaStream and an optional video element to the VitalLens instance in the browser. This is used when managing camera permissions and UI independently. Must be called before starting the video stream.
```javascript
import { VitalLens } from 'vitallens';
const vl = new VitalLens({ method: 'vitallens', apiKey: 'YOUR_API_KEY' });
async function init() {
const videoEl = document.getElementById('my-video');
// Acquire camera
const stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'user', width: 640, height: 480 },
audio: false,
});
videoEl.srcObject = stream;
// Attach to VitalLens
await vl.setVideoStream(stream, videoEl);
console.log('Stream attached, ready to start.');
}
init();
```
--------------------------------
### Integrate `` for Health Checks
Source: https://context7.com/rouast-labs/vitallens.js/llms.txt
Use this component for a 30-second guided health check. It manages face positioning, lighting, progress, and results. Ideal for telemedicine waiting rooms or onboarding.
```html
```
--------------------------------
### setVideoStream(stream, videoElement) — Attach Media Stream
Source: https://context7.com/rouast-labs/vitallens.js/llms.txt
Manually attaches an existing MediaStream and an optional video element to the VitalLens instance. This is useful when your application handles camera permissions and UI independently. Must be called before starting the video stream.
```APIDOC
## setVideoStream(stream, videoElement) — Attach Media Stream
### Description
*(Browser Only)* Manually attaches an existing `MediaStream` and an optional `