capacitor-card-scanner 0.0.1 → 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/README.md CHANGED
@@ -45,13 +45,16 @@ Add to the app's `Info.plist`:
45
45
  1. Add a CSS class to the Theme / screen:
46
46
 
47
47
  ```css
48
+ html:has(body.camera-active),
48
49
  body.camera-active,
50
+ body.camera-active #reactContainer,
51
+ body.camera-active .screen-container,
52
+ body.camera-active .active-screen,
53
+ body.camera-active .screen,
49
54
  body.camera-active .layout,
50
55
  body.camera-active .main,
51
56
  body.camera-active .main-content,
52
- body.camera-active .content,
53
- body.camera-active .screen,
54
- body.camera-active .active-screen {
57
+ body.camera-active .content {
55
58
  background: transparent !important;
56
59
  }
57
60
  ```
@@ -78,6 +81,25 @@ Add to the app's `Info.plist`:
78
81
  $parameters.ImageBase64 = photo.base64;
79
82
  ```
80
83
 
84
+ ### Card detection (Android)
85
+
86
+ After `start()`, call `startDetection()`. A red rectangle is drawn around the
87
+ card (between the camera and the WebView) and its text is read on-device with
88
+ ML Kit. `cardDetected` fires once per card, when the same collector number (or
89
+ name) was read on `stableFrames` consecutive runs. Remove the card from view
90
+ for ~1.5s to scan the same card again.
91
+
92
+ ```js
93
+ const { CardScanner } = Capacitor.Plugins;
94
+ await CardScanner.addListener('cardDetected', (card) => {
95
+ // card.name, card.collectorNumber ('025/165'), card.text, card.lines, card.cardBox, card.image
96
+ });
97
+ await CardScanner.startDetection({ intervalMs: 300, stableFrames: 2, includeImage: false });
98
+ // ...
99
+ await CardScanner.stopDetection();
100
+ await CardScanner.removeAllListeners();
101
+ ```
102
+
81
103
  ## API
82
104
 
83
105
  <docgen-index>
@@ -88,6 +110,10 @@ Add to the app's `Info.plist`:
88
110
  * [`setTorch(...)`](#settorch)
89
111
  * [`setZoom(...)`](#setzoom)
90
112
  * [`flip()`](#flip)
113
+ * [`startDetection(...)`](#startdetection)
114
+ * [`stopDetection()`](#stopdetection)
115
+ * [`addListener('cardDetected', ...)`](#addlistenercarddetected-)
116
+ * [`removeAllListeners()`](#removealllisteners)
91
117
  * [`checkPermissions()`](#checkpermissions)
92
118
  * [`requestPermissions()`](#requestpermissions)
93
119
  * [Interfaces](#interfaces)
@@ -184,6 +210,60 @@ Switches between the rear and front camera.
184
210
  --------------------
185
211
 
186
212
 
213
+ ### startDetection(...)
214
+
215
+ ```typescript
216
+ startDetection(options?: DetectionOptions | undefined) => Promise<void>
217
+ ```
218
+
219
+ Starts looking for cards: draws a red rectangle around the card and reads
220
+ its text, emitting `cardDetected`. Requires `start()` first. Android only.
221
+
222
+ | Param | Type |
223
+ | ------------- | ------------------------------------------------------------- |
224
+ | **`options`** | <code><a href="#detectionoptions">DetectionOptions</a></code> |
225
+
226
+ --------------------
227
+
228
+
229
+ ### stopDetection()
230
+
231
+ ```typescript
232
+ stopDetection() => Promise<void>
233
+ ```
234
+
235
+ Stops card detection and hides the rectangle.
236
+
237
+ --------------------
238
+
239
+
240
+ ### addListener('cardDetected', ...)
241
+
242
+ ```typescript
243
+ addListener(eventName: 'cardDetected', listener: (event: CardDetectedEvent) => void) => Promise<PluginListenerHandle>
244
+ ```
245
+
246
+ Fired once per card, when its text has been read consistently.
247
+
248
+ | Param | Type |
249
+ | --------------- | ----------------------------------------------------------------------------------- |
250
+ | **`eventName`** | <code>'cardDetected'</code> |
251
+ | **`listener`** | <code>(event: <a href="#carddetectedevent">CardDetectedEvent</a>) =&gt; void</code> |
252
+
253
+ **Returns:** <code>Promise&lt;<a href="#pluginlistenerhandle">PluginListenerHandle</a>&gt;</code>
254
+
255
+ --------------------
256
+
257
+
258
+ ### removeAllListeners()
259
+
260
+ ```typescript
261
+ removeAllListeners() => Promise<void>
262
+ ```
263
+
264
+ --------------------
265
+
266
+
187
267
  ### checkPermissions()
188
268
 
189
269
  ```typescript
