├── .circleci
└── config.yml
├── .editorconfig
├── .gitattributes
├── .github
└── FUNDING.yml
├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── android
├── build.gradle
├── gradle.properties
└── src
│ ├── main
│ ├── AndroidManifest.xml
│ └── java
│ │ └── com
│ │ └── reactnativemlkitocr
│ │ ├── MlkitOcrModuleImpl.kt
│ │ └── MlkitOcrPackage.kt
│ ├── newarch
│ └── java
│ │ └── com
│ │ └── reactnativemlkitocr
│ │ └── MlkitOcrModule.kt
│ └── oldarch
│ └── java
│ └── com
│ └── reactnativemlkitocr
│ └── MlkitOcrModule.kt
├── babel.config.js
├── example
├── android
│ ├── app
│ │ ├── _BUCK
│ │ ├── build.gradle
│ │ ├── build_defs.bzl
│ │ ├── debug.keystore
│ │ ├── proguard-rules.pro
│ │ └── src
│ │ │ ├── debug
│ │ │ ├── AndroidManifest.xml
│ │ │ └── java
│ │ │ │ └── com
│ │ │ │ └── example
│ │ │ │ └── reactnativemlkitocr
│ │ │ │ └── ReactNativeFlipper.java
│ │ │ └── main
│ │ │ ├── AndroidManifest.xml
│ │ │ ├── java
│ │ │ └── com
│ │ │ │ └── example
│ │ │ │ └── reactnativemlkitocr
│ │ │ │ ├── MainActivity.java
│ │ │ │ ├── MainApplication.java
│ │ │ │ └── newarchitecture
│ │ │ │ ├── MainApplicationReactNativeHost.java
│ │ │ │ ├── components
│ │ │ │ └── MainComponentsRegistry.java
│ │ │ │ └── modules
│ │ │ │ └── MainApplicationTurboModuleManagerDelegate.java
│ │ │ ├── jni
│ │ │ ├── Android.mk
│ │ │ ├── MainApplicationModuleProvider.cpp
│ │ │ ├── MainApplicationModuleProvider.h
│ │ │ ├── MainApplicationTurboModuleManagerDelegate.cpp
│ │ │ ├── MainApplicationTurboModuleManagerDelegate.h
│ │ │ ├── MainComponentsRegistry.cpp
│ │ │ ├── MainComponentsRegistry.h
│ │ │ └── OnLoad.cpp
│ │ │ └── res
│ │ │ ├── mipmap-hdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ └── values
│ │ │ ├── strings.xml
│ │ │ └── styles.xml
│ ├── build.gradle
│ ├── gradle.properties
│ ├── gradle
│ │ └── wrapper
│ │ │ ├── gradle-wrapper.jar
│ │ │ └── gradle-wrapper.properties
│ ├── gradlew
│ ├── gradlew.bat
│ └── settings.gradle
├── app.json
├── babel.config.js
├── index.js
├── ios
│ ├── MlkitOcrExample.xcodeproj
│ │ ├── project.pbxproj
│ │ └── xcshareddata
│ │ │ └── xcschemes
│ │ │ └── MlkitOcrExample.xcscheme
│ ├── MlkitOcrExample.xcworkspace
│ │ ├── contents.xcworkspacedata
│ │ └── xcshareddata
│ │ │ └── IDEWorkspaceChecks.plist
│ ├── MlkitOcrExample
│ │ ├── AppDelegate.h
│ │ ├── AppDelegate.mm
│ │ ├── Base.lproj
│ │ │ └── LaunchScreen.xib
│ │ ├── Images.xcassets
│ │ │ ├── AppIcon.appiconset
│ │ │ │ └── Contents.json
│ │ │ └── Contents.json
│ │ ├── Info.plist
│ │ └── main.m
│ ├── Podfile
│ └── Podfile.lock
├── metro.config.js
├── package.json
├── src
│ └── App.tsx
└── yarn.lock
├── ios
├── MlkitOcr.h
├── MlkitOcr.mm
└── MlkitOcr.xcodeproj
│ └── project.pbxproj
├── package.json
├── react-native-mlkit-ocr.podspec
├── src
├── NativeMlkitOcr.ts
├── __tests__
│ └── index.test.tsx
├── index.d.ts
└── index.ts
├── tsconfig.build.json
├── tsconfig.json
└── yarn.lock
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | version: 2.1
2 |
3 | executors:
4 | default:
5 | docker:
6 | - image: circleci/node:10
7 | working_directory: ~/project
8 |
9 | commands:
10 | attach_project:
11 | steps:
12 | - attach_workspace:
13 | at: ~/project
14 |
15 | jobs:
16 | install-dependencies:
17 | executor: default
18 | steps:
19 | - checkout
20 | - attach_project
21 | - restore_cache:
22 | keys:
23 | - dependencies-{{ checksum "package.json" }}
24 | - dependencies-
25 | - restore_cache:
26 | keys:
27 | - dependencies-example-{{ checksum "example/package.json" }}
28 | - dependencies-example-
29 | - run:
30 | name: Install dependencies
31 | command: |
32 | yarn install --cwd example --frozen-lockfile
33 | yarn install --frozen-lockfile
34 | - save_cache:
35 | key: dependencies-{{ checksum "package.json" }}
36 | paths: node_modules
37 | - save_cache:
38 | key: dependencies-example-{{ checksum "example/package.json" }}
39 | paths: example/node_modules
40 | - persist_to_workspace:
41 | root: .
42 | paths: .
43 |
44 | lint:
45 | executor: default
46 | steps:
47 | - attach_project
48 | - run:
49 | name: Lint files
50 | command: |
51 | yarn lint
52 |
53 | typescript:
54 | executor: default
55 | steps:
56 | - attach_project
57 | - run:
58 | name: Typecheck files
59 | command: |
60 | yarn typescript
61 |
62 | unit-tests:
63 | executor: default
64 | steps:
65 | - attach_project
66 | - run:
67 | name: Run unit tests
68 | command: |
69 | yarn test --coverage
70 | - store_artifacts:
71 | path: coverage
72 | destination: coverage
73 |
74 | build-package:
75 | executor: default
76 | steps:
77 | - attach_project
78 | - run:
79 | name: Build package
80 | command: |
81 | yarn prepare
82 |
83 | workflows:
84 | build-and-test:
85 | jobs:
86 | - install-dependencies
87 | - lint:
88 | requires:
89 | - install-dependencies
90 | - typescript:
91 | requires:
92 | - install-dependencies
93 | - unit-tests:
94 | requires:
95 | - install-dependencies
96 | - build-package:
97 | requires:
98 | - install-dependencies
99 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # EditorConfig helps developers define and maintain consistent
2 | # coding styles between different editors and IDEs
3 | # editorconfig.org
4 |
5 | root = true
6 |
7 | [*]
8 |
9 | indent_style = space
10 | indent_size = 2
11 |
12 | end_of_line = lf
13 | charset = utf-8
14 | trim_trailing_whitespace = true
15 | insert_final_newline = true
16 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.pbxproj -text
2 | # specific for windows script files
3 | *.bat text eol=crlf
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: [agoldis]
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: # Replace with a single Ko-fi username
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | otechie: # Replace with a single Otechie username
12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
13 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # OSX
2 | #
3 | .DS_Store
4 |
5 | # XDE
6 | .expo/
7 |
8 | # VSCode
9 | .vscode/
10 | jsconfig.json
11 |
12 | # Xcode
13 | #
14 | build/
15 | *.pbxuser
16 | !default.pbxuser
17 | *.mode1v3
18 | !default.mode1v3
19 | *.mode2v3
20 | !default.mode2v3
21 | *.perspectivev3
22 | !default.perspectivev3
23 | xcuserdata
24 | *.xccheckout
25 | *.moved-aside
26 | DerivedData
27 | *.hmap
28 | *.ipa
29 | *.xcuserstate
30 | project.xcworkspace
31 |
32 | # Android/IJ
33 | #
34 | .idea
35 | .gradle
36 | local.properties
37 | android.iml
38 |
39 | # Cocoapods
40 | #
41 | example/ios/Pods
42 |
43 | # node.js
44 | #
45 | node_modules/
46 | npm-debug.log
47 | yarn-debug.log
48 | yarn-error.log
49 |
50 | # BUCK
51 | buck-out/
52 | \.buckd/
53 | android/app/libs
54 | android/keystores/debug.keystore
55 |
56 | # Expo
57 | .expo/*
58 |
59 | # generated by bob
60 | lib/
61 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project.
4 |
5 | ## Development workflow
6 |
7 | To get started with the project, run `yarn bootstrap` in the root directory to install the required dependencies for each package:
8 |
9 | ```sh
10 | yarn bootstrap
11 | ```
12 |
13 | While developing, you can run the [example app](/example/) to test your changes.
14 |
15 | To start the packager:
16 |
17 | ```sh
18 | yarn example start
19 | ```
20 |
21 | To run the example app on Android:
22 |
23 | ```sh
24 | yarn example android
25 | ```
26 |
27 | To run the example app on iOS:
28 |
29 | ```sh
30 | yarn example ios
31 | ```
32 |
33 | Make sure your code passes TypeScript and ESLint. Run the following to verify:
34 |
35 | ```sh
36 | yarn typescript
37 | yarn lint
38 | ```
39 |
40 | To fix formatting errors, run the following:
41 |
42 | ```sh
43 | yarn lint --fix
44 | ```
45 |
46 | Remember to add tests for your change if possible. Run the unit tests by:
47 |
48 | ```sh
49 | yarn test
50 | ```
51 |
52 | To edit the Objective-C files, open `example/ios/MlkitOcrExample.xcworkspace` in XCode and find the source files at `Pods > Development Pods > react-native-mlkit-ocr`.
53 |
54 | To edit the Kotlin files, open `example/android` in Android studio and find the source files at `reactnativemlkitocr` under `Android`.
55 |
56 | ### Commit message convention
57 |
58 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages:
59 |
60 | - `fix`: bug fixes, e.g. fix crash due to deprecated method.
61 | - `feat`: new features, e.g. add new method to the module.
62 | - `refactor`: code refactor, e.g. migrate from class components to hooks.
63 | - `docs`: changes into documentation, e.g. add usage example for the module..
64 | - `test`: adding or updating tests, eg add integration tests using detox.
65 | - `chore`: tooling changes, e.g. change CI config.
66 |
67 | Our pre-commit hooks verify that your commit message matches this format when committing.
68 |
69 | ### Linting and tests
70 |
71 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/)
72 |
73 | We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing.
74 |
75 | Our pre-commit hooks verify that the linter and tests pass when committing.
76 |
77 | ### Scripts
78 |
79 | The `package.json` file contains various scripts for common tasks:
80 |
81 | - `yarn bootstrap`: setup project by installing all dependencies and pods.
82 | - `yarn typescript`: type-check files with TypeScript.
83 | - `yarn lint`: lint files with ESLint.
84 | - `yarn test`: run unit tests with Jest.
85 | - `yarn example start`: start the Metro server for the example app.
86 | - `yarn example android`: run the example app on Android.
87 | - `yarn example ios`: run the example app on iOS.
88 |
89 | ### Sending a pull request
90 |
91 | > **Working on your first pull request?** You can learn how from this _free_ series: [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github).
92 |
93 | When you're sending a pull request:
94 |
95 | - Prefer small pull requests focused on one change.
96 | - Verify that linters and tests are passing.
97 | - Review the documentation to make sure it looks good.
98 | - Follow the pull request template when opening a pull request.
99 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue.
100 |
101 | ## Code of Conduct
102 |
103 | ### Our Pledge
104 |
105 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
106 |
107 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
108 |
109 | ### Our Standards
110 |
111 | Examples of behavior that contributes to a positive environment for our community include:
112 |
113 | - Demonstrating empathy and kindness toward other people
114 | - Being respectful of differing opinions, viewpoints, and experiences
115 | - Giving and gracefully accepting constructive feedback
116 | - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
117 | - Focusing on what is best not just for us as individuals, but for the overall community
118 |
119 | Examples of unacceptable behavior include:
120 |
121 | - The use of sexualized language or imagery, and sexual attention or
122 | advances of any kind
123 | - Trolling, insulting or derogatory comments, and personal or political attacks
124 | - Public or private harassment
125 | - Publishing others' private information, such as a physical or email
126 | address, without their explicit permission
127 | - Other conduct which could reasonably be considered inappropriate in a
128 | professional setting
129 |
130 | ### Enforcement Responsibilities
131 |
132 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
133 |
134 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
135 |
136 | ### Scope
137 |
138 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
139 |
140 | ### Enforcement
141 |
142 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly.
143 |
144 | All community leaders are obligated to respect the privacy and security of the reporter of any incident.
145 |
146 | ### Enforcement Guidelines
147 |
148 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
149 |
150 | #### 1. Correction
151 |
152 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
153 |
154 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
155 |
156 | #### 2. Warning
157 |
158 | **Community Impact**: A violation through a single incident or series of actions.
159 |
160 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
161 |
162 | #### 3. Temporary Ban
163 |
164 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
165 |
166 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
167 |
168 | #### 4. Permanent Ban
169 |
170 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
171 |
172 | **Consequence**: A permanent ban from any sort of public interaction within the community.
173 |
174 | ### Attribution
175 |
176 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
177 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
178 |
179 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
180 |
181 | [homepage]: https://www.contributor-covenant.org
182 |
183 | For answers to common questions about this code of conduct, see the FAQ at
184 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
185 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Andrew Goldis
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.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # react-native-mlkit-ocr
2 |
3 | Google on-device MLKit text recognition for React Native
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 | ## Installation
12 |
13 | ```sh
14 | npm install react-native-mlkit-ocr
15 | ```
16 | ## Post-install Steps
17 |
18 | ### iOS
19 | Run
20 |
21 | ```js
22 | cd ios && pod install
23 | ```
24 |
25 | ## Usage
26 |
27 | ```js
28 | import MlkitOcr from 'react-native-mlkit-ocr';
29 |
30 | // ...
31 |
32 | const resultFromUri = await MlkitOcr.detectFromUri(uri);
33 | const resultFromFile = await MlkitOcr.detectFromFile(path);
34 | ```
35 |
36 |
37 | ## Example
38 |
39 | To get started with the project, run `yarn bootstrap` in the root directory to install the required dependencies for each package:
40 |
41 | ```sh
42 | yarn bootstrap
43 | ```
44 |
45 | To start the packager:
46 |
47 | ```sh
48 | yarn example start
49 | ```
50 |
51 | To run the example app on Android:
52 |
53 | ```sh
54 | yarn example android
55 | ```
56 |
57 | To run the example app on iOS:
58 |
59 | ```sh
60 | yarn example ios
61 | ```
62 |
63 | ## Contributing
64 |
65 | See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.
66 |
67 | ## License
68 |
69 | MIT
70 |
--------------------------------------------------------------------------------
/android/build.gradle:
--------------------------------------------------------------------------------
1 | import groovy.json.JsonSlurper
2 | import java.nio.file.Paths
3 |
4 | buildscript {
5 |
6 | def kotlin_version = rootProject.ext.has('kotlinVersion') ? rootProject.ext.get('kotlinVersion') : project.properties['MlkitOcr_kotlinVersion']
7 |
8 | ext.safeExtGet = { prop ->
9 | rootProject.ext.has(prop) ? rootProject.ext.get(prop) : project.properties["MlkitOcr_${prop}"]
10 | }
11 |
12 | repositories {
13 | google()
14 | gradlePluginPortal()
15 | mavenCentral()
16 | }
17 |
18 | dependencies {
19 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
20 | }
21 | }
22 |
23 | def getExtOrDefault(name) {
24 | return rootProject.ext.has(name) ? rootProject.ext.get(name) : project.properties["MlkitOcr_${name}"]
25 | }
26 |
27 | def isNewArchitectureEnabled() {
28 | return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
29 | }
30 |
31 | static def findNodeModulePath(baseDir, packageName) {
32 | def basePath = baseDir.toPath().normalize()
33 | // Node's module resolution algorithm searches up to the root directory,
34 | // after which the base path will be null
35 | while (basePath) {
36 | def candidatePath = Paths.get(basePath.toString(), "node_modules", packageName)
37 | if (candidatePath.toFile().exists()) {
38 | return candidatePath.toString()
39 | }
40 | basePath = basePath.getParent()
41 | }
42 | return null
43 | }
44 |
45 | def findNodeModulePath(packageName) {
46 | // Don't start in the project dir, as its path ends with node_modules/react-native-mlkit-ocr/android
47 | // we want to go two levels up, so we end up in the first_node modules and eventually
48 | // search upwards if the package is not found there
49 | return findNodeModulePath(projectDir.toPath().parent.parent.toFile(), packageName)
50 | }
51 |
52 | apply plugin: 'com.android.library'
53 | apply plugin: 'kotlin-android'
54 |
55 | if (isNewArchitectureEnabled()) {
56 | apply plugin: 'com.facebook.react'
57 | }
58 |
59 | android {
60 | compileSdkVersion safeExtGet('compileSdkVersion')
61 |
62 | // Used to override the NDK path/version on internal CI or by allowing
63 | // users to customize the NDK path/version from their root project (e.g. for M1 support)
64 | if (rootProject.hasProperty("ndkPath")) {
65 | ndkPath rootProject.ext.ndkPath
66 | }
67 | if (rootProject.hasProperty("ndkVersion")) {
68 | ndkVersion rootProject.ext.ndkVersion
69 | }
70 |
71 | defaultConfig {
72 | minSdkVersion getExtOrDefault('minSdkVersion')
73 | targetSdkVersion getExtOrDefault('targetSdkVersion')
74 | buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
75 | versionCode 110
76 | versionName "1.1.0"
77 | }
78 |
79 | compileOptions {
80 | sourceCompatibility JavaVersion.VERSION_1_8
81 | targetCompatibility JavaVersion.VERSION_1_8
82 | }
83 |
84 | lintOptions {
85 | abortOnError false
86 | }
87 |
88 | sourceSets {
89 | main {
90 | if (isNewArchitectureEnabled()) {
91 | java.srcDirs += ["src/newarch",
92 | "${project.buildDir}/generated/source/codegen/java"]
93 | } else {
94 | java.srcDirs += ["src/oldarch"]
95 | }
96 | }
97 | }
98 | }
99 |
100 | repositories {
101 | maven {
102 | // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
103 | url "${rootDir}/../node_modules/react-native/android"
104 | }
105 | mavenCentral()
106 | google()
107 | }
108 |
109 | def kotlin_version = getExtOrDefault('kotlinVersion')
110 |
111 | dependencies {
112 |
113 | if (isNewArchitectureEnabled()) {
114 | implementation project(":ReactAndroid")
115 | } else {
116 | implementation 'com.facebook.react:react-native:+'
117 | }
118 |
119 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
120 |
121 | implementation 'com.google.android.gms:play-services-mlkit-text-recognition:18.0.2'
122 | }
123 |
124 | if (isNewArchitectureEnabled()) {
125 | react {
126 | reactNativeDir = rootProject.file(findNodeModulePath(rootProject.rootDir, "react-native") ?: "../node_modules/react-native/")
127 | jsRootDir = file("../src/")
128 | codegenDir = rootProject.file(findNodeModulePath(rootProject.rootDir, "react-native-codegen") ?: "../node_modules/react-native-codegen/")
129 | libraryName = "mlkitocr"
130 | codegenJavaPackageName = "com.reactnativemlkitocr"
131 | }
132 |
133 | // Resolves "LOCAL_SRC_FILES points to a missing file, Check that libfb.so exists or that its path is correct".
134 | tasks.whenTaskAdded { task ->
135 | if (task.name.contains("configureCMakeDebug")) {
136 | rootProject.getTasksByName("packageReactNdkDebugLibs", true).forEach {
137 | task.dependsOn(it)
138 | }
139 | }
140 | // We want to add a dependency for both configureCMakeRelease and configureCMakeRelWithDebInfo
141 | if (task.name.contains("configureCMakeRel")) {
142 | rootProject.getTasksByName("packageReactNdkReleaseLibs", true).forEach {
143 | task.dependsOn(it)
144 | }
145 | }
146 | }
147 | }
148 |
--------------------------------------------------------------------------------
/android/gradle.properties:
--------------------------------------------------------------------------------
1 | MlkitOcr_kotlinVersion=1.6.10
2 | MlkitOcr_minSdkVersion=21
3 | MlkitOcr_compileSdkVersion=31
4 | MlkitOcr_targetSdkVersion=31
5 |
--------------------------------------------------------------------------------
/android/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/android/src/main/java/com/reactnativemlkitocr/MlkitOcrModuleImpl.kt:
--------------------------------------------------------------------------------
1 | package com.reactnativemlkitocr
2 |
3 | import android.graphics.Point
4 | import android.graphics.Rect
5 | import android.net.Uri
6 | import com.facebook.react.bridge.*
7 | import com.google.mlkit.vision.common.InputImage
8 | import com.google.mlkit.vision.text.Text
9 | import com.google.mlkit.vision.text.TextRecognition
10 | import com.google.mlkit.vision.text.latin.TextRecognizerOptions
11 | import java.lang.Exception
12 |
13 | class MlkitOcrModuleImpl {
14 |
15 | companion object {
16 | const val NAME = "MlkitOcr"
17 |
18 | fun detectFromResource(context: ReactApplicationContext, path: String, promise: Promise) {
19 | val image: InputImage;
20 | try {
21 | image = InputImage.fromFilePath(context, Uri.parse(path))
22 | val recognizer = TextRecognition.getClient(TextRecognizerOptions.DEFAULT_OPTIONS)
23 | recognizer.process(image).addOnSuccessListener { visionText ->
24 | promise.resolve(getDataAsArray(visionText))
25 | }.addOnFailureListener { e ->
26 | promise.reject(e);
27 | e.printStackTrace();
28 | }
29 | } catch (e: Exception) {
30 | promise.reject(e);
31 | e.printStackTrace();
32 | }
33 | }
34 |
35 | private fun getCoordinates(boundingBox: Rect?): WritableMap {
36 | val coordinates: WritableMap = Arguments.createMap()
37 | if (boundingBox == null) {
38 | coordinates.putNull("top")
39 | coordinates.putNull("left")
40 | coordinates.putNull("width")
41 | coordinates.putNull("height")
42 | } else {
43 | coordinates.putInt("top", boundingBox.top)
44 | coordinates.putInt("left", boundingBox.left)
45 | coordinates.putInt("width", boundingBox.width())
46 | coordinates.putInt("height", boundingBox.height())
47 | }
48 | return coordinates;
49 | }
50 |
51 | private fun getCornerPoints(pointsList: Array?): WritableArray {
52 | val p: WritableArray = Arguments.createArray()
53 | if (pointsList == null) {
54 | return p;
55 | }
56 |
57 | pointsList.forEach { point ->
58 | val i: WritableMap = Arguments.createMap()
59 | i.putInt("x", point.x);
60 | i.putInt("y", point.y);
61 | p.pushMap(i);
62 | }
63 |
64 | return p;
65 | }
66 |
67 |
68 | private fun getDataAsArray(visionText: Text): WritableArray? {
69 | val data: WritableArray = Arguments.createArray()
70 |
71 | for (block in visionText.textBlocks) {
72 | val blockElements: WritableArray = Arguments.createArray()
73 | for (line in block.lines) {
74 | val lineElements: WritableArray = Arguments.createArray()
75 | for (element in line.elements) {
76 | val e: WritableMap = Arguments.createMap()
77 | e.putString("text", element.text)
78 | e.putMap("bounding", getCoordinates(element.boundingBox))
79 | e.putArray("cornerPoints", getCornerPoints(element.cornerPoints))
80 | e.putString("confidence", element.confidence.toString())
81 | lineElements.pushMap(e)
82 | }
83 | val l: WritableMap = Arguments.createMap()
84 | val lCoordinates = getCoordinates(line.boundingBox)
85 | l.putString("text", line.text)
86 | l.putMap("bounding", lCoordinates)
87 | l.putArray("elements", lineElements)
88 | l.putArray("cornerPoints", getCornerPoints(line.cornerPoints))
89 | l.putString("confidence", line.confidence.toString())
90 |
91 | blockElements.pushMap(l)
92 | }
93 |
94 | val info: WritableMap = Arguments.createMap()
95 |
96 |
97 | info.putMap("bounding", getCoordinates(block.boundingBox))
98 | info.putString("text", block.text)
99 | info.putArray("lines", blockElements)
100 | info.putArray("cornerPoints", getCornerPoints(block.cornerPoints))
101 | data.pushMap(info)
102 | }
103 | return data
104 | }
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/android/src/main/java/com/reactnativemlkitocr/MlkitOcrPackage.kt:
--------------------------------------------------------------------------------
1 | package com.reactnativemlkitocr
2 |
3 | import com.facebook.react.TurboReactPackage
4 | import com.facebook.react.bridge.NativeModule
5 | import com.facebook.react.bridge.ReactApplicationContext
6 | import com.facebook.react.module.annotations.ReactModule
7 | import com.facebook.react.module.model.ReactModuleInfo
8 | import com.facebook.react.module.model.ReactModuleInfoProvider
9 | import com.facebook.react.turbomodule.core.interfaces.TurboModule
10 | import java.util.*
11 |
12 | class MlkitOcrPackage : TurboReactPackage() {
13 |
14 | override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? {
15 | return if (name == MlkitOcrModuleImpl.NAME) {
16 | MlkitOcrModule(reactContext)
17 | } else {
18 | null
19 | }
20 | }
21 |
22 | override fun getReactModuleInfoProvider(): ReactModuleInfoProvider {
23 | return ReactModuleInfoProvider {
24 | val moduleInfos: MutableMap =
25 | HashMap()
26 | val isTurboModule = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
27 | moduleInfos[MlkitOcrModuleImpl.NAME] = ReactModuleInfo(
28 | MlkitOcrModuleImpl.NAME,
29 | MlkitOcrModuleImpl.NAME,
30 | false, // canOverrideExistingModule
31 | false, // needsEagerInit
32 | true, // hasConstants
33 | false, // isCxxModule
34 | isTurboModule // isTurboModule
35 | )
36 | moduleInfos
37 | }
38 | }
39 | }
40 |
41 |
--------------------------------------------------------------------------------
/android/src/newarch/java/com/reactnativemlkitocr/MlkitOcrModule.kt:
--------------------------------------------------------------------------------
1 | package com.reactnativemlkitocr
2 |
3 | import com.facebook.react.bridge.Promise
4 | import com.facebook.react.bridge.ReactApplicationContext
5 |
6 | class MlkitOcrModule(reactContext: ReactApplicationContext) :
7 | NativeMlkitOcrSpec(reactContext) {
8 |
9 | override fun getName(): String {
10 | return NAME
11 | }
12 |
13 | override fun detectFromUri(imagePath: String, promise: Promise) {
14 | return MlkitOcrModuleImpl.detectFromResource(this.reactApplicationContext, imagePath, promise)
15 | }
16 |
17 | override fun detectFromFile(imagePath: String, promise: Promise) {
18 | return MlkitOcrModuleImpl.detectFromResource(this.reactApplicationContext, imagePath, promise)
19 | }
20 |
21 | companion object {
22 | const val NAME = MlkitOcrModuleImpl.NAME
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/android/src/oldarch/java/com/reactnativemlkitocr/MlkitOcrModule.kt:
--------------------------------------------------------------------------------
1 | package com.reactnativemlkitocr
2 |
3 | import com.facebook.react.bridge.Promise
4 | import com.facebook.react.bridge.ReactApplicationContext
5 | import com.facebook.react.bridge.ReactContextBaseJavaModule
6 | import com.facebook.react.bridge.ReactMethod
7 |
8 | class MlkitOcrModule internal constructor(context: ReactApplicationContext?) :
9 | ReactContextBaseJavaModule(context) {
10 |
11 | override fun getName(): String {
12 | return MlkitOcrModuleImpl.NAME
13 | }
14 |
15 | @ReactMethod
16 | fun detectFromUri(imagePath: String, promise: Promise) {
17 | return MlkitOcrModuleImpl.detectFromResource(this.reactApplicationContext, imagePath, promise)
18 | }
19 |
20 | @ReactMethod
21 | fun detectFromFile(imagePath: String, promise: Promise) {
22 | return MlkitOcrModuleImpl.detectFromResource(this.reactApplicationContext, imagePath, promise)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | presets: ['module:metro-react-native-babel-preset'],
3 | };
4 |
--------------------------------------------------------------------------------
/example/android/app/_BUCK:
--------------------------------------------------------------------------------
1 | # To learn about Buck see [Docs](https://buckbuild.com/).
2 | # To run your application with Buck:
3 | # - install Buck
4 | # - `npm start` - to start the packager
5 | # - `cd android`
6 | # - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"`
7 | # - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck
8 | # - `buck install -r android/app` - compile, install and run application
9 | #
10 |
11 | load(":build_defs.bzl", "create_aar_targets", "create_jar_targets")
12 |
13 | lib_deps = []
14 |
15 | create_aar_targets(glob(["libs/*.aar"]))
16 |
17 | create_jar_targets(glob(["libs/*.jar"]))
18 |
19 | android_library(
20 | name = "all-libs",
21 | exported_deps = lib_deps,
22 | )
23 |
24 | android_library(
25 | name = "app-code",
26 | srcs = glob([
27 | "src/main/java/**/*.java",
28 | ]),
29 | deps = [
30 | ":all-libs",
31 | ":build_config",
32 | ":res",
33 | ],
34 | )
35 |
36 | android_build_config(
37 | name = "build_config",
38 | package = "com.example.reactnativemlkitocr",
39 | )
40 |
41 | android_resource(
42 | name = "res",
43 | package = "com.example.reactnativemlkitocr",
44 | res = "src/main/res",
45 | )
46 |
47 | android_binary(
48 | name = "app",
49 | keystore = "//android/keystores:debug",
50 | manifest = "src/main/AndroidManifest.xml",
51 | package_type = "debug",
52 | deps = [
53 | ":app-code",
54 | ],
55 | )
56 |
--------------------------------------------------------------------------------
/example/android/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: "com.android.application"
2 |
3 | if (isNewArchitectureEnabled()) {
4 | apply plugin: "com.facebook.react"
5 | }
6 |
7 | import com.android.build.OutputFile
8 | import org.apache.tools.ant.taskdefs.condition.Os
9 |
10 | /**
11 | * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
12 | * and bundleReleaseJsAndAssets).
13 | * These basically call `react-native bundle` with the correct arguments during the Android build
14 | * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
15 | * bundle directly from the development server. Below you can see all the possible configurations
16 | * and their defaults. If you decide to add a configuration block, make sure to add it before the
17 | * `apply from: "../../node_modules/react-native/react.gradle"` line.
18 | *
19 | * project.ext.react = [
20 | * // the name of the generated asset file containing your JS bundle
21 | * bundleAssetName: "index.android.bundle",
22 | *
23 | * // the entry file for bundle generation. If none specified and
24 | * // "index.android.js" exists, it will be used. Otherwise "index.js" is
25 | * // default. Can be overridden with ENTRY_FILE environment variable.
26 | * entryFile: "index.android.js",
27 | *
28 | * // https://reactnative.dev/docs/performance#enable-the-ram-format
29 | * bundleCommand: "ram-bundle",
30 | *
31 | * // whether to bundle JS and assets in debug mode
32 | * bundleInDebug: false,
33 | *
34 | * // whether to bundle JS and assets in release mode
35 | * bundleInRelease: true,
36 | *
37 | * // whether to bundle JS and assets in another build variant (if configured).
38 | * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
39 | * // The configuration property can be in the following formats
40 | * // 'bundleIn${productFlavor}${buildType}'
41 | * // 'bundleIn${buildType}'
42 | * // bundleInFreeDebug: true,
43 | * // bundleInPaidRelease: true,
44 | * // bundleInBeta: true,
45 | *
46 | * // whether to disable dev mode in custom build variants (by default only disabled in release)
47 | * // for MlkitOcrExample: to disable dev mode in the staging build type (if configured)
48 | * devDisabledInStaging: true,
49 | * // The configuration property can be in the following formats
50 | * // 'devDisabledIn${productFlavor}${buildType}'
51 | * // 'devDisabledIn${buildType}'
52 | *
53 | * // the root of your project, i.e. where "package.json" lives
54 | * root: "../../",
55 | *
56 | * // where to put the JS bundle asset in debug mode
57 | * jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
58 | *
59 | * // where to put the JS bundle asset in release mode
60 | * jsBundleDirRelease: "$buildDir/intermediates/assets/release",
61 | *
62 | * // where to put drawable resources / React Native assets, e.g. the ones you use via
63 | * // require('./image.png')), in debug mode
64 | * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
65 | *
66 | * // where to put drawable resources / React Native assets, e.g. the ones you use via
67 | * // require('./image.png')), in release mode
68 | * resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
69 | *
70 | * // by default the gradle tasks are skipped if none of the JS files or assets change; this means
71 | * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
72 | * // date; if you have any other folders that you want to ignore for performance reasons (gradle
73 | * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
74 | * // for MlkitOcrExample, you might want to remove it from here.
75 | * inputExcludes: ["android/**", "ios/**"],
76 | *
77 | * // override which node gets called and with what additional arguments
78 | * nodeExecutableAndArgs: ["node"],
79 | *
80 | * // supply additional arguments to the packager
81 | * extraPackagerArgs: []
82 | * ]
83 | */
84 |
85 | project.ext.react = [
86 | enableHermes: true, // clean and rebuild if changing
87 | ]
88 |
89 | apply from: "../../node_modules/react-native/react.gradle"
90 |
91 | /**
92 | * Set this to true to create two separate APKs instead of one:
93 | * - An APK that only works on ARM devices
94 | * - An APK that only works on x86 devices
95 | * The advantage is the size of the APK is reduced by about 4MB.
96 | * Upload all the APKs to the Play Store and people will download
97 | * the correct one based on the CPU architecture of their device.
98 | */
99 | def enableSeparateBuildPerCPUArchitecture = false
100 |
101 | /**
102 | * Run Proguard to shrink the Java bytecode in release builds.
103 | */
104 | def enableProguardInReleaseBuilds = false
105 |
106 | /**
107 | * The preferred build flavor of JavaScriptCore.
108 | *
109 | * For MlkitOcrExample, to use the international variant, you can use:
110 | * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
111 | *
112 | * The international variant includes ICU i18n library and necessary data
113 | * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
114 | * give correct results when using with locales other than en-US. Note that
115 | * this variant is about 6MiB larger per architecture than default.
116 | */
117 | def jscFlavor = 'org.webkit:android-jsc:+'
118 |
119 | /**
120 | * Whether to enable the Hermes VM.
121 | *
122 | * This should be set on project.ext.react and that value will be read here. If it is not set
123 | * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
124 | * and the benefits of using Hermes will therefore be sharply reduced.
125 | */
126 | def enableHermes = project.ext.react.get("enableHermes", false);
127 |
128 | /**
129 | * Architectures to build native code for.
130 | */
131 | def reactNativeArchitectures() {
132 | def value = project.getProperties().get("reactNativeArchitectures")
133 | return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
134 | }
135 |
136 | android {
137 | ndkVersion rootProject.ext.ndkVersion
138 |
139 | compileSdkVersion rootProject.ext.compileSdkVersion
140 |
141 | defaultConfig {
142 | applicationId "com.example.reactnativemlkitocr"
143 | minSdkVersion rootProject.ext.minSdkVersion
144 | targetSdkVersion rootProject.ext.targetSdkVersion
145 | versionCode 1
146 | versionName "1.0"
147 | buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
148 |
149 | if (isNewArchitectureEnabled()) {
150 | // We configure the NDK build only if you decide to opt-in for the New Architecture.
151 | externalNativeBuild {
152 | ndkBuild {
153 | arguments "APP_PLATFORM=android-21",
154 | "APP_STL=c++_shared",
155 | "NDK_TOOLCHAIN_VERSION=clang",
156 | "GENERATED_SRC_DIR=$buildDir/generated/source",
157 | "PROJECT_BUILD_DIR=$buildDir",
158 | "REACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid",
159 | "REACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build",
160 | "NODE_MODULES_DIR=$rootDir/../node_modules"
161 | cFlags "-Wall", "-Werror", "-fexceptions", "-frtti", "-DWITH_INSPECTOR=1"
162 | cppFlags "-std=c++17"
163 | // Make sure this target name is the same you specify inside the
164 | // src/main/jni/Android.mk file for the `LOCAL_MODULE` variable.
165 | targets "mlkitocrexample_appmodules"
166 | }
167 | }
168 | if (!enableSeparateBuildPerCPUArchitecture) {
169 | ndk {
170 | abiFilters (*reactNativeArchitectures())
171 | }
172 | }
173 | }
174 | }
175 |
176 | if (isNewArchitectureEnabled()) {
177 | // We configure the NDK build only if you decide to opt-in for the New Architecture.
178 | externalNativeBuild {
179 | ndkBuild {
180 | path "$projectDir/src/main/jni/Android.mk"
181 | }
182 | }
183 | def reactAndroidProjectDir = project(':ReactAndroid').projectDir
184 | def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) {
185 | dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck")
186 | from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
187 | into("$buildDir/react-ndk/exported")
188 | }
189 | def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) {
190 | dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck")
191 | from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
192 | into("$buildDir/react-ndk/exported")
193 | }
194 | afterEvaluate {
195 | // If you wish to add a custom TurboModule or component locally,
196 | // you should uncomment this line.
197 | // preBuild.dependsOn("generateCodegenArtifactsFromSchema")
198 | preDebugBuild.dependsOn(packageReactNdkDebugLibs)
199 | preReleaseBuild.dependsOn(packageReactNdkReleaseLibs)
200 |
201 | // Due to a bug inside AGP, we have to explicitly set a dependency
202 | // between configureNdkBuild* tasks and the preBuild tasks.
203 | // This can be removed once this is solved: https://issuetracker.google.com/issues/207403732
204 | configureNdkBuildRelease.dependsOn(preReleaseBuild)
205 | configureNdkBuildDebug.dependsOn(preDebugBuild)
206 | reactNativeArchitectures().each { architecture ->
207 | tasks.findByName("configureNdkBuildDebug[${architecture}]")?.configure {
208 | dependsOn("preDebugBuild")
209 | }
210 | tasks.findByName("configureNdkBuildRelease[${architecture}]")?.configure {
211 | dependsOn("preReleaseBuild")
212 | }
213 | }
214 | }
215 | }
216 |
217 | splits {
218 | abi {
219 | reset()
220 | enable enableSeparateBuildPerCPUArchitecture
221 | universalApk false // If true, also generate a universal APK
222 | include(*reactNativeArchitectures())
223 | }
224 | }
225 |
226 | signingConfigs {
227 | debug {
228 | storeFile file('debug.keystore')
229 | storePassword 'android'
230 | keyAlias 'androiddebugkey'
231 | keyPassword 'android'
232 | }
233 | }
234 |
235 | buildTypes {
236 | debug {
237 | signingConfig signingConfigs.debug
238 | }
239 | release {
240 | // Caution! In production, you need to generate your own keystore file.
241 | // see https://reactnative.dev/docs/signed-apk-android.
242 | signingConfig signingConfigs.debug
243 | minifyEnabled enableProguardInReleaseBuilds
244 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
245 | }
246 | }
247 |
248 | // applicationVariants are e.g. debug, release
249 | applicationVariants.all { variant ->
250 | variant.outputs.each { output ->
251 | // For each separate APK per architecture, set a unique version code as described here:
252 | // https://developer.android.com/studio/build/configure-apk-splits.html
253 | // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
254 | def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
255 | def abi = output.getFilter(OutputFile.ABI)
256 | if (abi != null) { // null for the universal-debug, universal-release variants
257 | output.versionCodeOverride =
258 | defaultConfig.versionCode * 1000 + versionCodes.get(abi)
259 | }
260 | }
261 | }
262 |
263 | packagingOptions {
264 | pickFirst '**/*/libc++_shared.so'
265 | pickFirst '**/*/libjsc.so'
266 | pickFirst '**/*/libfb.so'
267 | }
268 | }
269 |
270 | dependencies {
271 | implementation fileTree(dir: "libs", include: ["*.jar"])
272 |
273 | //noinspection GradleDynamicVersion
274 | implementation "com.facebook.react:react-native:+" // From node_modules
275 |
276 | implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
277 |
278 | debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
279 | exclude group:'com.facebook.fbjni'
280 | }
281 |
282 | debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
283 | exclude group:'com.facebook.flipper'
284 | exclude group:'com.squareup.okhttp3', module:'okhttp'
285 | }
286 |
287 | debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
288 | exclude group:'com.facebook.flipper'
289 | }
290 |
291 | if (enableHermes) {
292 | //noinspection GradleDynamicVersion
293 | implementation("com.facebook.react:hermes-engine:+") { // From node_modules
294 | exclude group:'com.facebook.fbjni'
295 | }
296 | } else {
297 | implementation jscFlavor
298 | }
299 | }
300 |
301 | if (isNewArchitectureEnabled()) {
302 | // If new architecture is enabled, we let you build RN from source
303 | // Otherwise we fallback to a prebuilt .aar bundled in the NPM package.
304 | // This will be applied to all the imported transtitive dependency.
305 | configurations.all {
306 | resolutionStrategy.dependencySubstitution {
307 | substitute(module("com.facebook.react:react-native"))
308 | .using(project(":ReactAndroid"))
309 | .because("On New Architecture we're building React Native from source")
310 | substitute(module("com.facebook.react:hermes-engine"))
311 | .using(project(":ReactAndroid:hermes-engine"))
312 | .because("On New Architecture we're building Hermes from source")
313 | }
314 | }
315 | }
316 |
317 | // Run this once to be able to run the application with BUCK
318 | // puts all compile dependencies into folder libs for BUCK to use
319 | task copyDownloadableDepsToLibs(type: Copy) {
320 | from configurations.implementation
321 | into 'libs'
322 | }
323 |
324 | apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
325 |
326 | def isNewArchitectureEnabled() {
327 | // To opt-in for the New Architecture, you can either:
328 | // - Set `newArchEnabled` to true inside the `gradle.properties` file
329 | // - Invoke gradle with `-newArchEnabled=true`
330 | // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
331 | return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
332 | }
333 |
--------------------------------------------------------------------------------
/example/android/app/build_defs.bzl:
--------------------------------------------------------------------------------
1 | """Helper definitions to glob .aar and .jar targets"""
2 |
3 | def create_aar_targets(aarfiles):
4 | for aarfile in aarfiles:
5 | name = "aars__" + aarfile[aarfile.rindex("/") + 1:aarfile.rindex(".aar")]
6 | lib_deps.append(":" + name)
7 | android_prebuilt_aar(
8 | name = name,
9 | aar = aarfile,
10 | )
11 |
12 | def create_jar_targets(jarfiles):
13 | for jarfile in jarfiles:
14 | name = "jars__" + jarfile[jarfile.rindex("/") + 1:jarfile.rindex(".jar")]
15 | lib_deps.append(":" + name)
16 | prebuilt_jar(
17 | name = name,
18 | binary_jar = jarfile,
19 | )
20 |
--------------------------------------------------------------------------------
/example/android/app/debug.keystore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/agoldis/react-native-mlkit-ocr/38064ca19f20a498f5e1c8bd32e22efc548ba0b5/example/android/app/debug.keystore
--------------------------------------------------------------------------------
/example/android/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # By default, the flags in this file are appended to flags specified
3 | # in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
4 | # You can edit the include path and order by changing the proguardFiles
5 | # directive in build.gradle.
6 | #
7 | # For more details, see
8 | # http://developer.android.com/guide/developing/tools/proguard.html
9 |
10 | # Add any project specific keep options here:
11 |
--------------------------------------------------------------------------------
/example/android/app/src/debug/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/example/android/app/src/debug/java/com/example/reactnativemlkitocr/ReactNativeFlipper.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) Meta Platforms, Inc. and affiliates.
3 | *
4 | *
This source code is licensed under the MIT license found in the LICENSE file in the root
5 | * directory of this source tree.
6 | */
7 | package com.example.reactnativemlkitocr;
8 |
9 | import android.content.Context;
10 | import com.facebook.flipper.android.AndroidFlipperClient;
11 | import com.facebook.flipper.android.utils.FlipperUtils;
12 | import com.facebook.flipper.core.FlipperClient;
13 | import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin;
14 | import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin;
15 | import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin;
16 | import com.facebook.flipper.plugins.inspector.DescriptorMapping;
17 | import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin;
18 | import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor;
19 | import com.facebook.flipper.plugins.network.NetworkFlipperPlugin;
20 | import com.facebook.flipper.plugins.react.ReactFlipperPlugin;
21 | import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin;
22 | import com.facebook.react.ReactInstanceEventListener;
23 | import com.facebook.react.ReactInstanceManager;
24 | import com.facebook.react.bridge.ReactContext;
25 | import com.facebook.react.modules.network.NetworkingModule;
26 | import okhttp3.OkHttpClient;
27 |
28 | public class ReactNativeFlipper {
29 | public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
30 | if (FlipperUtils.shouldEnableFlipper(context)) {
31 | final FlipperClient client = AndroidFlipperClient.getInstance(context);
32 |
33 | client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults()));
34 | client.addPlugin(new ReactFlipperPlugin());
35 | client.addPlugin(new DatabasesFlipperPlugin(context));
36 | client.addPlugin(new SharedPreferencesFlipperPlugin(context));
37 | client.addPlugin(CrashReporterPlugin.getInstance());
38 |
39 | NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
40 | NetworkingModule.setCustomClientBuilder(
41 | new NetworkingModule.CustomClientBuilder() {
42 | @Override
43 | public void apply(OkHttpClient.Builder builder) {
44 | builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
45 | }
46 | });
47 | client.addPlugin(networkFlipperPlugin);
48 | client.start();
49 |
50 | // Fresco Plugin needs to ensure that ImagePipelineFactory is initialized
51 | // Hence we run if after all native modules have been initialized
52 | ReactContext reactContext = reactInstanceManager.getCurrentReactContext();
53 | if (reactContext == null) {
54 | reactInstanceManager.addReactInstanceEventListener(
55 | new ReactInstanceEventListener() {
56 | @Override
57 | public void onReactContextInitialized(ReactContext reactContext) {
58 | reactInstanceManager.removeReactInstanceEventListener(this);
59 | reactContext.runOnNativeModulesQueueThread(
60 | new Runnable() {
61 | @Override
62 | public void run() {
63 | client.addPlugin(new FrescoFlipperPlugin());
64 | }
65 | });
66 | }
67 | });
68 | } else {
69 | client.addPlugin(new FrescoFlipperPlugin());
70 | }
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/example/android/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
4 |
5 |
6 |
13 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/com/example/reactnativemlkitocr/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.example.reactnativemlkitocr;
2 |
3 | import com.facebook.react.ReactActivity;
4 | import com.facebook.react.ReactActivityDelegate;
5 | import com.facebook.react.ReactRootView;
6 |
7 | public class MainActivity extends ReactActivity {
8 |
9 | /**
10 | * Returns the name of the main component registered from JavaScript. This is used to schedule
11 | * rendering of the component.
12 | */
13 | @Override
14 | protected String getMainComponentName() {
15 | return "MlkitOcrExample";
16 | }
17 |
18 | /**
19 | * Returns the instance of the {@link ReactActivityDelegate}. There the RootView is created and
20 | * you can specify the rendered you wish to use (Fabric or the older renderer).
21 | */
22 | @Override
23 | protected ReactActivityDelegate createReactActivityDelegate() {
24 | return new MainActivityDelegate(this, getMainComponentName());
25 | }
26 |
27 | public static class MainActivityDelegate extends ReactActivityDelegate {
28 | public MainActivityDelegate(ReactActivity activity, String mainComponentName) {
29 | super(activity, mainComponentName);
30 | }
31 |
32 | @Override
33 | protected ReactRootView createRootView() {
34 | ReactRootView reactRootView = new ReactRootView(getContext());
35 | // If you opted-in for the New Architecture, we enable the Fabric Renderer.
36 | reactRootView.setIsFabric(BuildConfig.IS_NEW_ARCHITECTURE_ENABLED);
37 | return reactRootView;
38 | }
39 | }
40 | }
41 |
42 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/com/example/reactnativemlkitocr/MainApplication.java:
--------------------------------------------------------------------------------
1 | package com.example.reactnativemlkitocr;
2 |
3 | import android.app.Application;
4 | import android.content.Context;
5 |
6 | import com.facebook.react.PackageList;
7 | import com.facebook.react.ReactApplication;
8 | import com.facebook.react.ReactInstanceManager;
9 | import com.facebook.react.ReactNativeHost;
10 | import com.facebook.react.ReactPackage;
11 | import com.facebook.react.config.ReactFeatureFlags;
12 | import com.facebook.soloader.SoLoader;
13 | import com.example.reactnativemlkitocr.newarchitecture.MainApplicationReactNativeHost;
14 |
15 | import java.lang.reflect.InvocationTargetException;
16 | import java.util.List;
17 |
18 |
19 | public class MainApplication extends Application implements ReactApplication {
20 |
21 | private final ReactNativeHost mReactNativeHost =
22 | new ReactNativeHost(this) {
23 | @Override
24 | public boolean getUseDeveloperSupport() {
25 | return BuildConfig.DEBUG;
26 | }
27 |
28 | @Override
29 | protected List getPackages() {
30 | @SuppressWarnings("UnnecessaryLocalVariable")
31 | List packages = new PackageList(this).getPackages();
32 | // Packages that cannot be autolinked yet can be added manually here, for example:
33 | // packages.add(new MyReactNativePackage());
34 | return packages;
35 | }
36 |
37 | @Override
38 | protected String getJSMainModuleName() {
39 | return "index";
40 | }
41 | };
42 |
43 | private final ReactNativeHost mNewArchitectureNativeHost =
44 | new MainApplicationReactNativeHost(this);
45 |
46 | @Override
47 | public ReactNativeHost getReactNativeHost() {
48 | if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
49 | return mNewArchitectureNativeHost;
50 | } else {
51 | return mReactNativeHost;
52 | }
53 | }
54 |
55 | @Override
56 | public void onCreate() {
57 | super.onCreate();
58 | // If you opted-in for the New Architecture, we enable the TurboModule system
59 | ReactFeatureFlags.useTurboModules = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
60 | SoLoader.init(this, /* native exopackage */ false);
61 | initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
62 | }
63 |
64 | /**
65 | * Loads Flipper in React Native templates. Call this in the onCreate method with something like
66 | * initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
67 | *
68 | * @param context
69 | * @param reactInstanceManager
70 | */
71 | private static void initializeFlipper(
72 | Context context, ReactInstanceManager reactInstanceManager) {
73 | if (BuildConfig.DEBUG) {
74 | try {
75 | /*
76 | We use reflection here to pick up the class that initializes Flipper,
77 | since Flipper library is not available in release mode
78 | */
79 | Class> aClass = Class.forName("com.example.reactnativemlkitocr.ReactNativeFlipper");
80 | aClass
81 | .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
82 | .invoke(null, context, reactInstanceManager);
83 | } catch (ClassNotFoundException e) {
84 | e.printStackTrace();
85 | } catch (NoSuchMethodException e) {
86 | e.printStackTrace();
87 | } catch (IllegalAccessException e) {
88 | e.printStackTrace();
89 | } catch (InvocationTargetException e) {
90 | e.printStackTrace();
91 | }
92 | }
93 | }
94 | }
95 |
96 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/com/example/reactnativemlkitocr/newarchitecture/MainApplicationReactNativeHost.java:
--------------------------------------------------------------------------------
1 | package com.example.reactnativemlkitocr.newarchitecture;
2 |
3 | import android.app.Application;
4 | import androidx.annotation.NonNull;
5 | import com.facebook.react.PackageList;
6 | import com.facebook.react.ReactInstanceManager;
7 | import com.facebook.react.ReactNativeHost;
8 | import com.facebook.react.ReactPackage;
9 | import com.facebook.react.ReactPackageTurboModuleManagerDelegate;
10 | import com.facebook.react.bridge.JSIModulePackage;
11 | import com.facebook.react.bridge.JSIModuleProvider;
12 | import com.facebook.react.bridge.JSIModuleSpec;
13 | import com.facebook.react.bridge.JSIModuleType;
14 | import com.facebook.react.bridge.JavaScriptContextHolder;
15 | import com.facebook.react.bridge.ReactApplicationContext;
16 | import com.facebook.react.bridge.UIManager;
17 | import com.facebook.react.fabric.ComponentFactory;
18 | import com.facebook.react.fabric.CoreComponentsRegistry;
19 | import com.facebook.react.fabric.EmptyReactNativeConfig;
20 | import com.facebook.react.fabric.FabricJSIModuleProvider;
21 | import com.facebook.react.uimanager.ViewManagerRegistry;
22 | import com.example.reactnativemlkitocr.BuildConfig;
23 | import com.example.reactnativemlkitocr.newarchitecture.components.MainComponentsRegistry;
24 | import com.example.reactnativemlkitocr.newarchitecture.modules.MainApplicationTurboModuleManagerDelegate;
25 | import java.util.ArrayList;
26 | import java.util.List;
27 |
28 | import com.reactnativemlkitocr.MlkitOcrPackage;
29 |
30 | /**
31 | * A {@link ReactNativeHost} that helps you load everything needed for the New Architecture, both
32 | * TurboModule delegates and the Fabric Renderer.
33 | *
34 | *
Please note that this class is used ONLY if you opt-in for the New Architecture (see the
35 | * `newArchEnabled` property). Is ignored otherwise.
36 | */
37 | public class MainApplicationReactNativeHost extends ReactNativeHost {
38 | public MainApplicationReactNativeHost(Application application) {
39 | super(application);
40 | }
41 |
42 | @Override
43 | public boolean getUseDeveloperSupport() {
44 | return BuildConfig.DEBUG;
45 | }
46 |
47 | @Override
48 | protected List getPackages() {
49 | List packages = new PackageList(this).getPackages();
50 | // Packages that cannot be autolinked yet can be added manually here, for example:
51 | // packages.add(new MyReactNativePackage());
52 | // TurboModules must also be loaded here providing a valid TurboReactPackage implementation:
53 | // packages.add(new TurboReactPackage() { ... });
54 | // If you have custom Fabric Components, their ViewManagers should also be loaded here
55 | // inside a ReactPackage.
56 | packages.add(new MlkitOcrPackage());
57 | return packages;
58 | }
59 |
60 | @Override
61 | protected String getJSMainModuleName() {
62 | return "index";
63 | }
64 |
65 | @NonNull
66 | @Override
67 | protected ReactPackageTurboModuleManagerDelegate.Builder
68 | getReactPackageTurboModuleManagerDelegateBuilder() {
69 | // Here we provide the ReactPackageTurboModuleManagerDelegate Builder. This is necessary
70 | // for the new architecture and to use TurboModules correctly.
71 | return new MainApplicationTurboModuleManagerDelegate.Builder();
72 | }
73 |
74 | @Override
75 | protected JSIModulePackage getJSIModulePackage() {
76 | return new JSIModulePackage() {
77 | @Override
78 | public List getJSIModules(
79 | final ReactApplicationContext reactApplicationContext,
80 | final JavaScriptContextHolder jsContext) {
81 | final List specs = new ArrayList<>();
82 |
83 | // Here we provide a new JSIModuleSpec that will be responsible of providing the
84 | // custom Fabric Components.
85 | specs.add(
86 | new JSIModuleSpec() {
87 | @Override
88 | public JSIModuleType getJSIModuleType() {
89 | return JSIModuleType.UIManager;
90 | }
91 |
92 | @Override
93 | public JSIModuleProvider getJSIModuleProvider() {
94 | final ComponentFactory componentFactory = new ComponentFactory();
95 | CoreComponentsRegistry.register(componentFactory);
96 |
97 | // Here we register a Components Registry.
98 | // The one that is generated with the template contains no components
99 | // and just provides you the one from React Native core.
100 | MainComponentsRegistry.register(componentFactory);
101 |
102 | final ReactInstanceManager reactInstanceManager = getReactInstanceManager();
103 |
104 | ViewManagerRegistry viewManagerRegistry =
105 | new ViewManagerRegistry(
106 | reactInstanceManager.getOrCreateViewManagers(reactApplicationContext));
107 |
108 | return new FabricJSIModuleProvider(
109 | reactApplicationContext,
110 | componentFactory,
111 | new EmptyReactNativeConfig(),
112 | viewManagerRegistry);
113 | }
114 | });
115 | return specs;
116 | }
117 | };
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/com/example/reactnativemlkitocr/newarchitecture/components/MainComponentsRegistry.java:
--------------------------------------------------------------------------------
1 | package com.example.reactnativemlkitocr.newarchitecture.components;
2 |
3 | import com.facebook.jni.HybridData;
4 | import com.facebook.proguard.annotations.DoNotStrip;
5 | import com.facebook.react.fabric.ComponentFactory;
6 | import com.facebook.soloader.SoLoader;
7 |
8 | /**
9 | * Class responsible to load the custom Fabric Components. This class has native methods and needs a
10 | * corresponding C++ implementation/header file to work correctly (already placed inside the jni/
11 | * folder for you).
12 | *
13 | *
Please note that this class is used ONLY if you opt-in for the New Architecture (see the
14 | * `newArchEnabled` property). Is ignored otherwise.
15 | */
16 | @DoNotStrip
17 | public class MainComponentsRegistry {
18 | static {
19 | SoLoader.loadLibrary("fabricjni");
20 | }
21 |
22 | @DoNotStrip private final HybridData mHybridData;
23 |
24 | @DoNotStrip
25 | private native HybridData initHybrid(ComponentFactory componentFactory);
26 |
27 | @DoNotStrip
28 | private MainComponentsRegistry(ComponentFactory componentFactory) {
29 | mHybridData = initHybrid(componentFactory);
30 | }
31 |
32 | @DoNotStrip
33 | public static MainComponentsRegistry register(ComponentFactory componentFactory) {
34 | return new MainComponentsRegistry(componentFactory);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/com/example/reactnativemlkitocr/newarchitecture/modules/MainApplicationTurboModuleManagerDelegate.java:
--------------------------------------------------------------------------------
1 | package com.example.reactnativemlkitocr.newarchitecture.modules;
2 |
3 | import com.facebook.jni.HybridData;
4 | import com.facebook.react.ReactPackage;
5 | import com.facebook.react.ReactPackageTurboModuleManagerDelegate;
6 | import com.facebook.react.bridge.ReactApplicationContext;
7 | import com.facebook.soloader.SoLoader;
8 | import java.util.List;
9 |
10 | /**
11 | * Class responsible to load the TurboModules. This class has native methods and needs a
12 | * corresponding C++ implementation/header file to work correctly (already placed inside the jni/
13 | * folder for you).
14 | *
15 | *