react-native-text-reader 0.5.0 → 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.
package/README.md CHANGED
@@ -1,33 +1,117 @@
1
- # react-native-text-reader
1
+ # `react-native-text-reader`
2
2
 
3
- A React Native library for OCR (Optical Character Recognition) using Vision Framework on iOS and Firebase ML Kit on Android.
3
+ A simple React Native library for extracting text from images using native iOS (Vision Framework) and Android (ML Kit) capabilities.
4
+
5
+
6
+ ## Table of Contents
7
+
8
+ - [Installation](#installation)
9
+ - [Platform Setup](#platform-setup)
10
+ - [iOS](#ios)
11
+ - [Android](#android)
12
+ - [Usage](#usage)
13
+ - [Basic Example](#basic-example)
14
+ - [Options](#options)
15
+ - [ScriptOptions Enum](#scriptoptions-enum)
16
+ - [Contributing](#contributing)
17
+ - [License](#license)
18
+
19
+ ### NOTE:
20
+ I currently do not work extensively with React Native, so this project may not receive frequent updates. However, if anyone is interested in contributing, please feel free to reach out!
4
21
 
5
22
  ## Installation
6
23
 
7
- ```sh
24
+ Install the package using npm or yarn:
25
+
26
+ ```bash
8
27
  npm install react-native-text-reader
9
28
  ```
10
29
 
30
+ or
31
+
32
+ ```bash
33
+ yarn add react-native-text-reader
34
+ ```
35
+
36
+ After installing the package, make sure to link the native dependencies:
37
+
38
+ ### iOS
39
+
40
+ If you're using iOS, run the following command to install the necessary native modules:
41
+
42
+ ```bash
43
+ cd ios/ && pod install
44
+ ```
45
+
46
+ ### Android
47
+
48
+ No additional steps are required for Android.
49
+
50
+ ---
51
+
11
52
  ## Usage
12
53
 
54
+ To use the text reader, import it and call the `read` method with the image path and options.
55
+
56
+ ### Basic Example
13
57
 
14
- ```js
15
- import { read } from 'react-native-text-reader';
58
+ ```javascript
59
+ import TextReader, { ScriptOptions } from 'react-native-text-reader';
16
60
 
17
- // ...
61
+ const imagePath = 'path/to/your/image.jpg';
62
+ const options = {
63
+ visionIgnoreThreshold: 0.5, // iOS only
64
+ script: ScriptOptions.LATIN, // Android only
65
+ };
66
+
67
+ const readTextFromImage = async () => {
68
+ try {
69
+ const text = await TextReader.read(imagePath, options);
70
+ console.log('Extracted text:', text);
71
+ } catch (error) {
72
+ console.error('Error reading text:', error);
73
+ }
74
+ };
75
+
76
+ readTextFromImage();
18
77
 
19
- const result = await read('imageUri');
20
78
  ```
21
79
 
80
+ ---
22
81
 
23
- ## Contributing
82
+ ## Options
24
83
 
25
- See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.
84
+ ### `Options`
26
85
 
27
- ## License
86
+ | Property | Type | Description |
87
+ |--------------------------|-------------------|------------------------------------------------------|
88
+ | `visionIgnoreThreshold` | `number` | The confidence threshold for iOS (default: 0.0) |
89
+ | `script` | `ScriptOptions` | The language script for Android (default: `LATIN`) |
28
90
 
29
- MIT
91
+ ---
92
+
93
+ ## ScriptOptions
94
+
95
+ The `ScriptOptions` enum allows you to specify different language scripts for Android:
96
+
97
+ ```javascript
98
+ export enum ScriptOptions {
99
+ LATIN = 'Latin',
100
+ CHINESE = 'Chinese',
101
+ DEVANAGARI = 'Devanagari',
102
+ JAPANESE = 'Japanese',
103
+ KOREAN = 'Korean',
104
+ }
105
+ ```
106
+
107
+ ---
108
+
109
+ ## Contributing
110
+
111
+ Contributions are welcome! Please submit a pull request or open an issue for any enhancements or bugs.
30
112
 
31
113
  ---
32
114
 
33
- Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)
115
+ ## License
116
+
117
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
@@ -10,47 +10,63 @@ extension String {
10
10
  @objc(TextReader)
11
11
  class TextReader: NSObject {
12
12
  @objc static func requiresMainQueueSetup() -> Bool { return true }
13
+
13
14
  @objc(read:withOptions:withResolver:withRejecter:)
14
- func read(imgPath: String, options: [String: Float], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
15
- guard !imgPath.isEmpty else { reject("ERR", "Image path cannot be empty.", nil); return }
15
+ func read(imgPath: String, options: [String: Any], resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
16
+ guard !imgPath.isEmpty else {
17
+ reject("ERR_EMPTY_PATH", "Image path cannot be empty.", nil)
18
+ return
19
+ }
16
20
 
17
21
  let formattedImgPath = imgPath.stripPrefix("file://")
18
- var threshold: Float = 0.0
19
-
20
- if !(options["visionIgnoreThreshold"]?.isZero ?? true) {
21
- threshold = options["visionIgnoreThreshold"] ?? 0.0
22
- }
22
+ let threshold = (options["visionIgnoreThreshold"] as? NSNumber)?.floatValue ?? 0.0
23
23
 
24
24
  do {
25
25
  let imgData = try Data(contentsOf: URL(fileURLWithPath: formattedImgPath))
26
- let image = UIImage(data: imgData)
27
-
28
- guard let cgImage = image?.cgImage else { return }
26
+ guard let image = UIImage(data: imgData), let cgImage = image.cgImage else {
27
+ reject("ERR_IMAGE_PROCESSING", "Failed to load image from the provided path.", nil)
28
+ return
29
+ }
29
30
 
30
31
  let requestHandler = VNImageRequestHandler(cgImage: cgImage)
32
+ let ocrRequest = VNRecognizeTextRequest { request, error in
33
+ self.handleTextRecognitionResult(request: request, threshold: threshold, error: error, resolve: resolve, reject: reject)
34
+ }
31
35
 
32
- let ocrRequest = VNRecognizeTextRequest { (request: VNRequest, error: Error?) in
33
- self.textReaderHandler(request: request, threshold: threshold, error: error, resolve: resolve, reject: reject)
36
+ if #available(iOS 16.0, *) {
37
+ ocrRequest.automaticallyDetectsLanguage = true
34
38
  }
35
39
 
36
40
  try requestHandler.perform([ocrRequest])
37
41
  } catch {
38
- print(error)
39
- reject("ERR", error.localizedDescription, nil)
42
+ reject("ERR_IMAGE_LOADING", "Failed to load or process the image: \(error.localizedDescription)", nil)
40
43
  }
41
44
  }
42
45
 
43
- func textReaderHandler(request: VNRequest, threshold: Float, error _: Error?, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
44
- guard let observations = request.results as? [VNRecognizedTextObservation] else { reject("ERR", "Failed to read the text.", nil); return }
46
+ private func handleTextRecognitionResult(request: VNRequest, threshold: Float, error: Error?, resolve: @escaping RCTPromiseResolveBlock, reject: @escaping RCTPromiseRejectBlock) {
47
+ if let error = error {
48
+ reject("ERR_OCR", "Error in text recognition: \(error.localizedDescription)", nil)
49
+ return
50
+ }
51
+
52
+ guard let observations = request.results as? [VNRecognizedTextObservation] else {
53
+ reject("ERR_OCR_RESULTS", "Failed to read text from the image.", nil)
54
+ return
55
+ }
45
56
 
46
- let strings = observations.compactMap { observation -> String? in
47
- if observation.topCandidates(1).first?.confidence ?? 0 >= threshold {
48
- return observation.topCandidates(1).first?.string
49
- } else {
50
- return nil
57
+ if observations.isEmpty {
58
+ resolve([])
59
+ return
60
+ }
61
+
62
+ let extractedStrings = observations.compactMap { observation -> String? in
63
+ guard let topCandidate = observation.topCandidates(1).first else { return nil }
64
+ if topCandidate.confidence >= threshold {
65
+ return topCandidate.string
51
66
  }
67
+ return nil
52
68
  }
53
-
54
- resolve(strings)
69
+
70
+ resolve(extractedStrings.isEmpty ? [] : extractedStrings)
55
71
  }
56
- }
72
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-text-reader",
3
- "version": "0.5.0",
3
+ "version": "1.2.0",
4
4
  "description": "A React Native library for OCR (Optical Character Recognition) using Vision Framework on iOS and Firebase ML Kit on Android.",
5
5
  "source": "./src/index.tsx",
6
6
  "main": "./lib/commonjs/index.js",