@@ -246,6 +326,54 @@ requestPermissions() => Promise<PermissionStatus>
246
326
  | **`ratio`** | <code>number</code> | Zoom ratio, clamped between the camera's min and max. |
247
327
 
248
328
 
329
+ #### DetectionOptions
330
+
331
+ | Prop | Type | Description | Default |
332
+ | ------------------ | -------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------ |
333
+ | **`intervalMs`** | <code>number</code> | Minimum time between two OCR runs, in milliseconds. The red rectangle is updated on every frame regardless. | <code>300</code> |
334
+ | **`stableFrames`** | <code>number</code> | How many consecutive OCR runs must read the same card before `cardDetected` fires. | <code>2</code> |
335
+ | **`includeImage`** | <code>boolean</code> | Include a JPEG of the detected card in the event. | <code>false</code> |
336
+
337
+
338
+ #### PluginListenerHandle
339
+
340
+ | Prop | Type |
341
+ | ------------ | ----------------------------------------- |
342
+ | **`remove`** | <code>() =&gt; Promise&lt;void&gt;</code> |
343
+
344
+
345
+ #### CardDetectedEvent
346
+
347
+ | Prop | Type | Description |
348
+ | --------------------- | ----------------------------------- | ---------------------------------------------------------------------------- |
349
+ | **`name`** | <code>string</code> | Best guess for the card name (topmost line of text on the card). |
350
+ | **`collectorNumber`** | <code>string</code> | Collector number, e.g. `025/165`. |
351
+ | **`text`** | <code>string</code> | All text read on the card. |
352
+ | **`lines`** | <code>TextLine[]</code> | |
353
+ | **`cardBox`** | <code><a href="#box">Box</a></code> | Where the card is in the camera frame. Missing if no card outline was found. |
354
+ | **`image`** | <code>string</code> | Base64 JPEG of the card, when `includeImage` is true. |
355
+
356
+
357
+ #### TextLine
358
+
359
+ | Prop | Type | Description |
360
+ | ---------- | ----------------------------------- | ------------------------------- |
361
+ | **`text`** | <code>string</code> | |
362
+ | **`box`** | <code><a href="#box">Box</a></code> | Position inside the card image. |
363
+
364
+
365
+ #### Box
366
+
367
+ Normalized rectangle (0-1).
368
+
369
+ | Prop | Type |
370
+ | ------------ | ------------------- |
371
+ | **`x`** | <code>number</code> |
372
+ | **`y`** | <code>number</code> |
373
+ | **`width`** | <code>number</code> |
374
+ | **`height`** | <code>number</code> |
375
+
376
+
249
377
  #### PermissionStatus
250
378
 
251
379
  | Prop | Type |
@@ -61,4 +61,6 @@ dependencies {
61
61
  implementation "androidx.camera:camera-camera2:$camerax_version"
62
62
  implementation "androidx.camera:camera-lifecycle:$camerax_version"
63
63
  implementation "androidx.camera:camera-view:$camerax_version"
64
+ implementation "com.google.mlkit:text-recognition:16.0.1"
65
+ implementation "com.google.mlkit:object-detection:17.0.2"
64
66
  }
