react-native-vision-camera-spoof-detector 1.1.26 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +132 -240
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -3,31 +3,31 @@
3
3
  [![npm version](https://badge.fury.io/js/react-native-vision-camera-spoof-detector.svg)](https://badge.fury.io/js/react-native-vision-camera-spoof-detector)
4
4
  [![GitHub](https://img.shields.io/badge/GitHub-Repository-blue)](https://github.com/dpraful/react-native-vision-camera-spoof-detector)
5
5
 
6
- High-performance face anti-spoofing and liveness detection module for React Native Vision Camera. Features TensorFlow Lite with GPU acceleration, optimized YUV processing, and real-time blink detection for robust liveness verification.
6
+ High-performance face anti-spoofing and liveness detection for React Native Vision Camera. The current implementation exposes a native Vision Camera output that processes frames on Android and iOS and reports a `FaceAntiSpoofingResult` back to JavaScript.
7
7
 
8
- ## 🎯 Features
8
+ ## Features
9
9
 
10
- - **🚀 Real-time Performance**: GPU-accelerated TensorFlow Lite processing for smooth 60fps detection
11
- - **🎯 High Accuracy**: Advanced ML models for distinguishing live faces from spoofing attempts
12
- - **👁️ Blink Detection**: Native blink detection for enhanced liveness verification
13
- - **📱 Optimized YUV Processing**: Efficient image data handling for React Native
14
- - **🔧 Easy Integration**: Seamlessly integrates with `react-native-vision-camera`
15
- - **⚡ Face Stability Tracking**: Automatic stable face detection with customizable thresholds
16
- - **🛡️ Face Centering**: Intelligent face positioning validation in frame
17
- - **📊 Anti-spoofing Confidence**: Detailed confidence scores with multiple detection models
18
- - **🔄 Batched Updates**: Optimized state management with minimal re-renders
10
+ - Native Android and iOS detection pipeline
11
+ - Vision Camera 5 `CameraOutput` integration via Nitro hybrid objects
12
+ - TensorFlow Lite inference with GPU or NNAPI fallback on Android
13
+ - Optimized BGRA/RGBA frame sampling, filtering, and resolution handling
14
+ - JS callbacks for `onResult` and `onError`
15
+ - Optional explicit availability and initialization checks
16
+ - No separate face-detector output is required for the basic anti-spoof camera-output flow
19
17
 
20
- ## 📋 Requirements
18
+ ## Requirements
21
19
 
22
- - React Native >= 0.76.0
23
- - React Native Vision Camera `^5.0.0`
20
+ - React Native `>= 0.60.0` (Vision Camera 5.x usage is the intended path)
21
+ - `react-native-vision-camera` `^5.0.0`
22
+ - `react-native-nitro-modules` `^0.37.1`
23
+ - `react-native-worklets` `^0.12.0`
24
24
  - `react-native-vision-camera-worklets` `^5.0.0`
25
25
  - iOS 11.0 or later
26
- - `react-native-vision-camera-face-detector` (required for the face-gated example below)
26
+ - Android support through the package's native modules and bundled TensorFlow Lite model
27
27
 
28
- ## 📦 Installation
28
+ ## Installation
29
29
 
30
- ### Step 1: Install the package
30
+ ### 1) Install package
31
31
 
32
32
  ```bash
33
33
  npm install react-native-vision-camera-spoof-detector
@@ -35,17 +35,17 @@ npm install react-native-vision-camera-spoof-detector
35
35
  yarn add react-native-vision-camera-spoof-detector
36
36
  ```
37
37
 
38
- ### Step 2: Install peer dependencies
38
+ ### 2) Install required peer dependencies
39
39
 
40
40
  ```bash
41
- npm install react-native-vision-camera react-native-reanimated react-native-worklets react-native-vision-camera-worklets react-native-vision-camera-face-detector
41
+ npm install react-native-vision-camera react-native-nitro-modules react-native-worklets react-native-vision-camera-worklets
42
42
  # or
43
- yarn add react-native-vision-camera react-native-reanimated react-native-worklets react-native-vision-camera-worklets react-native-vision-camera-face-detector
43
+ yarn add react-native-vision-camera react-native-nitro-modules react-native-worklets react-native-vision-camera-worklets
44
44
  ```
45
45
 
46
- ### Step 3: Configure iOS
46
+ ### 3) iOS setup
47
47
 
48
- Install the CocoaPods dependencies from the iOS directory:
48
+ Run pod install for the app:
49
49
 
50
50
  ```bash
51
51
  cd ios
@@ -53,87 +53,66 @@ pod install
53
53
  cd ..
54
54
  ```
55
55
 
56
- Add a camera usage description to `ios/<YourApp>/Info.plist`:
56
+ Add camera permission text to the app Info.plist:
57
57
 
58
58
  ```xml
59
59
  <key>NSCameraUsageDescription</key>
60
60
  <string>This app uses the camera for face liveness verification.</string>
61
61
  ```
62
62
 
63
- Open the generated `.xcworkspace` in Xcode, or run the app with the React Native CLI. The package pod bundles `FaceAntiSpoofing.tflite` and declares its `TensorFlowLiteSwift` and `VisionCamera` dependencies automatically. No manual model copy is required.
63
+ ### 4) Android setup
64
64
 
65
- ### Step 4: Configure Android (if not auto-linked)
65
+ For modern React Native projects, the native module is auto-linked by the app build. If your project is not auto-linked, ensure the library is included in the app build and Gradle resolves the Android native dependencies.
66
66
 
67
- Add to `android/app/build.gradle`:
67
+ ## Quick start
68
68
 
69
- ```gradle
70
- dependencies {
71
- implementation project(':react-native-vision-camera-spoof-detector')
72
- }
73
- ```
74
-
75
- ### Step 5: Link native module (for React Native < 0.60)
76
-
77
- ```bash
78
- react-native link react-native-vision-camera-spoof-detector
79
- ```
80
-
81
- ## 🚀 Quick Start
82
-
83
- Vision Camera 5 uses camera outputs for this package. The anti-spoof output can be combined with the face detector output and enabled only while a face is visible.
69
+ This package exposes a native output hook that can be attached directly to the `Camera` component.
84
70
 
85
- ```javascript
86
- import React, { useEffect, useState } from 'react';
87
- import { StyleSheet, Text, useWindowDimensions, View } from 'react-native';
71
+ ```tsx
72
+ import React, { useEffect } from 'react';
73
+ import { SafeAreaView, Text, View, StyleSheet } from 'react-native';
88
74
  import {
89
75
  Camera,
90
76
  useCameraDevice,
91
77
  useCameraPermission,
92
78
  } from 'react-native-vision-camera';
93
- import { useFaceDetectorOutput } from 'react-native-vision-camera-face-detector';
94
79
  import { useFaceAntiSpoofFrameOutput } from 'react-native-vision-camera-spoof-detector';
95
80
 
96
- const CameraScreen = () => {
81
+ export default function AntiSpoofScreen() {
97
82
  const device = useCameraDevice('front');
98
83
  const { hasPermission, requestPermission } = useCameraPermission();
99
- const { width: windowWidth, height: windowHeight } = useWindowDimensions();
100
- const [faces, setFaces] = useState([]);
101
- const [detectionError, setDetectionError] = useState(null);
102
- const [spoofResult, setSpoofResult] = useState(null);
103
84
 
104
85
  useEffect(() => {
105
- if (!hasPermission) requestPermission();
86
+ if (!hasPermission) {
87
+ requestPermission();
88
+ }
106
89
  }, [hasPermission, requestPermission]);
107
90
 
108
- const faceDetectorOutput = useFaceDetectorOutput({
109
- cameraFacing: 'front',
110
- autoMode: true,
111
- windowWidth,
112
- windowHeight,
113
- performanceMode: 'fast',
114
- trackingEnabled: true,
115
- onFacesDetected(detectedFaces) {
116
- setDetectionError(null);
117
- setFaces(detectedFaces);
118
- if (detectedFaces.length === 0) setSpoofResult(null);
119
- },
120
- onError(error) {
121
- setDetectionError(error.message);
122
- },
123
- });
124
-
125
91
  const antiSpoofOutput = useFaceAntiSpoofFrameOutput({
92
+ targetResolution: { width: 720, height: 1280 },
126
93
  onResult(result) {
127
- setSpoofResult(result);
94
+ console.log('anti-spoof result:', result);
95
+ },
96
+ onError(error) {
97
+ console.warn('anti-spoof error:', error);
128
98
  },
129
99
  });
130
100
 
131
- const outputs = faces.length > 0
132
- ? [faceDetectorOutput, antiSpoofOutput]
133
- : [faceDetectorOutput];
134
-
135
- if (!hasPermission) return <Message text="Camera permission is required." />;
136
- if (!device) return <Message text="No front camera is available." />;
101
+ if (!hasPermission) {
102
+ return (
103
+ <SafeAreaView style={styles.centered}>
104
+ <Text>Camera permission is required.</Text>
105
+ </SafeAreaView>
106
+ );
107
+ }
108
+
109
+ if (!device) {
110
+ return (
111
+ <SafeAreaView style={styles.centered}>
112
+ <Text>No front camera available.</Text>
113
+ </SafeAreaView>
114
+ );
115
+ }
137
116
 
138
117
  return (
139
118
  <View style={styles.container}>
@@ -141,65 +120,33 @@ const CameraScreen = () => {
141
120
  style={StyleSheet.absoluteFill}
142
121
  device={device}
143
122
  isActive
144
- outputs={outputs}
123
+ outputs={[antiSpoofOutput]}
145
124
  />
146
-
147
- <View style={styles.statusContainer}>
148
- <Text style={styles.statusText}>
149
- {detectionError ?? `${faces.length} face${faces.length === 1 ? '' : 's'} detected`}
150
- </Text>
151
- <Text style={styles.statusText}>
152
- {faces.length === 0
153
- ? 'Waiting for face...'
154
- : spoofResult
155
- ? JSON.stringify(spoofResult)
156
- : 'Anti-spoof processing...'}
157
- </Text>
158
- </View>
159
125
  </View>
160
126
  );
161
- };
162
-
163
- const Message = ({ text }) => (
164
- <View style={styles.messageContainer}>
165
- <Text style={styles.messageText}>{text}</Text>
166
- </View>
167
- );
127
+ }
168
128
 
169
129
  const styles = StyleSheet.create({
170
130
  container: { flex: 1 },
171
- messageContainer: {
131
+ centered: {
172
132
  flex: 1,
173
- alignItems: 'center',
174
133
  justifyContent: 'center',
175
- paddingHorizontal: 24,
176
- },
177
- messageText: { fontSize: 16, textAlign: 'center' },
178
- statusContainer: {
179
- position: 'absolute',
180
- top: 56,
181
- alignSelf: 'center',
182
- paddingHorizontal: 14,
183
- paddingVertical: 8,
184
- borderRadius: 16,
185
- backgroundColor: 'rgba(0, 0, 0, 0.65)',
134
+ alignItems: 'center',
186
135
  },
187
- statusText: { color: '#ffffff', fontSize: 14, marginVertical: 2 },
188
136
  });
189
-
190
- export default CameraScreen;
191
137
  ```
192
138
 
193
- The anti-spoof output callback receives a result after native inference. No manual `runOnJS`, frame processor, or explicit initialization call is required for this output API. The output may be omitted until a face is detected, as shown above.
139
+ The callback fires from the native detection pipeline after each processed frame. This output path is designed to be used directly with the Vision Camera `outputs` array.
194
140
 
195
- ## 📚 API Reference
141
+ ## API reference
196
142
 
197
143
  ### `useFaceAntiSpoofFrameOutput(options?)`
198
144
 
199
- Creates a Vision Camera 5 camera output for native anti-spoofing inference.
145
+ Creates a native Vision Camera 5 output for anti-spoofing inference.
200
146
 
201
- ```javascript
147
+ ```tsx
202
148
  const antiSpoofOutput = useFaceAntiSpoofFrameOutput({
149
+ targetResolution: { width: 720, height: 1280 },
203
150
  onResult(result) {
204
151
  console.log(result);
205
152
  },
@@ -209,178 +156,123 @@ const antiSpoofOutput = useFaceAntiSpoofFrameOutput({
209
156
  });
210
157
  ```
211
158
 
212
- Pass the returned output in the `Camera` component's `outputs` array. The callback runs on the React Native runtime after native inference.
159
+ Returned value should be included in the `Camera` component `outputs` array.
160
+
161
+ Options:
213
162
 
214
- **Options**: `onResult(result)` and optional `onError(error)`.
163
+ ```ts
164
+ interface UseFaceAntiSpoofFrameOutputOptions {
165
+ targetResolution?: { width: number; height: number };
166
+ onResult?: (result: FaceAntiSpoofingResult) => void;
167
+ onError?: (error: Error) => void;
168
+ }
169
+ ```
215
170
 
216
171
  ---
217
172
 
218
173
  ### `initializeFaceAntiSpoof()`
219
174
 
220
- Initializes the native module when an application needs an explicit startup check or model-loading diagnostics. It is not required when using `useFaceAntiSpoofFrameOutput()`.
175
+ Starts the native module and performs a basic model/init check.
221
176
 
222
- ```javascript
223
- const success = await initializeFaceAntiSpoof();
177
+ ```ts
178
+ const initialized = await initializeFaceAntiSpoof();
224
179
  ```
225
180
 
226
- **Returns**: `Promise<boolean>` - True if successful
181
+ Returns `Promise<boolean>`.
227
182
 
228
183
  ---
229
184
 
230
185
  ### `isFaceAntiSpoofAvailable()`
231
186
 
232
- Checks if the module is available on the device.
187
+ Checks whether the native module is present for the current device/platform.
233
188
 
234
- ```javascript
189
+ ```ts
235
190
  const available = isFaceAntiSpoofAvailable();
236
191
  ```
237
192
 
238
- **Returns**: `boolean`
193
+ Returns `boolean`.
239
194
 
240
195
  ---
241
196
 
242
197
  ### `FaceAntiSpoofingResult`
243
198
 
244
- ```typescript
199
+ ```ts
245
200
  interface FaceAntiSpoofingResult {
246
- isLive: boolean; // Real face (true) or spoof (false)
247
- label: string; // Usually "live", "spoof", or "error"
248
- neuralNetworkScore: number; // 0.0-1.0 confidence
249
- laplacianScore: number; // Image quality score
250
- combinedScore: number; // Weighted average
251
- error?: string; // Error message if any
201
+ isLive: boolean;
202
+ label: string;
203
+ neuralNetworkScore: number;
204
+ laplacianScore: number;
205
+ combinedScore: number;
206
+ confidence: number;
207
+ error?: string;
252
208
  }
253
209
  ```
254
210
 
255
- ## 🔧 Configuration
256
-
257
- ```javascript
258
- // Anti-spoofing sensitivity (0.0-1.0, lower = more lenient)
259
- const antispooflevel = 0.35;
260
-
261
- // Liveness verification mode
262
- // 0: Anti-spoofing only
263
- // 1: Anti-spoofing + blink detection
264
- const livenessLevel = 1;
265
-
266
- // Customizable thresholds
267
- const FACE_STABILITY_THRESHOLD = 3; // Frames for stable face
268
- const FACE_MOVEMENT_THRESHOLD = 15; // Max pixel movement
269
- const BLINK_THRESHOLD = 0.3; // Eye closure probability
270
- const REQUIRED_BLINKS = 3; // Blinks for liveness
271
- const REQUIRED_CONSECUTIVE_LIVE_FRAMES = 3; // Consecutive live frames
272
- const REAL_LAPLACIAN_THRESHOLD = 3500; // Image quality threshold
273
- const FACE_CENTER_THRESHOLD_X = 0.2; // X-axis tolerance
274
- const FACE_CENTER_THRESHOLD_Y = 0.15; // Y-axis tolerance
275
- ```
276
-
277
- ## 🎮 Complete Examples
278
-
279
- The [Quick Start](#-quick-start) above shows the basic frame-processor integration. For the complete capture flow, face detection, liveness, and UI patterns, see the [project wiki](https://github.com/dpraful/react-native-vision-camera-spoof-detector/wiki).
211
+ Result fields:
280
212
 
281
- ## 🔍 Attack Detection Capabilities
213
+ - `isLive`: true for a likely real face, false for a spoof attempt
214
+ - `label`: human-readable label such as `Live Face` or `Spoof Face`
215
+ - `neuralNetworkScore`: raw model score from the TFLite classifier
216
+ - `laplacianScore`: image variance / quality score used to detect blur or non-real textures
217
+ - `combinedScore`: combined weighted score constructed by the native implementation
218
+ - `confidence`: derived confidence value for the final decision
282
219
 
283
- The module detects and prevents:
284
- - ✅ Print attacks (photos)
285
- - ✅ Display attacks (screens/tablets)
286
- - ✅ Mask attacks (with blink detection)
287
- - ✅ Replay attacks (videos)
220
+ ## Android and iOS implementation notes
288
221
 
289
- Performance depends on:
290
- - Image quality
291
- - Lighting conditions
292
- - Face angle and positioning
293
- - Device camera specs
222
+ ### Android
294
223
 
295
- ## ⚙️ Performance Tips
224
+ - Uses a native `ImageAnalysis`-based output pipeline
225
+ - Reads RGBA frame data and applies brightness / variance gating before inference
226
+ - Uses the bundled TensorFlow Lite model and prefers GPU delegate, with NNAPI/CPU fallback
227
+ - Normalizes frames for model input and returns a JS callback result after evaluation
296
228
 
297
- 1. Use `performanceMode: 'fast'` in Face Detector
298
- 2. Module automatically batches state updates
299
- 3. Adjust `FRAME_PROCESSOR_MIN_INTERVAL_MS` as needed
300
- 4. GPU acceleration is used automatically when available
301
- 5. Proper frame release prevents memory leaks
229
+ ### iOS
302
230
 
303
- ## 📱 Platform Support
231
+ - Uses an `AVCaptureVideoDataOutput` pipeline with a native sample-buffer delegate
232
+ - Converts BGRA pixel buffers to a normalized RGB input for the detector
233
+ - Filters frames using brightness and variance checks before inference
234
+ - Returns the evaluation result through the same `onResult` callback contract
304
235
 
305
- | Platform | Status | GPU | Notes |
306
- |----------|--------|-----|-------|
307
- | Android | ✅ Supported | Yes | TensorFlow Lite model bundled in the AAR |
308
- | iOS | ✅ Supported | CPU | Requires CocoaPods and iOS 11+ |
309
- | Web | ❌ No | N/A | Not applicable |
236
+ ## Troubleshooting
310
237
 
311
- ## 🐛 Troubleshooting
238
+ ### Module not available
312
239
 
313
- **Module won't initialize**
314
- ```javascript
315
- const available = isFaceAntiSpoofAvailable();
316
- if (!available) {
317
- console.log('Not available on this device');
240
+ ```ts
241
+ if (!isFaceAntiSpoofAvailable()) {
242
+ console.warn('Face anti-spoofing native module is unavailable on this device.');
318
243
  }
319
244
  ```
320
245
 
321
- - iOS: run `pod install` from the `ios` directory and rebuild the app from the generated workspace.
322
- - iOS: verify `NSCameraUsageDescription` exists in the app's `Info.plist`.
323
- - Check the initialization promise result and inspect the native logs for model-loading errors.
324
-
325
- **Low accuracy**
326
- - Check lighting conditions
327
- - Ensure face is centered
328
- - Adjust `antispooflevel` parameter
329
- - Verify the `FaceAntiSpoofing.tflite` model is bundled (the package does this automatically on iOS)
330
-
331
- **Performance issues**
332
- - Reduce frame processing frequency
333
- - Use lower camera resolution
334
- - Enable fast performance mode
335
- - Check device temperature
336
-
337
- **Face detection fails**
338
- - Ensure clear face visibility
339
- - Check camera permissions
340
- - Verify sufficient lighting
341
- - Check minimum face size threshold
342
-
343
- ## 📖 Documentation
246
+ ### iOS issues
344
247
 
345
- - [Project Wiki](https://github.com/dpraful/react-native-vision-camera-spoof-detector/wiki)
346
- - [Changelog](./CHANGELOG.md)
347
- - [Contributing Guide](./CONTRIBUTING.md)
248
+ - Ensure `NSCameraUsageDescription` exists in the app's Info.plist
249
+ - Run `pod install` inside the iOS folder after dependency updates
250
+ - Rebuild the generated `.xcworkspace` in Xcode
348
251
 
349
- ## 🤝 Contributing
252
+ ### Android issues
350
253
 
351
- Contributions welcome! See [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines.
254
+ - Confirm the app has camera permissions
255
+ - Ensure the module is properly linked in the app project
256
+ - Check native logs for TFLite loading or delegate errors
352
257
 
353
- ## 📄 License
258
+ ## Platform support
354
259
 
355
- JESCON TECHNOLOGIES PVT LTD License - see [LICENSE](./LICENSE) file for details.
260
+ | Platform | GPU acceleration | Status | Notes |
261
+ |----------|------------------|--------|-------|
262
+ | Android | ✅ Yes | ✅ Supported | Uses TensorFlow Lite GPU delegate when available, with NNAPI/CPU fallback |
263
+ | iOS | ✅ Yes | ✅ Supported | Uses TensorFlow Lite Metal GPU delegate when available, with CPU fallback |
264
+ | Web | ❌ No | ❌ Not supported | Native camera processing only |
356
265
 
357
- ## 👨‍💼 Author
266
+ ## License
358
267
 
359
- **PRAFULDAS M M**
360
- - Company: JESCON TECHNOLOGIES PVT LTD
361
- - Location: Thrissur, Kerala, India
362
- - Email: jescontechnologies@gmail.com
268
+ MIT. See [LICENSE](./LICENSE).
363
269
 
364
- ## 🔗 Quick Links
270
+ ## Repository
365
271
 
366
- - [NPM Package](https://www.npmjs.com/package/react-native-vision-camera-spoof-detector)
367
- - [GitHub Repository](https://github.com/dpraful/react-native-vision-camera-spoof-detector)
368
- - [React Native Vision Camera](https://react-native-vision-camera.com)
369
- - [TensorFlow Lite](https://www.tensorflow.org/lite)
272
+ - GitHub: https://github.com/dpraful/react-native-vision-camera-spoof-detector
273
+ - NPM: https://www.npmjs.com/package/react-native-vision-camera-spoof-detector
370
274
 
371
- ## 📞 Support & Community
275
+ ## Author
372
276
 
373
- - 🐛 [Report Issues](https://github.com/dpraful/react-native-vision-camera-spoof-detector/issues)
374
- - 💬 [GitHub Discussions](https://github.com/dpraful/react-native-vision-camera-spoof-detector/discussions)
375
- - 📧 Email: jescontechnologies@gmail.com
376
-
377
- ## 🙏 Acknowledgments
378
-
379
- Built with:
380
- - [TensorFlow Lite](https://www.tensorflow.org/lite)
381
- - [React Native Vision Camera](https://react-native-vision-camera.com)
382
- - [React Native Worklets](https://docs.swmansion.com/react-native-worklets/)
383
-
384
- ---
277
+ JESCON TECHNOLOGIES PVT LTD
385
278
 
386
- Made with ❤️ by JESCON TECHNOLOGIES PVT LTD
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-vision-camera-spoof-detector",
3
- "version": "1.1.26",
3
+ "version": "1.2.0",
4
4
  "description": "High-performance face anti-spoofing and liveness detection module for React Native Vision Camera. Uses TensorFlow Lite with GPU acceleration and optimized YUV processing.",
5
5
  "homepage": "https://github.com/dpraful/react-native-vision-camera-spoof-detector",
6
6
  "repository": {