@masumdev/rn-camera-ai-mlkit 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +250 -2
- package/lib/commonjs/detector/MLKitTextRecognizer.js +387 -0
- package/lib/commonjs/detector/MLKitTextRecognizer.js.map +1 -0
- package/lib/commonjs/detector/index.js +17 -0
- package/lib/commonjs/detector/index.js.map +1 -0
- package/lib/commonjs/index.js +39 -0
- package/lib/commonjs/index.js.map +1 -0
- package/lib/commonjs/package.json +1 -0
- package/lib/commonjs/parser/documentFraming.js +279 -0
- package/lib/commonjs/parser/documentFraming.js.map +1 -0
- package/lib/commonjs/parser/index.js +28 -0
- package/lib/commonjs/parser/index.js.map +1 -0
- package/lib/commonjs/parser/mlkitTextParser.js +287 -0
- package/lib/commonjs/parser/mlkitTextParser.js.map +1 -0
- package/lib/commonjs/types/index.js +17 -0
- package/lib/commonjs/types/index.js.map +1 -0
- package/lib/commonjs/types/mlkit.js +6 -0
- package/lib/commonjs/types/mlkit.js.map +1 -0
- package/lib/module/detector/MLKitTextRecognizer.js +380 -0
- package/lib/module/detector/MLKitTextRecognizer.js.map +1 -0
- package/lib/module/detector/index.js +4 -0
- package/lib/module/detector/index.js.map +1 -0
- package/lib/module/index.js +6 -0
- package/lib/module/index.js.map +1 -0
- package/lib/module/package.json +1 -0
- package/lib/module/parser/documentFraming.js +272 -0
- package/lib/module/parser/documentFraming.js.map +1 -0
- package/lib/module/parser/index.js +5 -0
- package/lib/module/parser/index.js.map +1 -0
- package/lib/module/parser/mlkitTextParser.js +281 -0
- package/lib/module/parser/mlkitTextParser.js.map +1 -0
- package/lib/module/types/index.js +4 -0
- package/lib/module/types/index.js.map +1 -0
- package/lib/module/types/mlkit.js +4 -0
- package/lib/module/types/mlkit.js.map +1 -0
- package/lib/typescript/commonjs/detector/MLKitTextRecognizer.d.ts +59 -0
- package/lib/typescript/commonjs/detector/MLKitTextRecognizer.d.ts.map +1 -0
- package/lib/typescript/commonjs/detector/index.d.ts +2 -0
- package/lib/typescript/commonjs/detector/index.d.ts.map +1 -0
- package/lib/typescript/commonjs/index.d.ts +4 -0
- package/lib/typescript/commonjs/index.d.ts.map +1 -0
- package/lib/typescript/commonjs/package.json +1 -0
- package/lib/typescript/commonjs/parser/documentFraming.d.ts +66 -0
- package/lib/typescript/commonjs/parser/documentFraming.d.ts.map +1 -0
- package/lib/typescript/commonjs/parser/index.d.ts +3 -0
- package/lib/typescript/commonjs/parser/index.d.ts.map +1 -0
- package/lib/typescript/commonjs/parser/mlkitTextParser.d.ts +18 -0
- package/lib/typescript/commonjs/parser/mlkitTextParser.d.ts.map +1 -0
- package/lib/typescript/commonjs/types/index.d.ts +2 -0
- package/lib/typescript/commonjs/types/index.d.ts.map +1 -0
- package/lib/typescript/commonjs/types/mlkit.d.ts +241 -0
- package/lib/typescript/commonjs/types/mlkit.d.ts.map +1 -0
- package/lib/typescript/module/detector/MLKitTextRecognizer.d.ts +59 -0
- package/lib/typescript/module/detector/MLKitTextRecognizer.d.ts.map +1 -0
- package/lib/typescript/module/detector/index.d.ts +2 -0
- package/lib/typescript/module/detector/index.d.ts.map +1 -0
- package/lib/typescript/module/index.d.ts +4 -0
- package/lib/typescript/module/index.d.ts.map +1 -0
- package/lib/typescript/module/package.json +1 -0
- package/lib/typescript/module/parser/documentFraming.d.ts +66 -0
- package/lib/typescript/module/parser/documentFraming.d.ts.map +1 -0
- package/lib/typescript/module/parser/index.d.ts +3 -0
- package/lib/typescript/module/parser/index.d.ts.map +1 -0
- package/lib/typescript/module/parser/mlkitTextParser.d.ts +18 -0
- package/lib/typescript/module/parser/mlkitTextParser.d.ts.map +1 -0
- package/lib/typescript/module/types/index.d.ts +2 -0
- package/lib/typescript/module/types/index.d.ts.map +1 -0
- package/lib/typescript/module/types/mlkit.d.ts +241 -0
- package/lib/typescript/module/types/mlkit.d.ts.map +1 -0
- package/package.json +115 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ma'sum
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,251 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @masumdev/rn-camera-ai-mlkit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Google ML Kit on-device OCR & Text Recognition adapter for [`@masumdev/rn-camera-ai`](https://lib.masumdev.id/rn-camera-ai/) powered by [`react-native-vision-camera-mlkit`](https://github.com/pedrol2b/react-native-vision-camera-mlkit) (Nitro Modules + VisionCamera v5).
|
|
4
|
+
|
|
5
|
+
Provides synchronous, worklet-safe on-device text recognition across `block`, `line`, and `element` (word) granularities with zero-copy `yuv` camera buffers (`android.media.Image`), normalized `[0..1]` overlay coordinates, and built-in structured entity classification (Indonesian 16-digit NIK/KTP, Email, Phone, URL, Currency).
|
|
6
|
+
|
|
7
|
+
[](https://www.npmjs.com/package/@masumdev/rn-camera-ai-mlkit)
|
|
8
|
+
[](https://github.com/masumrpg/nodejs-lib/blob/main/LICENSE)
|
|
9
|
+
[](https://www.typescriptlang.org/)
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## Key Features
|
|
14
|
+
|
|
15
|
+
- **⚡ Zero-Copy YUV Camera Pipeline (`preferredPixelFormat: 'yuv'`)**: Instructs `<CameraAI />` to stream native `YUV_420_888` buffers so Google ML Kit `InputImage.fromMediaImage` processes frames directly without CPU RGBA bitmap conversions.
|
|
16
|
+
- **🎛️ Live Granularity & Entity Filtering**: Dynamically switch bounding box granularity (`block`, `line`, `element`) and semantic entity filters (`all`, `nik`, `email`, `phone`, `url`, `currency`, `number`) at runtime without restarting the camera.
|
|
17
|
+
- **📐 Accurate `[0..1]` Overlay Projection**: Translates raw ML Kit `bounds.left/top` pixel coordinates and 4-point rotated corners into normalized `@masumdev/rn-camera-ai` boxes aligned identically across portrait, landscape, `cover`, `contain`, and front-camera mirroring.
|
|
18
|
+
- **🧠 Worklet-Safe Entity Classifier & Document Extractor**: Automatically tags scanned boxes (`NIK`, `EMAIL`, `PHONE`, `URL`, `CURRENCY`) and extracts deduplicated structured lists via `getLastStructuredEntities()` and `extractStructuredOcrData(fullText)`.
|
|
19
|
+
- **📄 Paper Corner Framing & Scan Optimality (`evaluateDocumentFraming`)**: Fits corner brackets onto outer document margins (`paperBox`, `paperCorners`), dampens jitter (`smoothPaperBox`), and scores read probability (`0-100%`) across `searching`, `clipped`, `tilted`, `too_far`, `too_close`, `off_center`, `low_clarity`, and `optimal`.
|
|
20
|
+
- **🖼️ Static Photo OCR (`recognizeImage` / `recognizeTextFromUri`)**: Supports capture-first still-photo scanning triggered cleanly with zero idle live box clutter.
|
|
21
|
+
- **🌍 5 Script Models Supported**: Latin (default, ~1-2 MB), Chinese, Devanagari, Japanese, and Korean.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## Installation
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
bun add @masumdev/rn-camera-ai @masumdev/rn-camera-ai-mlkit
|
|
29
|
+
# or
|
|
30
|
+
npm install @masumdev/rn-camera-ai @masumdev/rn-camera-ai-mlkit
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
### Native Peer Dependencies
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
bun add react-native-vision-camera react-native-vision-camera-mlkit react-native-vision-camera-worklets react-native-worklets react-native-nitro-modules react-native-nitro-image react-native-reanimated
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### Expo Config Plugin Setup (`app.json`)
|
|
40
|
+
|
|
41
|
+
Configure selective Google ML Kit models in `app.json` (enable only Latin by default to keep APK binary size small) and rebuild your native development client:
|
|
42
|
+
|
|
43
|
+
```json
|
|
44
|
+
{
|
|
45
|
+
"expo": {
|
|
46
|
+
"plugins": [
|
|
47
|
+
[
|
|
48
|
+
"react-native-vision-camera-mlkit",
|
|
49
|
+
{
|
|
50
|
+
"textRecognition": true,
|
|
51
|
+
"textRecognitionChinese": false,
|
|
52
|
+
"textRecognitionDevanagari": false,
|
|
53
|
+
"textRecognitionJapanese": false,
|
|
54
|
+
"textRecognitionKorean": false,
|
|
55
|
+
"barcodeScanning": false
|
|
56
|
+
}
|
|
57
|
+
]
|
|
58
|
+
]
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
> **Note**: Adding native Google ML Kit libraries requires running `npx expo prebuild` / `npx expo run:android` (or EAS Build). Standard Expo Go cannot run native Nitro C++ modules.
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
|
|
67
|
+
## Quick Start (Capture-First Smart Document OCR)
|
|
68
|
+
|
|
69
|
+
Use `@masumdev/rn-camera-ai`'s zero-OCR `createDocumentAlignmentProcessor` for buttery preview corner tracking and run `recognizeImage` **once** after tapping Capture (recommended for battery & smooth FPS; you can also bind `ocrProcessor` directly for continuous live OCR):
|
|
70
|
+
|
|
71
|
+
```tsx
|
|
72
|
+
import React, { useEffect, useMemo, useRef, useState } from 'react';
|
|
73
|
+
import { Pressable, StyleSheet, Text, View } from 'react-native';
|
|
74
|
+
import {
|
|
75
|
+
CameraAI,
|
|
76
|
+
createDocumentAlignmentProcessor,
|
|
77
|
+
type CameraAIRef,
|
|
78
|
+
type DocumentGuideTarget,
|
|
79
|
+
} from '@masumdev/rn-camera-ai';
|
|
80
|
+
import {
|
|
81
|
+
createMLKitTextRecognizer,
|
|
82
|
+
type MLKitTextRecognizer,
|
|
83
|
+
} from '@masumdev/rn-camera-ai-mlkit';
|
|
84
|
+
|
|
85
|
+
export function OcrScannerScreen() {
|
|
86
|
+
const cameraRef = useRef<CameraAIRef | null>(null);
|
|
87
|
+
const alignmentProcessor = useMemo(
|
|
88
|
+
() => createDocumentAlignmentProcessor({ targetFps: 5 }),
|
|
89
|
+
[]
|
|
90
|
+
);
|
|
91
|
+
const [ocrProcessor, setOcrProcessor] = useState<MLKitTextRecognizer | null>(null);
|
|
92
|
+
const [guide, setGuide] = useState<DocumentGuideTarget>({
|
|
93
|
+
box: { x: 0.08, y: 0.14, width: 0.84, height: 0.64 },
|
|
94
|
+
readiness: 'searching',
|
|
95
|
+
optimalityScore: 0,
|
|
96
|
+
statusText: 'Arahkan kertas ke dalam bingkai',
|
|
97
|
+
});
|
|
98
|
+
const [transcript, setTranscript] = useState('');
|
|
99
|
+
|
|
100
|
+
useEffect(() => {
|
|
101
|
+
let active = true;
|
|
102
|
+
let instance: MLKitTextRecognizer | null = null;
|
|
103
|
+
|
|
104
|
+
async function setup() {
|
|
105
|
+
const created = await createMLKitTextRecognizer({
|
|
106
|
+
language: 'LATIN',
|
|
107
|
+
granularity: 'line',
|
|
108
|
+
entityFilter: 'all',
|
|
109
|
+
minTextLength: 2,
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
if (active) {
|
|
113
|
+
instance = created;
|
|
114
|
+
setOcrProcessor(created);
|
|
115
|
+
} else {
|
|
116
|
+
created.dispose?.();
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
setup();
|
|
121
|
+
|
|
122
|
+
return () => {
|
|
123
|
+
active = false;
|
|
124
|
+
alignmentProcessor.dispose?.();
|
|
125
|
+
instance?.dispose?.();
|
|
126
|
+
};
|
|
127
|
+
}, [alignmentProcessor]);
|
|
128
|
+
|
|
129
|
+
const handleCapture = async () => {
|
|
130
|
+
const photo = await cameraRef.current?.capturePhoto({ flashMode: 'off' });
|
|
131
|
+
if (!photo || !ocrProcessor) return;
|
|
132
|
+
const result = await ocrProcessor.recognizeImage(photo.uri);
|
|
133
|
+
setTranscript(result?.text ?? '');
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
return (
|
|
137
|
+
<View style={styles.container}>
|
|
138
|
+
<CameraAI
|
|
139
|
+
ref={cameraRef}
|
|
140
|
+
processor={alignmentProcessor}
|
|
141
|
+
enablePhotoCapture={true}
|
|
142
|
+
showBoxes={false}
|
|
143
|
+
showLabels={false}
|
|
144
|
+
showLandmarks={false}
|
|
145
|
+
documentGuide={guide}
|
|
146
|
+
onDetections={(results) => {
|
|
147
|
+
const align = results[0]?.documentAlignment;
|
|
148
|
+
if (!align) return;
|
|
149
|
+
setGuide({
|
|
150
|
+
box: results[0].boundingBox,
|
|
151
|
+
corners: align.corners,
|
|
152
|
+
readiness: align.isOptimal ? 'optimal' : align.hasDocument ? 'adjusting' : 'searching',
|
|
153
|
+
optimalityScore: align.optimalityScore,
|
|
154
|
+
statusText: align.headline,
|
|
155
|
+
hintText: align.hint,
|
|
156
|
+
});
|
|
157
|
+
}}
|
|
158
|
+
/>
|
|
159
|
+
<View style={styles.transcriptBox}>
|
|
160
|
+
<Text style={styles.transcriptText}>{transcript || guide.statusText}</Text>
|
|
161
|
+
<Pressable onPress={handleCapture} style={styles.captureBtn}>
|
|
162
|
+
<Text style={styles.captureText}>Capture Document</Text>
|
|
163
|
+
</Pressable>
|
|
164
|
+
</View>
|
|
165
|
+
</View>
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const styles = StyleSheet.create({
|
|
170
|
+
container: { flex: 1, backgroundColor: '#000' },
|
|
171
|
+
transcriptBox: {
|
|
172
|
+
position: 'absolute',
|
|
173
|
+
bottom: 24,
|
|
174
|
+
left: 16,
|
|
175
|
+
right: 16,
|
|
176
|
+
backgroundColor: 'rgba(5, 22, 30, 0.88)',
|
|
177
|
+
padding: 14,
|
|
178
|
+
borderRadius: 12,
|
|
179
|
+
gap: 10,
|
|
180
|
+
},
|
|
181
|
+
transcriptText: { color: '#f8fafc', fontSize: 13 },
|
|
182
|
+
captureBtn: {
|
|
183
|
+
backgroundColor: '#f59e0b',
|
|
184
|
+
borderRadius: 8,
|
|
185
|
+
paddingVertical: 10,
|
|
186
|
+
alignItems: 'center',
|
|
187
|
+
},
|
|
188
|
+
captureText: { color: '#05161E', fontWeight: '700' },
|
|
189
|
+
});
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
---
|
|
193
|
+
|
|
194
|
+
## Static Image / Photo OCR (`recognizeTextFromUri`)
|
|
195
|
+
|
|
196
|
+
For scanned documents, gallery photos, or ID card captures:
|
|
197
|
+
|
|
198
|
+
```typescript
|
|
199
|
+
import { recognizeTextFromUri } from '@masumdev/rn-camera-ai-mlkit';
|
|
200
|
+
|
|
201
|
+
const result = await recognizeTextFromUri('file:///storage/emulated/0/DCIM/ktp.jpg', {
|
|
202
|
+
language: 'LATIN',
|
|
203
|
+
granularity: 'line',
|
|
204
|
+
imageWidth: 1280,
|
|
205
|
+
imageHeight: 720,
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
console.log('Full Text:', result.fullText);
|
|
209
|
+
console.log('Extracted NIKs:', result.entities.niks);
|
|
210
|
+
console.log('Extracted Emails:', result.entities.emails);
|
|
211
|
+
console.log('Extracted Phones:', result.entities.phones);
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
---
|
|
215
|
+
|
|
216
|
+
## API Reference
|
|
217
|
+
|
|
218
|
+
### `createMLKitTextRecognizer(config?)`
|
|
219
|
+
|
|
220
|
+
#### Configuration Options (`MLKitTextRecognizerConfig`)
|
|
221
|
+
|
|
222
|
+
| Option | Type | Default | Description |
|
|
223
|
+
| :--- | :--- | :--- | :--- |
|
|
224
|
+
| `language` | `'LATIN' \| 'CHINESE' \| 'DEVANAGARI' \| 'JAPANESE' \| 'KOREAN'` | `'LATIN'` | Google ML Kit script recognition model. |
|
|
225
|
+
| `granularity` | `'block' \| 'line' \| 'element'` | `'line'` | Hierarchy level emitted as overlay bounding boxes. |
|
|
226
|
+
| `entityFilter` | `'all' \| 'nik' \| 'email' \| 'phone' \| 'url' \| 'currency' \| 'number' \| 'text'` | `'all'` | Filter detections to a specific semantic entity class. |
|
|
227
|
+
| `scaleFactor` | `number` | `1.0` | Optional image downscale factor (`0.9` - `1.0`). |
|
|
228
|
+
| `invertColors` | `boolean` | `false` | Invert dark-background / white-text images prior to OCR. |
|
|
229
|
+
| `roi` | `MLKitRegionOfInterest` | `undefined` | Restrict ML Kit processing to a crop rectangle. |
|
|
230
|
+
| `targetFps` | `number` | `10` | Frame rate throttling limit in FPS. |
|
|
231
|
+
| `minTextLength` | `number` | `1` | Minimum character count per emitted item. |
|
|
232
|
+
| `minConfidence` | `number` | `0` | Minimum confidence cutoff `[0, 1]` (Android). |
|
|
233
|
+
| `maxResults` | `number` | `30` | Maximum bounding boxes emitted per frame. |
|
|
234
|
+
| `preferredPixelFormat` | `'yuv' \| 'rgb' \| 'native'` | `'yuv'` | Camera frame pixel format (`yuv` enables Android ML Kit zero-copy). |
|
|
235
|
+
|
|
236
|
+
#### Runtime Methods (`MLKitTextRecognizer`)
|
|
237
|
+
|
|
238
|
+
- **`setGranularity(granularity)`**: Live switches `'block' | 'line' | 'element'`.
|
|
239
|
+
- **`setEntityFilter(filter)`**: Live filters detections to specific entity classes.
|
|
240
|
+
- **`setInvertColors(invert)`**: Recreates underlying native recognizer with color inversion enabled/disabled.
|
|
241
|
+
- **`setMinConfidence(confidence)`**: Dynamically sets confidence threshold.
|
|
242
|
+
- **`setMaxResults(maxResults)`**: Dynamically sets box limit per frame.
|
|
243
|
+
- **`getLastFullText()`**: Returns full recognized multi-line text string from the latest frame.
|
|
244
|
+
- **`getLastStructuredEntities()`**: Returns deduplicated `{ niks, emails, phones, urls, currencies }`.
|
|
245
|
+
- **`recognizeImage(uri, dims?)`**: Runs async OCR against a photo URI.
|
|
246
|
+
|
|
247
|
+
---
|
|
248
|
+
|
|
249
|
+
## License
|
|
250
|
+
|
|
251
|
+
MIT © [Ma'sum](https://github.com/masumrpg) — [masumdev.id](https://lib.masumdev.id)
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
Object.defineProperty(exports, "__esModule", {
|
|
4
|
+
value: true
|
|
5
|
+
});
|
|
6
|
+
exports.MLKitTextRecognizerImpl = void 0;
|
|
7
|
+
exports.createMLKitTextRecognizer = createMLKitTextRecognizer;
|
|
8
|
+
exports.recognizeTextFromUri = recognizeTextFromUri;
|
|
9
|
+
var _rnCameraAi = require("@masumdev/rn-camera-ai");
|
|
10
|
+
var _mlkitTextParser = require("../parser/mlkitTextParser.js");
|
|
11
|
+
function createSafeSynchronizable(initial, fixedType = false) {
|
|
12
|
+
try {
|
|
13
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
14
|
+
const worklets = require('react-native-worklets');
|
|
15
|
+
if (typeof worklets?.createSynchronizable === 'function') {
|
|
16
|
+
return fixedType ? worklets.createSynchronizable(initial, {
|
|
17
|
+
fixedType: true
|
|
18
|
+
}) : worklets.createSynchronizable(initial);
|
|
19
|
+
}
|
|
20
|
+
} catch {
|
|
21
|
+
// Fallback for Bun / Node test environments
|
|
22
|
+
}
|
|
23
|
+
let value = initial;
|
|
24
|
+
return {
|
|
25
|
+
getBlocking: () => value,
|
|
26
|
+
setBlocking: nextValue => {
|
|
27
|
+
value = nextValue;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function loadNativeMLKitModule() {
|
|
32
|
+
try {
|
|
33
|
+
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
34
|
+
return require('react-native-vision-camera-mlkit');
|
|
35
|
+
} catch {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function createNativeTextRecognizerInstance(mlkitModule, options) {
|
|
40
|
+
if (!mlkitModule) {
|
|
41
|
+
throw new _rnCameraAi.ModelLoadError('Native module "react-native-vision-camera-mlkit" is not available. Ensure it is installed and native binaries are rebuilt.', 'MODEL_LOAD_FAILED');
|
|
42
|
+
}
|
|
43
|
+
const featureAvailable = mlkitModule.isFeatureAvailable?.('TextRecognition') ?? mlkitModule.PluginFactory?.isFeatureAvailable?.('TextRecognition') ?? mlkitModule.VisionCameraMLKit?.isFeatureAvailable?.('TextRecognition') ?? true;
|
|
44
|
+
if (!featureAvailable) {
|
|
45
|
+
throw new _rnCameraAi.ModelLoadError('Google ML Kit TextRecognition feature is disabled in native build configuration. Enable textRecognition: true in react-native-vision-camera-mlkit plugin config.', 'MODEL_LOAD_FAILED');
|
|
46
|
+
}
|
|
47
|
+
const initialized = mlkitModule.PluginFactory?.initPlugin?.('TextRecognition', options) ?? mlkitModule.VisionCameraMLKit?.createTextRecognizer?.(options);
|
|
48
|
+
if (!initialized || typeof initialized.recognize !== 'function') {
|
|
49
|
+
throw new _rnCameraAi.ModelLoadError('Failed to instantiate ML Kit TextRecognizer native HybridObject.', 'MODEL_LOAD_FAILED');
|
|
50
|
+
}
|
|
51
|
+
return initialized;
|
|
52
|
+
}
|
|
53
|
+
function createMLKitWorkletProcessFrame(params) {
|
|
54
|
+
const {
|
|
55
|
+
disposedSync,
|
|
56
|
+
readySync,
|
|
57
|
+
recognizerSync,
|
|
58
|
+
granularitySync,
|
|
59
|
+
entityFilterSync,
|
|
60
|
+
minTextLengthSync,
|
|
61
|
+
minConfidenceSync,
|
|
62
|
+
maxResultsSync,
|
|
63
|
+
lastFrameTimeSync,
|
|
64
|
+
wasThrottledSync,
|
|
65
|
+
lastFullTextSync,
|
|
66
|
+
minFrameIntervalMs
|
|
67
|
+
} = params;
|
|
68
|
+
return frame => {
|
|
69
|
+
'worklet';
|
|
70
|
+
|
|
71
|
+
if (disposedSync.getBlocking()) {
|
|
72
|
+
throw new Error('Cannot process frame: MLKitTextRecognizer is disposed');
|
|
73
|
+
}
|
|
74
|
+
const activeRecognizer = recognizerSync.getBlocking();
|
|
75
|
+
if (!readySync.getBlocking() || !activeRecognizer) {
|
|
76
|
+
wasThrottledSync.setBlocking(false);
|
|
77
|
+
return [];
|
|
78
|
+
}
|
|
79
|
+
if (minFrameIntervalMs > 0) {
|
|
80
|
+
const now = Date.now();
|
|
81
|
+
const prevTime = lastFrameTimeSync.getBlocking();
|
|
82
|
+
if (prevTime > 0 && now - prevTime < minFrameIntervalMs) {
|
|
83
|
+
wasThrottledSync.setBlocking(true);
|
|
84
|
+
return [];
|
|
85
|
+
}
|
|
86
|
+
lastFrameTimeSync.setBlocking(now);
|
|
87
|
+
}
|
|
88
|
+
wasThrottledSync.setBlocking(false);
|
|
89
|
+
if (!frame || typeof frame !== 'object') {
|
|
90
|
+
return [];
|
|
91
|
+
}
|
|
92
|
+
const frameRecord = frame;
|
|
93
|
+
if (frameRecord.isValid === false) {
|
|
94
|
+
return [];
|
|
95
|
+
}
|
|
96
|
+
const rawW = typeof frameRecord.width === 'number' && frameRecord.width > 0 ? frameRecord.width : 720;
|
|
97
|
+
const rawH = typeof frameRecord.height === 'number' && frameRecord.height > 0 ? frameRecord.height : 1280;
|
|
98
|
+
|
|
99
|
+
// ML Kit InputImage.fromMediaImage internally auto-rotates 90/270-deg sensor frames
|
|
100
|
+
// so bounding boxes are returned in upright space.
|
|
101
|
+
const isRotated90Or270 = frameRecord.orientation === 'left' || frameRecord.orientation === 'right';
|
|
102
|
+
const uprightWidth = isRotated90Or270 ? rawH : rawW;
|
|
103
|
+
const uprightHeight = isRotated90Or270 ? rawW : rawH;
|
|
104
|
+
const rawResult = activeRecognizer.recognize(frame, {});
|
|
105
|
+
const fullText = rawResult && typeof rawResult.text === 'string' ? rawResult.text : '';
|
|
106
|
+
lastFullTextSync.setBlocking(fullText);
|
|
107
|
+
return (0, _mlkitTextParser.parseMLKitTextResult)(rawResult, uprightWidth, uprightHeight, {
|
|
108
|
+
granularity: granularitySync.getBlocking(),
|
|
109
|
+
entityFilter: entityFilterSync.getBlocking(),
|
|
110
|
+
minTextLength: minTextLengthSync.getBlocking(),
|
|
111
|
+
minConfidence: minConfidenceSync.getBlocking(),
|
|
112
|
+
maxResults: maxResultsSync.getBlocking()
|
|
113
|
+
});
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Concrete CameraProcessor implementation adapting Google ML Kit Text Recognition v2.
|
|
119
|
+
*/
|
|
120
|
+
class MLKitTextRecognizerImpl {
|
|
121
|
+
name = 'MLKitTextRecognizer';
|
|
122
|
+
constructor(config, nativeRecognizer) {
|
|
123
|
+
this.id = `mlkit-ocr-${Date.now()}-${Math.floor(Math.random() * 10000)}`;
|
|
124
|
+
this._config = config;
|
|
125
|
+
this._status = 'ready';
|
|
126
|
+
this._language = config.language ?? 'LATIN';
|
|
127
|
+
this._granularity = config.granularity ?? 'line';
|
|
128
|
+
this._entityFilter = config.entityFilter ?? 'all';
|
|
129
|
+
this._invertColors = Boolean(config.invertColors);
|
|
130
|
+
this._minTextLength = typeof config.minTextLength === 'number' && config.minTextLength >= 0 ? Math.floor(config.minTextLength) : 1;
|
|
131
|
+
this._minConfidence = typeof config.minConfidence === 'number' && Number.isFinite(config.minConfidence) ? Math.max(0, Math.min(1, config.minConfidence)) : 0;
|
|
132
|
+
this._maxResults = typeof config.maxResults === 'number' && Number.isFinite(config.maxResults) && config.maxResults >= 0 ? Math.floor(config.maxResults) : 30;
|
|
133
|
+
this.preferredPixelFormat = config.preferredPixelFormat ?? 'yuv';
|
|
134
|
+
const fps = config.targetFps ?? 10;
|
|
135
|
+
const minFrameIntervalMs = fps > 0 ? 1000 / fps : 0;
|
|
136
|
+
this._disposedSync = createSafeSynchronizable(false, true);
|
|
137
|
+
this._readySync = createSafeSynchronizable(true, true);
|
|
138
|
+
this._recognizerSync = createSafeSynchronizable(nativeRecognizer, false);
|
|
139
|
+
this._granularitySync = createSafeSynchronizable(this._granularity, false);
|
|
140
|
+
this._entityFilterSync = createSafeSynchronizable(this._entityFilter, false);
|
|
141
|
+
this._minTextLengthSync = createSafeSynchronizable(this._minTextLength, true);
|
|
142
|
+
this._minConfidenceSync = createSafeSynchronizable(this._minConfidence, true);
|
|
143
|
+
this._maxResultsSync = createSafeSynchronizable(this._maxResults, true);
|
|
144
|
+
this._lastFrameTimeSync = createSafeSynchronizable(0, true);
|
|
145
|
+
this.wasThrottledSync = createSafeSynchronizable(false, true);
|
|
146
|
+
this._lastFullTextSync = createSafeSynchronizable('', false);
|
|
147
|
+
this.processFrameWorklet = createMLKitWorkletProcessFrame({
|
|
148
|
+
disposedSync: this._disposedSync,
|
|
149
|
+
readySync: this._readySync,
|
|
150
|
+
recognizerSync: this._recognizerSync,
|
|
151
|
+
granularitySync: this._granularitySync,
|
|
152
|
+
entityFilterSync: this._entityFilterSync,
|
|
153
|
+
minTextLengthSync: this._minTextLengthSync,
|
|
154
|
+
minConfidenceSync: this._minConfidenceSync,
|
|
155
|
+
maxResultsSync: this._maxResultsSync,
|
|
156
|
+
lastFrameTimeSync: this._lastFrameTimeSync,
|
|
157
|
+
wasThrottledSync: this.wasThrottledSync,
|
|
158
|
+
lastFullTextSync: this._lastFullTextSync,
|
|
159
|
+
minFrameIntervalMs
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
get status() {
|
|
163
|
+
return this._status;
|
|
164
|
+
}
|
|
165
|
+
get targetFps() {
|
|
166
|
+
return this._config.targetFps ?? 10;
|
|
167
|
+
}
|
|
168
|
+
get language() {
|
|
169
|
+
return this._language;
|
|
170
|
+
}
|
|
171
|
+
get granularity() {
|
|
172
|
+
return this._granularity;
|
|
173
|
+
}
|
|
174
|
+
get entityFilter() {
|
|
175
|
+
return this._entityFilter;
|
|
176
|
+
}
|
|
177
|
+
get invertColors() {
|
|
178
|
+
return this._invertColors;
|
|
179
|
+
}
|
|
180
|
+
get minConfidence() {
|
|
181
|
+
return this._minConfidence;
|
|
182
|
+
}
|
|
183
|
+
setGranularity(granularity) {
|
|
184
|
+
this._granularity = granularity;
|
|
185
|
+
this._granularitySync.setBlocking(granularity);
|
|
186
|
+
}
|
|
187
|
+
setEntityFilter(filter) {
|
|
188
|
+
this._entityFilter = filter;
|
|
189
|
+
this._entityFilterSync.setBlocking(filter);
|
|
190
|
+
}
|
|
191
|
+
setMinConfidence(confidence) {
|
|
192
|
+
if (Number.isFinite(confidence)) {
|
|
193
|
+
this._minConfidence = Math.max(0, Math.min(1, confidence));
|
|
194
|
+
this._minConfidenceSync.setBlocking(this._minConfidence);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
setMaxResults(maxResults) {
|
|
198
|
+
if (Number.isFinite(maxResults) && maxResults >= 0) {
|
|
199
|
+
this._maxResults = Math.floor(maxResults);
|
|
200
|
+
this._maxResultsSync.setBlocking(this._maxResults);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
async setInvertColors(invert) {
|
|
204
|
+
if (this._invertColors === invert) {
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
this._invertColors = invert;
|
|
208
|
+
const prev = this._recognizerSync.getBlocking();
|
|
209
|
+
const nativeOptions = {
|
|
210
|
+
language: this._language,
|
|
211
|
+
scaleFactor: this._config.scaleFactor,
|
|
212
|
+
invertColors: invert,
|
|
213
|
+
roi: this._config.roi
|
|
214
|
+
};
|
|
215
|
+
const next = this._config.createRecognizer ? await Promise.resolve(this._config.createRecognizer(nativeOptions)) : createNativeTextRecognizerInstance(loadNativeMLKitModule(), nativeOptions);
|
|
216
|
+
this._recognizerSync.setBlocking(next);
|
|
217
|
+
prev?.dispose?.();
|
|
218
|
+
}
|
|
219
|
+
getLastFullText() {
|
|
220
|
+
return this._lastFullTextSync.getBlocking();
|
|
221
|
+
}
|
|
222
|
+
getLastStructuredEntities() {
|
|
223
|
+
return (0, _mlkitTextParser.extractStructuredOcrData)(this.getLastFullText());
|
|
224
|
+
}
|
|
225
|
+
processFrame(frame) {
|
|
226
|
+
try {
|
|
227
|
+
return this.processFrameWorklet(frame);
|
|
228
|
+
} catch (err) {
|
|
229
|
+
throw new _rnCameraAi.InferenceError(err instanceof Error ? err.message : 'ML Kit OCR execution failed', 'INFERENCE_ERROR', err);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
async recognizeImage(uri, options) {
|
|
233
|
+
const active = this._recognizerSync.getBlocking();
|
|
234
|
+
if (!active || typeof active.recognizeImage !== 'function') {
|
|
235
|
+
return recognizeTextFromUri(uri, {
|
|
236
|
+
language: this._language,
|
|
237
|
+
scaleFactor: this._config.scaleFactor,
|
|
238
|
+
invertColors: this._invertColors,
|
|
239
|
+
roi: this._config.roi,
|
|
240
|
+
granularity: this._granularity,
|
|
241
|
+
entityFilter: this._entityFilter,
|
|
242
|
+
minTextLength: this._minTextLength,
|
|
243
|
+
minConfidence: this._minConfidence,
|
|
244
|
+
maxResults: this._maxResults,
|
|
245
|
+
imageWidth: options?.imageWidth,
|
|
246
|
+
imageHeight: options?.imageHeight
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
const rawResult = await active.recognizeImage(uri);
|
|
250
|
+
return buildOcrDocumentResult(rawResult, {
|
|
251
|
+
granularity: this._granularity,
|
|
252
|
+
entityFilter: this._entityFilter,
|
|
253
|
+
minTextLength: this._minTextLength,
|
|
254
|
+
minConfidence: this._minConfidence,
|
|
255
|
+
maxResults: this._maxResults,
|
|
256
|
+
imageWidth: options?.imageWidth,
|
|
257
|
+
imageHeight: options?.imageHeight
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
async initialize() {
|
|
261
|
+
if (this._disposedSync.getBlocking()) {
|
|
262
|
+
const nativeOptions = {
|
|
263
|
+
language: this._language,
|
|
264
|
+
scaleFactor: this._config.scaleFactor,
|
|
265
|
+
invertColors: this._invertColors,
|
|
266
|
+
roi: this._config.roi
|
|
267
|
+
};
|
|
268
|
+
const created = this._config.createRecognizer ? await Promise.resolve(this._config.createRecognizer(nativeOptions)) : createNativeTextRecognizerInstance(loadNativeMLKitModule(), nativeOptions);
|
|
269
|
+
this._recognizerSync.setBlocking(created);
|
|
270
|
+
this._disposedSync.setBlocking(false);
|
|
271
|
+
}
|
|
272
|
+
this._status = 'ready';
|
|
273
|
+
this._readySync.setBlocking(true);
|
|
274
|
+
this._lastFrameTimeSync.setBlocking(0);
|
|
275
|
+
this.wasThrottledSync.setBlocking(false);
|
|
276
|
+
}
|
|
277
|
+
dispose() {
|
|
278
|
+
this._disposedSync.setBlocking(true);
|
|
279
|
+
this._readySync.setBlocking(false);
|
|
280
|
+
this._status = 'idle';
|
|
281
|
+
this._lastFrameTimeSync.setBlocking(0);
|
|
282
|
+
this.wasThrottledSync.setBlocking(false);
|
|
283
|
+
const active = this._recognizerSync.getBlocking();
|
|
284
|
+
this._recognizerSync.setBlocking(null);
|
|
285
|
+
active?.dispose?.();
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
exports.MLKitTextRecognizerImpl = MLKitTextRecognizerImpl;
|
|
289
|
+
function inferImageDimensionsFromResult(rawResult, explicitWidth, explicitHeight) {
|
|
290
|
+
if (typeof explicitWidth === 'number' && explicitWidth > 0 && typeof explicitHeight === 'number' && explicitHeight > 0) {
|
|
291
|
+
return {
|
|
292
|
+
width: explicitWidth,
|
|
293
|
+
height: explicitHeight
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
let maxRight = 1;
|
|
297
|
+
let maxBottom = 1;
|
|
298
|
+
for (let i = 0; i < rawResult.blocks.length; i++) {
|
|
299
|
+
const bounds = rawResult.blocks[i]?.bounds;
|
|
300
|
+
if (!bounds) {
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
const right = typeof bounds.right === 'number' ? bounds.right : (bounds.left ?? 0) + bounds.width;
|
|
304
|
+
const bottom = typeof bounds.bottom === 'number' ? bounds.bottom : (bounds.top ?? 0) + bounds.height;
|
|
305
|
+
if (right > maxRight) maxRight = right;
|
|
306
|
+
if (bottom > maxBottom) maxBottom = bottom;
|
|
307
|
+
}
|
|
308
|
+
return {
|
|
309
|
+
width: Math.max(100, maxRight),
|
|
310
|
+
height: Math.max(100, maxBottom)
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
function buildOcrDocumentResult(rawResult, options) {
|
|
314
|
+
const fullText = typeof rawResult?.text === 'string' ? rawResult.text : '';
|
|
315
|
+
const dims = inferImageDimensionsFromResult(rawResult, options.imageWidth, options.imageHeight);
|
|
316
|
+
const detections = (0, _mlkitTextParser.parseMLKitTextResult)(rawResult, dims.width, dims.height, {
|
|
317
|
+
granularity: options.granularity,
|
|
318
|
+
entityFilter: options.entityFilter,
|
|
319
|
+
minTextLength: options.minTextLength,
|
|
320
|
+
minConfidence: options.minConfidence,
|
|
321
|
+
maxResults: options.maxResults,
|
|
322
|
+
defaultConfidence: options.defaultConfidence
|
|
323
|
+
});
|
|
324
|
+
return {
|
|
325
|
+
fullText,
|
|
326
|
+
detections,
|
|
327
|
+
entities: (0, _mlkitTextParser.extractStructuredOcrData)(fullText),
|
|
328
|
+
rawResult
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Creates and initializes a worklet-capable Google ML Kit OCR processor for CameraAI.
|
|
334
|
+
*/
|
|
335
|
+
async function createMLKitTextRecognizer(config = {}) {
|
|
336
|
+
const nativeOptions = {
|
|
337
|
+
language: config.language ?? 'LATIN',
|
|
338
|
+
scaleFactor: config.scaleFactor,
|
|
339
|
+
invertColors: config.invertColors,
|
|
340
|
+
roi: config.roi
|
|
341
|
+
};
|
|
342
|
+
try {
|
|
343
|
+
const recognizer = config.createRecognizer ? await Promise.resolve(config.createRecognizer(nativeOptions)) : createNativeTextRecognizerInstance(loadNativeMLKitModule(), nativeOptions);
|
|
344
|
+
return new MLKitTextRecognizerImpl(config, recognizer);
|
|
345
|
+
} catch (err) {
|
|
346
|
+
if (err instanceof _rnCameraAi.ModelLoadError) {
|
|
347
|
+
throw err;
|
|
348
|
+
}
|
|
349
|
+
throw new _rnCameraAi.ModelLoadError(err instanceof Error ? err.message : 'Failed to initialize ML Kit TextRecognizer', 'MODEL_LOAD_FAILED', err);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Performs asynchronous Google ML Kit OCR on a static photo URI or local image path.
|
|
355
|
+
*/
|
|
356
|
+
async function recognizeTextFromUri(uri, options = {}) {
|
|
357
|
+
if (!uri || typeof uri !== 'string') {
|
|
358
|
+
throw new _rnCameraAi.InferenceError('recognizeTextFromUri requires a valid image URI string', 'INVALID_INPUT');
|
|
359
|
+
}
|
|
360
|
+
const nativeOpts = {
|
|
361
|
+
language: options.language ?? 'LATIN',
|
|
362
|
+
scaleFactor: options.scaleFactor,
|
|
363
|
+
invertColors: options.invertColors,
|
|
364
|
+
roi: options.roi,
|
|
365
|
+
orientation: options.orientation
|
|
366
|
+
};
|
|
367
|
+
if (options.processImage) {
|
|
368
|
+
const raw = await options.processImage(uri, nativeOpts);
|
|
369
|
+
return buildOcrDocumentResult(raw, options);
|
|
370
|
+
}
|
|
371
|
+
const mlkitModule = loadNativeMLKitModule();
|
|
372
|
+
if (typeof mlkitModule?.processImageTextRecognition === 'function') {
|
|
373
|
+
const raw = await mlkitModule.processImageTextRecognition(uri, nativeOpts);
|
|
374
|
+
return buildOcrDocumentResult(raw, options);
|
|
375
|
+
}
|
|
376
|
+
const instance = createNativeTextRecognizerInstance(mlkitModule, nativeOpts);
|
|
377
|
+
try {
|
|
378
|
+
if (typeof instance.recognizeImage !== 'function') {
|
|
379
|
+
throw new _rnCameraAi.InferenceError('Native ML Kit TextRecognizer does not expose recognizeImage(uri).', 'INFERENCE_ERROR');
|
|
380
|
+
}
|
|
381
|
+
const raw = await instance.recognizeImage(uri);
|
|
382
|
+
return buildOcrDocumentResult(raw, options);
|
|
383
|
+
} finally {
|
|
384
|
+
instance.dispose?.();
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
//# sourceMappingURL=MLKitTextRecognizer.js.map
|