@@ -0,0 +1,249 @@
1
+ package pt.tcgclassifier.cardscanner;
2
+
3
+ import android.graphics.Bitmap;
4
+ import android.graphics.Matrix;
5
+ import android.graphics.Rect;
6
+ import android.graphics.RectF;
7
+ import android.os.SystemClock;
8
+ import android.util.Base64;
9
+ import androidx.annotation.NonNull;
10
+ import androidx.annotation.Nullable;
11
+ import androidx.camera.core.ImageAnalysis;
12
+ import androidx.camera.core.ImageProxy;
13
+ import com.getcapacitor.JSArray;
14
+ import com.getcapacitor.JSObject;
15
+ import com.getcapacitor.Logger;
16
+ import com.google.android.gms.tasks.Tasks;
17
+ import com.google.mlkit.vision.common.InputImage;
18
+ import com.google.mlkit.vision.objects.DetectedObject;
19
+ import com.google.mlkit.vision.objects.ObjectDetection;
20
+ import com.google.mlkit.vision.objects.ObjectDetector;
21
+ import com.google.mlkit.vision.objects.defaults.ObjectDetectorOptions;
22
+ import com.google.mlkit.vision.text.Text;
23
+ import com.google.mlkit.vision.text.TextRecognition;
24
+ import com.google.mlkit.vision.text.TextRecognizer;
25
+ import com.google.mlkit.vision.text.latin.TextRecognizerOptions;
26
+ import java.io.ByteArrayOutputStream;
27
+ import java.util.List;
28
+ import java.util.regex.Matcher;
29
+ import java.util.regex.Pattern;
30
+
31
+ /**
32
+ * Locates the card in every camera frame (for the on-screen rectangle) and,
33
+ * every {@code intervalMs}, runs OCR inside it. A card is reported once the
34
+ * same collector number (or name) has been read on several consecutive runs.
35
+ */
36
+ public class CardDetector implements ImageAnalysis.Analyzer {
37
+
38
+ public interface Listener {
39
+ void onCardDetected(JSObject result);
40
+ }
41
+
42
+ public interface BoxListener {
43
+ /**
44
+ * @param box card bounds normalized (0-1) to the upright frame, or null when no card is visible
45
+ */
46
+ void onBox(@Nullable RectF box, int frameWidth, int frameHeight);
47
+ }
48
+
49
+ // e.g. "025/165", "SV001/SV122", "TG05/TG30", "GG01/GG70"
50
+ private static final Pattern NUMBER = Pattern.compile("\\b([A-Za-z]{0,4}\\d{1,3}[a-z]?)\\s*/\\s*([A-Za-z]{0,4}\\d{1,3})\\b");
51
+ private static final Pattern HEADER = Pattern.compile(
52
+ "^(basic|stage\\s*\\d|trainer|item|supporter|stadium|energy|pok[eé]mon|evolves|hp\\b)",
53
+ Pattern.CASE_INSENSITIVE
54
+ );
55
+ private static final Pattern HP_SUFFIX = Pattern.compile("\\s*HP\\s*\\d+\\s*$", Pattern.CASE_INSENSITIVE);
56
+ private static final Pattern LETTER = Pattern.compile("\\p{L}");
57
+ /** After this long without reading a card, the same card can be reported again. */
58
+ private static final long RESET_AFTER_MS = 1500;
59
+ /** Objects smaller than this fraction of the frame are ignored. */
60
+ private static final float MIN_CARD_AREA = 0.08f;
61
+ /** Extra margin around the detected card before running OCR. */
62
+ private static final float CROP_MARGIN = 0.04f;
63
+
64
+ private final ObjectDetector objectDetector = ObjectDetection.getClient(
65
+ new ObjectDetectorOptions.Builder().setDetectorMode(ObjectDetectorOptions.STREAM_MODE).build()
66
+ );
67
+ private final TextRecognizer recognizer = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS);
68
+ private final long intervalMs;
69
+ private final int stableFrames;
70
+ private final boolean includeImage;
71
+ private final Listener listener;
72
+ private volatile BoxListener boxListener;
73
+
74
+ // Only touched from the analyzer thread.
75
+ private long lastOcrAt;
76
+ private long lastSeenAt;
77
+ private String candidateKey;
78
+ private int candidateCount;
79
+ private String lastEmittedKey;
80
+
81
+ public CardDetector(long intervalMs, int stableFrames, boolean includeImage, Listener listener) {
82
+ this.intervalMs = intervalMs;
83
+ this.stableFrames = Math.max(1, stableFrames);
84
+ this.includeImage = includeImage;
85
+ this.listener = listener;
86
+ }
87
+
88
+ public void setBoxListener(BoxListener boxListener) {
89
+ this.boxListener = boxListener;
90
+ }
91
+
92
+ public void close() {
93
+ objectDetector.close();
94
+ recognizer.close();
95
+ }
96
+
97
+ @Override
98
+ public void analyze(@NonNull ImageProxy image) {
99
+ long now = SystemClock.elapsedRealtime();
100
+ int rotation = image.getImageInfo().getRotationDegrees();
101
+ Bitmap raw;
102
+ try {
103
+ raw = image.toBitmap();
104
+ } finally {
105
+ image.close();
106
+ }
107
+ int frameW = rotation % 180 == 0 ? raw.getWidth() : raw.getHeight();
108
+ int frameH = rotation % 180 == 0 ? raw.getHeight() : raw.getWidth();
109
+
110
+ try {
111
+ List<DetectedObject> objects = Tasks.await(objectDetector.process(InputImage.fromBitmap(raw, rotation)));
112
+ Rect card = pickCard(objects, frameW, frameH);
113
+ RectF cardBox = card == null ? null : new RectF(
114
+ card.left / (float) frameW,
115
+ card.top / (float) frameH,
116
+ card.right / (float) frameW,
117
+ card.bottom / (float) frameH
118
+ );
119
+ BoxListener bl = boxListener;
120
+ if (bl != null) bl.onBox(cardBox, frameW, frameH);
121
+
122
+ if (now - lastOcrAt < intervalMs) return;
123
+ lastOcrAt = now;
124
+
125
+ Bitmap upright = rotate(raw, rotation);
126
+ Bitmap region = card == null ? upright : crop(upright, card);
127
+ Text text = Tasks.await(recognizer.process(InputImage.fromBitmap(region, 0)));
128
+ handle(text, region, cardBox, now);
129
+ } catch (Exception e) {
130
+ Logger.error("CardDetector", "Detection failed", e);
131
+ }
132
+ }
133
+
134
+ /** The biggest detected object, if it is large enough to be a card held close to the camera. */
135
+ @Nullable
136
+ private static Rect pickCard(List<DetectedObject> objects, int frameW, int frameH) {
137
+ Rect best = null;
138
+ long bestArea = 0;
139
+ for (DetectedObject o : objects) {
140
+ Rect r = new Rect(o.getBoundingBox());
141
+ if (!r.intersect(0, 0, frameW, frameH)) continue;
142
+ long area = (long) r.width() * r.height();
143
+ if (area > bestArea) {
144
+ best = r;
145
+ bestArea = area;
146
+ }
147
+ }
148
+ if (best == null || bestArea < MIN_CARD_AREA * frameW * frameH) return null;
149
+ return best;
150
+ }
151
+
152
+ private static Bitmap rotate(Bitmap bitmap, int rotation) {
153
+ if (rotation == 0) return bitmap;
154
+ Matrix matrix = new Matrix();
155
+ matrix.postRotate(rotation);
156
+ return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
157
+ }
158
+
159
+ private static Bitmap crop(Bitmap bitmap, Rect card) {
160
+ int mx = Math.round(card.width() * CROP_MARGIN);
161
+ int my = Math.round(card.height() * CROP_MARGIN);
162
+ int left = Math.max(0, card.left - mx);
163
+ int top = Math.max(0, card.top - my);
164
+ int right = Math.min(bitmap.getWidth(), card.right + mx);
165
+ int bottom = Math.min(bitmap.getHeight(), card.bottom + my);
166
+ return Bitmap.createBitmap(bitmap, left, top, right - left, bottom - top);
167
+ }
168
+
169
+ private void handle(Text text, Bitmap region, @Nullable RectF cardBox, long now) {
170
+ float w = region.getWidth();
171
+ float h = region.getHeight();
172
+ JSArray lines = new JSArray();
173
+ String number = null;
174
+ String name = null;
175
+ int nameTop = Integer.MAX_VALUE;
176
+
177
+ for (Text.TextBlock block : text.getTextBlocks()) {
178
+ for (Text.Line line : block.getLines()) {
179
+ String s = line.getText().trim();
180
+ Rect r = line.getBoundingBox();
181
+ if (s.isEmpty() || r == null) continue;
182
+
183
+ JSObject item = new JSObject();
184
+ item.put("text", s);
185
+ item.put("box", box(r.left / w, r.top / h, r.width() / w, r.height() / h));
186
+ lines.put(item);
187
+
188
+ if (number == null) {
189
+ Matcher m = NUMBER.matcher(s);
190
+ if (m.find()) number = m.group(1) + "/" + m.group(2);
191
+ }
192
+ if (r.top < nameTop && isNameCandidate(s)) {
193
+ name = HP_SUFFIX.matcher(s).replaceAll("").trim();
194
+ nameTop = r.top;
195
+ }
196
+ }
197
+ }
198
+
199
+ String key = number != null ? number : name;
200
+ if (key == null) {
201
+ candidateKey = null;
202
+ candidateCount = 0;
203
+ if (now - lastSeenAt > RESET_AFTER_MS) lastEmittedKey = null;
204
+ return;
205
+ }
206
+ lastSeenAt = now;
207
+
208
+ if (key.equals(candidateKey)) {
209
+ candidateCount++;
210
+ } else {
211
+ candidateKey = key;
212
+ candidateCount = 1;
213
+ }
214
+ if (candidateCount < stableFrames || key.equals(lastEmittedKey)) return;
215
+ lastEmittedKey = key;
216
+
217
+ JSObject result = new JSObject();
218
+ result.put("name", name);
219
+ result.put("collectorNumber", number);
220
+ result.put("text", text.getText());
221
+ result.put("lines", lines);
222
+ if (cardBox != null) {
223
+ result.put("cardBox", box(cardBox.left, cardBox.top, cardBox.width(), cardBox.height()));
224
+ }
225
+ if (includeImage) {
226
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
227
+ region.compress(Bitmap.CompressFormat.JPEG, 80, out);
228
+ result.put("image", Base64.encodeToString(out.toByteArray(), Base64.NO_WRAP));
229
+ }
230
+ listener.onCardDetected(result);
231
+ }
232
+
233
+ private static JSObject box(float x, float y, float width, float height) {
234
+ JSObject box = new JSObject();
235
+ box.put("x", x);
236
+ box.put("y", y);
237
+ box.put("width", width);
238
+ box.put("height", height);
239
+ return box;
240
+ }
241
+
242
+ private static boolean isNameCandidate(String s) {
243
+ if (HEADER.matcher(s).find()) return false;
244
+ Matcher m = LETTER.matcher(s);
245
+ int letters = 0;
246
+ while (m.find()) letters++;
247
+ return letters >= 3;
248
+ }
249
+ }