? = FaceSDK.faceDetection(bitmap, param)
81 | if (!faceBoxes.isNullOrEmpty()) {
82 | for (face in faceBoxes!!) {
83 | val faceImage = Utils.cropFace(bitmap, face)
84 | val templates = FaceSDK.templateExtraction(bitmap, face)
85 |
86 | val byteArrayOutputStream = ByteArrayOutputStream()
87 | faceImage.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream)
88 | val faceJpg: ByteArray = byteArrayOutputStream.toByteArray()
89 |
90 | val e: WritableMap = Arguments.createMap()
91 | e.putString("x1", face.x1.toString())
92 | e.putString("y1", face.y1.toString())
93 | e.putString("x2", face.x2.toString())
94 | e.putString("y2", face.y2.toString())
95 | e.putString("liveness", face.liveness.toString())
96 | e.putString("yaw", face.yaw.toString())
97 | e.putString("roll", face.roll.toString())
98 | e.putString("pitch", face.pitch.toString())
99 | e.putString("templates", Utils.byteArrayToBase64(templates))
100 | e.putString("faceJpg", Utils.byteArrayToBase64(faceJpg))
101 | e.putString("frameWidth", bitmap.width.toString())
102 | e.putString("frameHeight", bitmap.height.toString())
103 | faceBoxesMap.pushMap(e)
104 | }
105 | }
106 | }
107 |
108 | promise.resolve(faceBoxesMap)
109 | }
110 |
111 | @ReactMethod
112 | fun similarityCalculation(templates1: String, templates2: String, promise: Promise) {
113 | val similarity = FaceSDK.similarityCalculation(Utils.base64ToByteArray(templates1), Utils.base64ToByteArray(templates2))
114 | Log.e("KBY", "similarityCalculation" + similarity)
115 | promise.resolve(similarity)
116 | }
117 |
118 | @ReactMethod
119 | fun startCamera(promise: Promise) {
120 | Log.e("KBY", "start camera" + faceRecognitionSdkViewManager);
121 | faceRecognitionSdkViewManager?.startCamera()
122 | promise.resolve(0)
123 | }
124 |
125 | @ReactMethod
126 | fun stopCamera(promise: Promise) {
127 | Log.e("KBY", "stop camera");
128 | faceRecognitionSdkViewManager?.stopCamera()
129 | promise.resolve(0)
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/android/src/main/java/com/facerecognitionsdk/Utils.kt:
--------------------------------------------------------------------------------
1 | package com.facerecognitionsdk
2 |
3 | import android.content.Context
4 | import android.database.Cursor
5 | import android.graphics.Bitmap
6 | import android.graphics.BitmapFactory
7 | import android.graphics.Matrix
8 | import android.net.Uri
9 | import android.provider.MediaStore
10 | import android.util.Base64
11 | import android.util.Log
12 | import com.kbyai.facesdk.FaceBox
13 | import android.media.ExifInterface
14 | import java.io.IOException
15 | import java.io.InputStream
16 |
17 | object Utils {
18 |
19 | fun cropFace(src: Bitmap, faceBox: FaceBox): Bitmap {
20 | val centerX = (faceBox.x1 + faceBox.x2) / 2
21 | val centerY = (faceBox.y1 + faceBox.y2) / 2
22 | val cropWidth = ((faceBox.x2 - faceBox.x1) * 1.4f).toInt()
23 |
24 | var cropX1 = centerX - cropWidth / 2
25 | var cropY1 = centerY - cropWidth / 2
26 | var cropX2 = centerX + cropWidth / 2
27 | var cropY2 = centerY + cropWidth / 2
28 | if (cropX1 < 0) cropX1 = 0
29 | if (cropX2 >= src.width) cropX2 = src.width - 1
30 | if (cropY1 < 0) cropY1 = 0
31 | if (cropY2 >= src.height) cropY2 = src.height - 1
32 |
33 |
34 | val cropScaleWidth = 200
35 | val cropScaleHeight = 200
36 | val scaleWidth = cropScaleWidth.toFloat() / (cropX2 - cropX1 + 1)
37 | val scaleHeight = cropScaleHeight.toFloat() / (cropY2 - cropY1 + 1)
38 |
39 | val m = Matrix()
40 |
41 | m.setScale(1.0f, 1.0f)
42 | m.postScale(scaleWidth, scaleHeight)
43 | val cropped = Bitmap.createBitmap(src, cropX1, cropY1, (cropX2 - cropX1 + 1), (cropY2 - cropY1 + 1), m,
44 | true /* filter */)
45 | return cropped
46 | }
47 |
48 | fun getOrientation(context: Context, photoUri: Uri): Int {
49 | val cursor: Cursor? = context.contentResolver.query(photoUri,
50 | arrayOf(MediaStore.Images.ImageColumns.ORIENTATION), null, null, null)
51 |
52 | if (cursor?.count != 1) {
53 | return -1
54 | }
55 |
56 | cursor.moveToFirst()
57 | return cursor.getInt(0)
58 | }
59 |
60 | @Throws(IOException::class)
61 | fun getCorrectlyOrientedImage(context: Context, photoUri: Uri): Bitmap {
62 | var rotate = 0
63 | val inputStream: InputStream? = context.contentResolver.openInputStream(photoUri)
64 | inputStream?.let {
65 | val exif = ExifInterface(it)
66 | val orientation = exif.getAttributeInt(
67 | ExifInterface.TAG_ORIENTATION,
68 | ExifInterface.ORIENTATION_NORMAL
69 | )
70 | rotate = when (orientation) {
71 | ExifInterface.ORIENTATION_ROTATE_270 -> 270
72 | ExifInterface.ORIENTATION_ROTATE_180 -> 180
73 | ExifInterface.ORIENTATION_ROTATE_90 -> 90
74 | else -> 0
75 | }
76 | it.close()
77 | }
78 |
79 | var srcBitmap: Bitmap
80 | val isStream = context.contentResolver.openInputStream(photoUri)
81 | srcBitmap = BitmapFactory.decodeStream(isStream)
82 | isStream?.close()
83 |
84 | val matrix = Matrix()
85 | matrix.postRotate(rotate.toFloat())
86 | return Bitmap.createBitmap(
87 | srcBitmap,
88 | 0,
89 | 0,
90 | srcBitmap.width,
91 | srcBitmap.height,
92 | matrix,
93 | true
94 | )
95 | }
96 |
97 | fun byteArrayToBase64(byteArray: ByteArray): String {
98 | val base64ByteArray = Base64.encode(byteArray, Base64.DEFAULT)
99 | return String(base64ByteArray)
100 | }
101 |
102 | fun base64ToByteArray(base64String: String): ByteArray {
103 | return Base64.decode(base64String, Base64.DEFAULT)
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/android/src/main/res/layout/camera_layout.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | presets: ['module:metro-react-native-babel-preset'],
3 | };
4 |
--------------------------------------------------------------------------------
/example/.watchmanconfig:
--------------------------------------------------------------------------------
1 | {}
2 |
--------------------------------------------------------------------------------
/example/Gemfile:
--------------------------------------------------------------------------------
1 | source 'https://rubygems.org'
2 |
3 | # You may use http://rbenv.org/ or https://rvm.io/ to install and use this version
4 | ruby ">= 2.6.10"
5 |
6 | gem 'cocoapods', '~> 1.12'
7 |
--------------------------------------------------------------------------------
/example/README.md:
--------------------------------------------------------------------------------
1 | This is a new [**React Native**](https://reactnative.dev) project, bootstrapped using [`@react-native-community/cli`](https://github.com/react-native-community/cli).
2 |
3 | # Getting Started
4 |
5 | >**Note**: Make sure you have completed the [React Native - Environment Setup](https://reactnative.dev/docs/environment-setup) instructions till "Creating a new application" step, before proceeding.
6 |
7 | ## Step 1: Start the Metro Server
8 |
9 | First, you will need to start **Metro**, the JavaScript _bundler_ that ships _with_ React Native.
10 |
11 | To start Metro, run the following command from the _root_ of your React Native project:
12 |
13 | ```bash
14 | # using npm
15 | npm start
16 |
17 | # OR using Yarn
18 | yarn start
19 | ```
20 |
21 | ## Step 2: Start your Application
22 |
23 | Let Metro Bundler run in its _own_ terminal. Open a _new_ terminal from the _root_ of your React Native project. Run the following command to start your _Android_ or _iOS_ app:
24 |
25 | ### For Android
26 |
27 | ```bash
28 | # using npm
29 | npm run android
30 |
31 | # OR using Yarn
32 | yarn android
33 | ```
34 |
35 | ### For iOS
36 |
37 | ```bash
38 | # using npm
39 | npm run ios
40 |
41 | # OR using Yarn
42 | yarn ios
43 | ```
44 |
45 | If everything is set up _correctly_, you should see your new app running in your _Android Emulator_ or _iOS Simulator_ shortly provided you have set up your emulator/simulator correctly.
46 |
47 | This is one way to run your app — you can also run it directly from within Android Studio and Xcode respectively.
48 |
49 | ## Step 3: Modifying your App
50 |
51 | Now that you have successfully run the app, let's modify it.
52 |
53 | 1. Open `App.tsx` in your text editor of choice and edit some lines.
54 | 2. For **Android**: Press the R key twice or select **"Reload"** from the **Developer Menu** (Ctrl + M (on Window and Linux) or Cmd ⌘ + M (on macOS)) to see your changes!
55 |
56 | For **iOS**: Hit Cmd ⌘ + R in your iOS Simulator to reload the app and see your changes!
57 |
58 | ## Congratulations! :tada:
59 |
60 | You've successfully run and modified your React Native App. :partying_face:
61 |
62 | ### Now what?
63 |
64 | - If you want to add this new React Native code to an existing application, check out the [Integration guide](https://reactnative.dev/docs/integration-with-existing-apps).
65 | - If you're curious to learn more about React Native, check out the [Introduction to React Native](https://reactnative.dev/docs/getting-started).
66 |
67 | # Troubleshooting
68 |
69 | If you can't get this to work, see the [Troubleshooting](https://reactnative.dev/docs/troubleshooting) page.
70 |
71 | # Learn More
72 |
73 | To learn more about React Native, take a look at the following resources:
74 |
75 | - [React Native Website](https://reactnative.dev) - learn more about React Native.
76 | - [Getting Started](https://reactnative.dev/docs/environment-setup) - an **overview** of React Native and how setup your environment.
77 | - [Learn the Basics](https://reactnative.dev/docs/getting-started) - a **guided tour** of the React Native **basics**.
78 | - [Blog](https://reactnative.dev/blog) - read the latest official React Native **Blog** posts.
79 | - [`@facebook/react-native`](https://github.com/facebook/react-native) - the Open Source; GitHub **repository** for React Native.
80 |
--------------------------------------------------------------------------------
/example/android/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: "com.android.application"
2 | apply plugin: "com.facebook.react"
3 |
4 | /**
5 | * This is the configuration block to customize your React Native Android app.
6 | * By default you don't need to apply any configuration, just uncomment the lines you need.
7 | */
8 | react {
9 | /* Folders */
10 | // The root of your project, i.e. where "package.json" lives. Default is '..'
11 | // root = file("../")
12 | // The folder where the react-native NPM package is. Default is ../node_modules/react-native
13 | // reactNativeDir = file("../node_modules/react-native")
14 | // The folder where the react-native Codegen package is. Default is ../node_modules/@react-native/codegen
15 | // codegenDir = file("../node_modules/@react-native/codegen")
16 | // The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js
17 | // cliFile = file("../node_modules/react-native/cli.js")
18 |
19 | /* Variants */
20 | // The list of variants to that are debuggable. For those we're going to
21 | // skip the bundling of the JS bundle and the assets. By default is just 'debug'.
22 | // If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
23 | // debuggableVariants = ["liteDebug", "prodDebug"]
24 |
25 | /* Bundling */
26 | // A list containing the node command and its flags. Default is just 'node'.
27 | // nodeExecutableAndArgs = ["node"]
28 | //
29 | // The command to run when bundling. By default is 'bundle'
30 | // bundleCommand = "ram-bundle"
31 | //
32 | // The path to the CLI configuration file. Default is empty.
33 | // bundleConfig = file(../rn-cli.config.js)
34 | //
35 | // The name of the generated asset file containing your JS bundle
36 | // bundleAssetName = "MyApplication.android.bundle"
37 | //
38 | // The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
39 | // entryFile = file("../js/MyApplication.android.js")
40 | //
41 | // A list of extra flags to pass to the 'bundle' commands.
42 | // See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
43 | // extraPackagerArgs = []
44 |
45 | /* Hermes Commands */
46 | // The hermes compiler command to run. By default it is 'hermesc'
47 | // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
48 | //
49 | // The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
50 | // hermesFlags = ["-O", "-output-source-map"]
51 | }
52 |
53 | /**
54 | * Set this to true to Run Proguard on Release builds to minify the Java bytecode.
55 | */
56 | def enableProguardInReleaseBuilds = false
57 |
58 | /**
59 | * The preferred build flavor of JavaScriptCore (JSC)
60 | *
61 | * For example, to use the international variant, you can use:
62 | * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
63 | *
64 | * The international variant includes ICU i18n library and necessary data
65 | * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
66 | * give correct results when using with locales other than en-US. Note that
67 | * this variant is about 6MiB larger per architecture than default.
68 | */
69 | def jscFlavor = 'org.webkit:android-jsc:+'
70 |
71 | android {
72 | ndkVersion rootProject.ext.ndkVersion
73 |
74 | compileSdkVersion rootProject.ext.compileSdkVersion
75 |
76 | namespace "com.facerecognitionsdkexample"
77 | defaultConfig {
78 | applicationId "com.facerecognitionsdkexample"
79 | minSdkVersion rootProject.ext.minSdkVersion
80 | targetSdkVersion rootProject.ext.targetSdkVersion
81 | versionCode 1
82 | versionName "1.0"
83 | }
84 | signingConfigs {
85 | debug {
86 | storeFile file('debug.keystore')
87 | storePassword 'android'
88 | keyAlias 'androiddebugkey'
89 | keyPassword 'android'
90 | }
91 | }
92 | buildTypes {
93 | debug {
94 | signingConfig signingConfigs.debug
95 | }
96 | release {
97 | // Caution! In production, you need to generate your own keystore file.
98 | // see https://reactnative.dev/docs/signed-apk-android.
99 | signingConfig signingConfigs.debug
100 | minifyEnabled enableProguardInReleaseBuilds
101 | proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
102 | }
103 | }
104 | }
105 |
106 | dependencies {
107 | // The version of react-native is set by the React Native Gradle Plugin
108 | implementation("com.facebook.react:react-android")
109 | // implementation project(path: ':libfacesdk')
110 |
111 | debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}")
112 | debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
113 | exclude group:'com.squareup.okhttp3', module:'okhttp'
114 | }
115 |
116 | debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}")
117 | if (hermesEnabled.toBoolean()) {
118 | implementation("com.facebook.react:hermes-android")
119 | } else {
120 | implementation jscFlavor
121 | }
122 | }
123 |
124 | apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
125 |
--------------------------------------------------------------------------------
/example/android/app/debug.keystore:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kby-ai/FaceRecognition-React-Native/b4dd71b10a1528de1bec4c7b781ca6f8f3d1b43c/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 |
--------------------------------------------------------------------------------
/example/android/app/src/debug/java/com/facerecognitionsdkexample/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.facerecognitionsdkexample;
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.sharedpreferences.SharedPreferencesFlipperPlugin;
21 | import com.facebook.react.ReactInstanceEventListener;
22 | import com.facebook.react.ReactInstanceManager;
23 | import com.facebook.react.bridge.ReactContext;
24 | import com.facebook.react.modules.network.NetworkingModule;
25 | import okhttp3.OkHttpClient;
26 |
27 | /**
28 | * Class responsible of loading Flipper inside your React Native application. This is the debug
29 | * flavor of it. Here you can add your own plugins and customize the Flipper setup.
30 | */
31 | public class ReactNativeFlipper {
32 | public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
33 | if (FlipperUtils.shouldEnableFlipper(context)) {
34 | final FlipperClient client = AndroidFlipperClient.getInstance(context);
35 |
36 | client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults()));
37 | client.addPlugin(new DatabasesFlipperPlugin(context));
38 | client.addPlugin(new SharedPreferencesFlipperPlugin(context));
39 | client.addPlugin(CrashReporterPlugin.getInstance());
40 |
41 | NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
42 | NetworkingModule.setCustomClientBuilder(
43 | new NetworkingModule.CustomClientBuilder() {
44 | @Override
45 | public void apply(OkHttpClient.Builder builder) {
46 | builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
47 | }
48 | });
49 | client.addPlugin(networkFlipperPlugin);
50 | client.start();
51 |
52 | // Fresco Plugin needs to ensure that ImagePipelineFactory is initialized
53 | // Hence we run if after all native modules have been initialized
54 | ReactContext reactContext = reactInstanceManager.getCurrentReactContext();
55 | if (reactContext == null) {
56 | reactInstanceManager.addReactInstanceEventListener(
57 | new ReactInstanceEventListener() {
58 | @Override
59 | public void onReactContextInitialized(ReactContext reactContext) {
60 | reactInstanceManager.removeReactInstanceEventListener(this);
61 | reactContext.runOnNativeModulesQueueThread(
62 | new Runnable() {
63 | @Override
64 | public void run() {
65 | client.addPlugin(new FrescoFlipperPlugin());
66 | }
67 | });
68 | }
69 | });
70 | } else {
71 | client.addPlugin(new FrescoFlipperPlugin());
72 | }
73 | }
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/example/android/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
14 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/com/facerecognitionsdkexample/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.facerecognitionsdkexample;
2 |
3 | import com.facebook.react.ReactActivity;
4 | import com.facebook.react.ReactActivityDelegate;
5 | import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
6 | import com.facebook.react.defaults.DefaultReactActivityDelegate;
7 |
8 | public class MainActivity extends ReactActivity {
9 |
10 | /**
11 | * Returns the name of the main component registered from JavaScript. This is used to schedule
12 | * rendering of the component.
13 | */
14 | @Override
15 | protected String getMainComponentName() {
16 | return "FaceRecognitionSdkExample";
17 | }
18 |
19 | /**
20 | * Returns the instance of the {@link ReactActivityDelegate}. Here we use a util class {@link
21 | * DefaultReactActivityDelegate} which allows you to easily enable Fabric and Concurrent React
22 | * (aka React 18) with two boolean flags.
23 | */
24 | @Override
25 | protected ReactActivityDelegate createReactActivityDelegate() {
26 | return new DefaultReactActivityDelegate(
27 | this,
28 | getMainComponentName(),
29 | // If you opted-in for the New Architecture, we enable the Fabric Renderer.
30 | DefaultNewArchitectureEntryPoint.getFabricEnabled());
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/example/android/app/src/main/java/com/facerecognitionsdkexample/MainApplication.java:
--------------------------------------------------------------------------------
1 | package com.facerecognitionsdkexample;
2 |
3 | import android.app.Application;
4 | import com.facebook.react.PackageList;
5 | import com.facebook.react.ReactApplication;
6 | import com.facebook.react.ReactNativeHost;
7 | import com.facebook.react.ReactPackage;
8 | import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint;
9 | import com.facebook.react.defaults.DefaultReactNativeHost;
10 | import com.facebook.soloader.SoLoader;
11 | import java.util.List;
12 |
13 | public class MainApplication extends Application implements ReactApplication {
14 |
15 | private final ReactNativeHost mReactNativeHost =
16 | new DefaultReactNativeHost(this) {
17 | @Override
18 | public boolean getUseDeveloperSupport() {
19 | return BuildConfig.DEBUG;
20 | }
21 |
22 | @Override
23 | protected List getPackages() {
24 | @SuppressWarnings("UnnecessaryLocalVariable")
25 | List packages = new PackageList(this).getPackages();
26 | // Packages that cannot be autolinked yet can be added manually here, for example:
27 | // packages.add(new MyReactNativePackage());
28 | return packages;
29 | }
30 |
31 | @Override
32 | protected String getJSMainModuleName() {
33 | return "index";
34 | }
35 |
36 | @Override
37 | protected boolean isNewArchEnabled() {
38 | return BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
39 | }
40 |
41 | @Override
42 | protected Boolean isHermesEnabled() {
43 | return BuildConfig.IS_HERMES_ENABLED;
44 | }
45 | };
46 |
47 | @Override
48 | public ReactNativeHost getReactNativeHost() {
49 | return mReactNativeHost;
50 | }
51 |
52 | @Override
53 | public void onCreate() {
54 | super.onCreate();
55 | SoLoader.init(this, /* native exopackage */ false);
56 | if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
57 | // If you opted-in for the New Architecture, we load the native entry point for this app.
58 | DefaultNewArchitectureEntryPoint.load();
59 | }
60 | ReactNativeFlipper.initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/example/android/app/src/main/res/drawable/rn_edit_text_material.xml:
--------------------------------------------------------------------------------
1 |
2 |
16 |
21 |
22 |
23 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kby-ai/FaceRecognition-React-Native/b4dd71b10a1528de1bec4c7b781ca6f8f3d1b43c/example/android/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kby-ai/FaceRecognition-React-Native/b4dd71b10a1528de1bec4c7b781ca6f8f3d1b43c/example/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kby-ai/FaceRecognition-React-Native/b4dd71b10a1528de1bec4c7b781ca6f8f3d1b43c/example/android/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kby-ai/FaceRecognition-React-Native/b4dd71b10a1528de1bec4c7b781ca6f8f3d1b43c/example/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kby-ai/FaceRecognition-React-Native/b4dd71b10a1528de1bec4c7b781ca6f8f3d1b43c/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kby-ai/FaceRecognition-React-Native/b4dd71b10a1528de1bec4c7b781ca6f8f3d1b43c/example/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kby-ai/FaceRecognition-React-Native/b4dd71b10a1528de1bec4c7b781ca6f8f3d1b43c/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kby-ai/FaceRecognition-React-Native/b4dd71b10a1528de1bec4c7b781ca6f8f3d1b43c/example/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kby-ai/FaceRecognition-React-Native/b4dd71b10a1528de1bec4c7b781ca6f8f3d1b43c/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kby-ai/FaceRecognition-React-Native/b4dd71b10a1528de1bec4c7b781ca6f8f3d1b43c/example/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/example/android/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | FaceRecognitionSdkExample
3 |
4 |
--------------------------------------------------------------------------------
/example/android/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/example/android/app/src/release/java/com/facerecognitionsdkexample/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.facerecognitionsdkexample;
8 |
9 | import android.content.Context;
10 | import com.facebook.react.ReactInstanceManager;
11 |
12 | /**
13 | * Class responsible of loading Flipper inside your React Native application. This is the release
14 | * flavor of it so it's empty as we don't want to load Flipper.
15 | */
16 | public class ReactNativeFlipper {
17 | public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
18 | // Do nothing as we don't want to initialize Flipper on Release.
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/example/android/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | ext {
5 | buildToolsVersion = "33.0.0"
6 | minSdkVersion = 23
7 | compileSdkVersion = 33
8 | targetSdkVersion = 33
9 |
10 | // We use NDK 23 which has both M1 support and is the side-by-side NDK version from AGP.
11 | ndkVersion = "21.4.7075529"
12 | }
13 | repositories {
14 | google()
15 | mavenCentral()
16 | }
17 | dependencies {
18 | classpath("com.android.tools.build:gradle")
19 | classpath("com.facebook.react:react-native-gradle-plugin")
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/example/android/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 |
3 | # IDE (e.g. Android Studio) users:
4 | # Gradle settings configured through the IDE *will override*
5 | # any settings specified in this file.
6 |
7 | # For more details on how to configure your build environment visit
8 | # http://www.gradle.org/docs/current/userguide/build_environment.html
9 |
10 | # Specifies the JVM arguments used for the daemon process.
11 | # The setting is particularly useful for tweaking memory settings.
12 | # Default value: -Xmx512m -XX:MaxMetaspaceSize=256m
13 | org.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m
14 |
15 | # When configured, Gradle will run in incubating parallel mode.
16 | # This option should only be used with decoupled projects. More details, visit
17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
18 | # org.gradle.parallel=true
19 |
20 | # AndroidX package structure to make it clearer which packages are bundled with the
21 | # Android operating system, and which are packaged with your app's APK
22 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
23 | android.useAndroidX=true
24 | # Automatically convert third-party libraries to use AndroidX
25 | android.enableJetifier=true
26 |
27 | # Version of flipper SDK to use with React Native
28 | FLIPPER_VERSION=0.182.0
29 |
30 | # Use this property to specify which architecture you want to build.
31 | # You can also override it from the CLI using
32 | # ./gradlew -PreactNativeArchitectures=x86_64
33 | reactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64
34 |
35 | # Use this property to enable support to the new architecture.
36 | # This will allow you to use TurboModules and the Fabric render in
37 | # your application. You should enable this flag either if you want
38 | # to write custom TurboModules/Fabric components OR use libraries that
39 | # are providing them.
40 | newArchEnabled=false
41 |
42 | # Use this property to enable or disable the Hermes JS engine.
43 | # If set to false, you will be using JSC instead.
44 | hermesEnabled=true
45 |
--------------------------------------------------------------------------------
/example/android/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kby-ai/FaceRecognition-React-Native/b4dd71b10a1528de1bec4c7b781ca6f8f3d1b43c/example/android/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/example/android/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.1-all.zip
4 | networkTimeout=10000
5 | zipStoreBase=GRADLE_USER_HOME
6 | zipStorePath=wrapper/dists
7 |
--------------------------------------------------------------------------------
/example/android/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 |
19 | ##############################################################################
20 | #
21 | # Gradle start up script for POSIX generated by Gradle.
22 | #
23 | # Important for running:
24 | #
25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
26 | # noncompliant, but you have some other compliant shell such as ksh or
27 | # bash, then to run this script, type that shell name before the whole
28 | # command line, like:
29 | #
30 | # ksh Gradle
31 | #
32 | # Busybox and similar reduced shells will NOT work, because this script
33 | # requires all of these POSIX shell features:
34 | # * functions;
35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
37 | # * compound commands having a testable exit status, especially «case»;
38 | # * various built-in commands including «command», «set», and «ulimit».
39 | #
40 | # Important for patching:
41 | #
42 | # (2) This script targets any POSIX shell, so it avoids extensions provided
43 | # by Bash, Ksh, etc; in particular arrays are avoided.
44 | #
45 | # The "traditional" practice of packing multiple parameters into a
46 | # space-separated string is a well documented source of bugs and security
47 | # problems, so this is (mostly) avoided, by progressively accumulating
48 | # options in "$@", and eventually passing that to Java.
49 | #
50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
52 | # see the in-line comments for details.
53 | #
54 | # There are tweaks for specific operating systems such as AIX, CygWin,
55 | # Darwin, MinGW, and NonStop.
56 | #
57 | # (3) This script is generated from the Groovy template
58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
59 | # within the Gradle project.
60 | #
61 | # You can find Gradle at https://github.com/gradle/gradle/.
62 | #
63 | ##############################################################################
64 |
65 | # Attempt to set APP_HOME
66 |
67 | # Resolve links: $0 may be a link
68 | app_path=$0
69 |
70 | # Need this for daisy-chained symlinks.
71 | while
72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
73 | [ -h "$app_path" ]
74 | do
75 | ls=$( ls -ld "$app_path" )
76 | link=${ls#*' -> '}
77 | case $link in #(
78 | /*) app_path=$link ;; #(
79 | *) app_path=$APP_HOME$link ;;
80 | esac
81 | done
82 |
83 | # This is normally unused
84 | # shellcheck disable=SC2034
85 | APP_BASE_NAME=${0##*/}
86 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit
87 |
88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
90 |
91 | # Use the maximum available, or set MAX_FD != -1 to use that value.
92 | MAX_FD=maximum
93 |
94 | warn () {
95 | echo "$*"
96 | } >&2
97 |
98 | die () {
99 | echo
100 | echo "$*"
101 | echo
102 | exit 1
103 | } >&2
104 |
105 | # OS specific support (must be 'true' or 'false').
106 | cygwin=false
107 | msys=false
108 | darwin=false
109 | nonstop=false
110 | case "$( uname )" in #(
111 | CYGWIN* ) cygwin=true ;; #(
112 | Darwin* ) darwin=true ;; #(
113 | MSYS* | MINGW* ) msys=true ;; #(
114 | NONSTOP* ) nonstop=true ;;
115 | esac
116 |
117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
118 |
119 |
120 | # Determine the Java command to use to start the JVM.
121 | if [ -n "$JAVA_HOME" ] ; then
122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
123 | # IBM's JDK on AIX uses strange locations for the executables
124 | JAVACMD=$JAVA_HOME/jre/sh/java
125 | else
126 | JAVACMD=$JAVA_HOME/bin/java
127 | fi
128 | if [ ! -x "$JAVACMD" ] ; then
129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
130 |
131 | Please set the JAVA_HOME variable in your environment to match the
132 | location of your Java installation."
133 | fi
134 | else
135 | JAVACMD=java
136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
137 |
138 | Please set the JAVA_HOME variable in your environment to match the
139 | location of your Java installation."
140 | fi
141 |
142 | # Increase the maximum file descriptors if we can.
143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
144 | case $MAX_FD in #(
145 | max*)
146 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
147 | # shellcheck disable=SC3045
148 | MAX_FD=$( ulimit -H -n ) ||
149 | warn "Could not query maximum file descriptor limit"
150 | esac
151 | case $MAX_FD in #(
152 | '' | soft) :;; #(
153 | *)
154 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
155 | # shellcheck disable=SC3045
156 | ulimit -n "$MAX_FD" ||
157 | warn "Could not set maximum file descriptor limit to $MAX_FD"
158 | esac
159 | fi
160 |
161 | # Collect all arguments for the java command, stacking in reverse order:
162 | # * args from the command line
163 | # * the main class name
164 | # * -classpath
165 | # * -D...appname settings
166 | # * --module-path (only if needed)
167 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
168 |
169 | # For Cygwin or MSYS, switch paths to Windows format before running java
170 | if "$cygwin" || "$msys" ; then
171 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
172 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
173 |
174 | JAVACMD=$( cygpath --unix "$JAVACMD" )
175 |
176 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
177 | for arg do
178 | if
179 | case $arg in #(
180 | -*) false ;; # don't mess with options #(
181 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
182 | [ -e "$t" ] ;; #(
183 | *) false ;;
184 | esac
185 | then
186 | arg=$( cygpath --path --ignore --mixed "$arg" )
187 | fi
188 | # Roll the args list around exactly as many times as the number of
189 | # args, so each arg winds up back in the position where it started, but
190 | # possibly modified.
191 | #
192 | # NB: a `for` loop captures its iteration list before it begins, so
193 | # changing the positional parameters here affects neither the number of
194 | # iterations, nor the values presented in `arg`.
195 | shift # remove old arg
196 | set -- "$@" "$arg" # push replacement arg
197 | done
198 | fi
199 |
200 | # Collect all arguments for the java command;
201 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of
202 | # shell script including quotes and variable substitutions, so put them in
203 | # double quotes to make sure that they get re-expanded; and
204 | # * put everything else in single quotes, so that it's not re-expanded.
205 |
206 | set -- \
207 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
208 | -classpath "$CLASSPATH" \
209 | org.gradle.wrapper.GradleWrapperMain \
210 | "$@"
211 |
212 | # Stop when "xargs" is not available.
213 | if ! command -v xargs >/dev/null 2>&1
214 | then
215 | die "xargs is not available"
216 | fi
217 |
218 | # Use "xargs" to parse quoted args.
219 | #
220 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
221 | #
222 | # In Bash we could simply go:
223 | #
224 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
225 | # set -- "${ARGS[@]}" "$@"
226 | #
227 | # but POSIX shell has neither arrays nor command substitution, so instead we
228 | # post-process each arg (as a line of input to sed) to backslash-escape any
229 | # character that might be a shell metacharacter, then use eval to reverse
230 | # that process (while maintaining the separation between arguments), and wrap
231 | # the whole thing up as a single "set" statement.
232 | #
233 | # This will of course break if any of these variables contains a newline or
234 | # an unmatched quote.
235 | #
236 |
237 | eval "set -- $(
238 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
239 | xargs -n1 |
240 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
241 | tr '\n' ' '
242 | )" '"$@"'
243 |
244 | exec "$JAVACMD" "$@"
245 |
--------------------------------------------------------------------------------
/example/android/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 |
17 | @if "%DEBUG%"=="" @echo off
18 | @rem ##########################################################################
19 | @rem
20 | @rem Gradle startup script for Windows
21 | @rem
22 | @rem ##########################################################################
23 |
24 | @rem Set local scope for the variables with windows NT shell
25 | if "%OS%"=="Windows_NT" setlocal
26 |
27 | set DIRNAME=%~dp0
28 | if "%DIRNAME%"=="" set DIRNAME=.
29 | @rem This is normally unused
30 | set APP_BASE_NAME=%~n0
31 | set APP_HOME=%DIRNAME%
32 |
33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
35 |
36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
38 |
39 | @rem Find java.exe
40 | if defined JAVA_HOME goto findJavaFromJavaHome
41 |
42 | set JAVA_EXE=java.exe
43 | %JAVA_EXE% -version >NUL 2>&1
44 | if %ERRORLEVEL% equ 0 goto execute
45 |
46 | echo.
47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
48 | echo.
49 | echo Please set the JAVA_HOME variable in your environment to match the
50 | echo location of your Java installation.
51 |
52 | goto fail
53 |
54 | :findJavaFromJavaHome
55 | set JAVA_HOME=%JAVA_HOME:"=%
56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
57 |
58 | if exist "%JAVA_EXE%" goto execute
59 |
60 | echo.
61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
62 | echo.
63 | echo Please set the JAVA_HOME variable in your environment to match the
64 | echo location of your Java installation.
65 |
66 | goto fail
67 |
68 | :execute
69 | @rem Setup the command line
70 |
71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
72 |
73 |
74 | @rem Execute Gradle
75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
76 |
77 | :end
78 | @rem End local scope for the variables with windows NT shell
79 | if %ERRORLEVEL% equ 0 goto mainEnd
80 |
81 | :fail
82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
83 | rem the _cmd.exe /c_ return code!
84 | set EXIT_CODE=%ERRORLEVEL%
85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
87 | exit /b %EXIT_CODE%
88 |
89 | :mainEnd
90 | if "%OS%"=="Windows_NT" endlocal
91 |
92 | :omega
93 |
--------------------------------------------------------------------------------
/example/android/libfacesdk/build.gradle:
--------------------------------------------------------------------------------
1 | configurations.maybeCreate("default")
2 | artifacts.add("default", file('facesdk.aar'))
--------------------------------------------------------------------------------
/example/android/libfacesdk/facesdk.aar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/kby-ai/FaceRecognition-React-Native/b4dd71b10a1528de1bec4c7b781ca6f8f3d1b43c/example/android/libfacesdk/facesdk.aar
--------------------------------------------------------------------------------
/example/android/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'FaceRecognitionSdkExample'
2 | apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
3 | include ':app'
4 | include ':libfacesdk'
5 | includeBuild('../node_modules/@react-native/gradle-plugin')
6 |
--------------------------------------------------------------------------------
/example/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "FaceRecognitionSdkExample",
3 | "displayName": "FaceRecognitionSdkExample"
4 | }
5 |
--------------------------------------------------------------------------------
/example/babel.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const pak = require('../package.json');
3 |
4 | module.exports = {
5 | presets: ['module:metro-react-native-babel-preset'],
6 | plugins: [
7 | [
8 | 'module-resolver',
9 | {
10 | extensions: ['.tsx', '.ts', '.js', '.json'],
11 | alias: {
12 | [pak.name]: path.join(__dirname, '..', pak.source),
13 | },
14 | },
15 | ],
16 | ],
17 | };
18 |
--------------------------------------------------------------------------------
/example/index.js:
--------------------------------------------------------------------------------
1 | import { AppRegistry } from 'react-native';
2 | import App from './src/App';
3 | import { name as appName } from './app.json';
4 |
5 | AppRegistry.registerComponent(appName, () => App);
6 |
--------------------------------------------------------------------------------
/example/ios/.xcode.env:
--------------------------------------------------------------------------------
1 | # This `.xcode.env` file is versioned and is used to source the environment
2 | # used when running script phases inside Xcode.
3 | # To customize your local environment, you can create an `.xcode.env.local`
4 | # file that is not versioned.
5 |
6 | # NODE_BINARY variable contains the PATH to the node executable.
7 | #
8 | # Customize the NODE_BINARY variable here.
9 | # For example, to use nvm with brew, add the following line
10 | # . "$(brew --prefix nvm)/nvm.sh" --no-use
11 | export NODE_BINARY=$(command -v node)
12 |
--------------------------------------------------------------------------------
/example/ios/FaceRecognitionSdkExample-Bridging-Header.h:
--------------------------------------------------------------------------------
1 | //
2 | // Use this file to import your target's public headers that you would like to expose to Swift.
3 | //
4 |
--------------------------------------------------------------------------------
/example/ios/FaceRecognitionSdkExample.xcodeproj/xcshareddata/xcschemes/FaceRecognitionSdkExample.xcscheme:
--------------------------------------------------------------------------------
1 |
2 |
5 |
8 |
9 |
15 |
21 |
22 |
23 |
24 |
25 |
30 |
31 |
33 |
39 |
40 |
41 |
42 |
43 |
53 |
55 |
61 |
62 |
63 |
64 |
70 |
72 |
78 |
79 |
80 |
81 |
83 |
84 |
87 |
88 |
89 |
--------------------------------------------------------------------------------
/example/ios/FaceRecognitionSdkExample/AppDelegate.h:
--------------------------------------------------------------------------------
1 | #import
2 | #import
3 |
4 | @interface AppDelegate : RCTAppDelegate
5 |
6 | @end
7 |
--------------------------------------------------------------------------------
/example/ios/FaceRecognitionSdkExample/AppDelegate.mm:
--------------------------------------------------------------------------------
1 | #import "AppDelegate.h"
2 |
3 | #import
4 |
5 | @implementation AppDelegate
6 |
7 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
8 | {
9 | self.moduleName = @"FaceRecognitionSdkExample";
10 | // You can add your custom initial props in the dictionary below.
11 | // They will be passed down to the ViewController used by React Native.
12 | self.initialProps = @{};
13 |
14 | return [super application:application didFinishLaunchingWithOptions:launchOptions];
15 | }
16 |
17 | - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
18 | {
19 | #if DEBUG
20 | return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
21 | #else
22 | return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
23 | #endif
24 | }
25 |
26 | @end
27 |
--------------------------------------------------------------------------------
/example/ios/FaceRecognitionSdkExample/Images.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "scale" : "2x",
6 | "size" : "20x20"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "scale" : "3x",
11 | "size" : "20x20"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "scale" : "2x",
16 | "size" : "29x29"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "scale" : "3x",
21 | "size" : "29x29"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "scale" : "2x",
26 | "size" : "40x40"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "scale" : "3x",
31 | "size" : "40x40"
32 | },
33 | {
34 | "idiom" : "iphone",
35 | "scale" : "2x",
36 | "size" : "60x60"
37 | },
38 | {
39 | "idiom" : "iphone",
40 | "scale" : "3x",
41 | "size" : "60x60"
42 | },
43 | {
44 | "idiom" : "ios-marketing",
45 | "scale" : "1x",
46 | "size" : "1024x1024"
47 | }
48 | ],
49 | "info" : {
50 | "author" : "xcode",
51 | "version" : 1
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/example/ios/FaceRecognitionSdkExample/Images.xcassets/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "info" : {
3 | "version" : 1,
4 | "author" : "xcode"
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/example/ios/FaceRecognitionSdkExample/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleDisplayName
8 | FaceRecognitionSdkExample
9 | CFBundleExecutable
10 | $(EXECUTABLE_NAME)
11 | CFBundleIdentifier
12 | $(PRODUCT_BUNDLE_IDENTIFIER)
13 | CFBundleInfoDictionaryVersion
14 | 6.0
15 | CFBundleName
16 | $(PRODUCT_NAME)
17 | CFBundlePackageType
18 | APPL
19 | CFBundleShortVersionString
20 | $(MARKETING_VERSION)
21 | CFBundleSignature
22 | ????
23 | CFBundleVersion
24 | $(CURRENT_PROJECT_VERSION)
25 | LSRequiresIPhoneOS
26 |
27 | NSAppTransportSecurity
28 |
29 | NSExceptionDomains
30 |
31 | localhost
32 |
33 | NSExceptionAllowsInsecureHTTPLoads
34 |
35 |
36 |
37 |
38 | NSLocationWhenInUseUsageDescription
39 |
40 | UILaunchStoryboardName
41 | LaunchScreen
42 | UIRequiredDeviceCapabilities
43 |
44 | armv7
45 |
46 | UISupportedInterfaceOrientations
47 |
48 | UIInterfaceOrientationPortrait
49 | UIInterfaceOrientationLandscapeLeft
50 | UIInterfaceOrientationLandscapeRight
51 |
52 | UIViewControllerBasedStatusBarAppearance
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/example/ios/FaceRecognitionSdkExample/LaunchScreen.storyboard:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
--------------------------------------------------------------------------------
/example/ios/FaceRecognitionSdkExample/main.m:
--------------------------------------------------------------------------------
1 | #import
2 |
3 | #import "AppDelegate.h"
4 |
5 | int main(int argc, char *argv[])
6 | {
7 | @autoreleasepool {
8 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/example/ios/FaceRecognitionSdkExampleTests/FaceRecognitionSdkExampleTests.m:
--------------------------------------------------------------------------------
1 | #import
2 | #import
3 |
4 | #import
5 | #import
6 |
7 | #define TIMEOUT_SECONDS 600
8 | #define TEXT_TO_LOOK_FOR @"Welcome to React"
9 |
10 | @interface FaceRecognitionSdkExampleTests : XCTestCase
11 |
12 | @end
13 |
14 | @implementation FaceRecognitionSdkExampleTests
15 |
16 | - (BOOL)findSubviewInView:(UIView *)view matching:(BOOL (^)(UIView *view))test
17 | {
18 | if (test(view)) {
19 | return YES;
20 | }
21 | for (UIView *subview in [view subviews]) {
22 | if ([self findSubviewInView:subview matching:test]) {
23 | return YES;
24 | }
25 | }
26 | return NO;
27 | }
28 |
29 | - (void)testRendersWelcomeScreen
30 | {
31 | UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController];
32 | NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS];
33 | BOOL foundElement = NO;
34 |
35 | __block NSString *redboxError = nil;
36 | #ifdef DEBUG
37 | RCTSetLogFunction(
38 | ^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) {
39 | if (level >= RCTLogLevelError) {
40 | redboxError = message;
41 | }
42 | });
43 | #endif
44 |
45 | while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) {
46 | [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
47 | [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
48 |
49 | foundElement = [self findSubviewInView:vc.view
50 | matching:^BOOL(UIView *view) {
51 | if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) {
52 | return YES;
53 | }
54 | return NO;
55 | }];
56 | }
57 |
58 | #ifdef DEBUG
59 | RCTSetLogFunction(RCTDefaultLogFunction);
60 | #endif
61 |
62 | XCTAssertNil(redboxError, @"RedBox error: %@", redboxError);
63 | XCTAssertTrue(foundElement, @"Couldn't find element with text '%@' in %d seconds", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS);
64 | }
65 |
66 | @end
67 |
--------------------------------------------------------------------------------
/example/ios/FaceRecognitionSdkExampleTests/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | en
7 | CFBundleExecutable
8 | $(EXECUTABLE_NAME)
9 | CFBundleIdentifier
10 | $(PRODUCT_BUNDLE_IDENTIFIER)
11 | CFBundleInfoDictionaryVersion
12 | 6.0
13 | CFBundleName
14 | $(PRODUCT_NAME)
15 | CFBundlePackageType
16 | BNDL
17 | CFBundleShortVersionString
18 | 1.0
19 | CFBundleSignature
20 | ????
21 | CFBundleVersion
22 | 1
23 |
24 |
25 |
--------------------------------------------------------------------------------
/example/ios/File.swift:
--------------------------------------------------------------------------------
1 | //
2 | // File.swift
3 | // FaceRecognitionSdkExample
4 | //
5 |
6 | import Foundation
7 |
--------------------------------------------------------------------------------
/example/ios/Podfile:
--------------------------------------------------------------------------------
1 | # Resolve react_native_pods.rb with node to allow for hoisting
2 | # require Pod::Executable.execute_command('node', ['-p',
3 | # 'require.resolve(
4 | # "react-native/scripts/react_native_pods.rb",
5 | # {paths: [process.argv[1]]},
6 | # )', __dir__]).strip
7 |
8 | def node_require(script)
9 | # Resolve script with node to allow for hoisting
10 | require Pod::Executable.execute_command('node', ['-p',
11 | "require.resolve(
12 | '#{script}',
13 | {paths: [process.argv[1]]},
14 | )", __dir__]).strip
15 | end
16 |
17 | node_require('react-native/scripts/react_native_pods.rb')
18 | node_require('react-native-permissions/scripts/setup.rb')
19 |
20 | platform :ios, min_ios_version_supported
21 | prepare_react_native_project!
22 |
23 | setup_permissions([
24 | 'Camera'
25 | ])
26 |
27 | # If you are using a `react-native-flipper` your iOS build will fail when `NO_FLIPPER=1` is set.
28 | # because `react-native-flipper` depends on (FlipperKit,...) that will be excluded
29 | #
30 | # To fix this you can also exclude `react-native-flipper` using a `react-native.config.js`
31 | # ```js
32 | # module.exports = {
33 | # dependencies: {
34 | # ...(process.env.NO_FLIPPER ? { 'react-native-flipper': { platforms: { ios: null } } } : {}),
35 | # ```
36 | flipper_config = ENV['NO_FLIPPER'] == "1" ? FlipperConfiguration.disabled : FlipperConfiguration.enabled
37 |
38 | linkage = ENV['USE_FRAMEWORKS']
39 | if linkage != nil
40 | Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green
41 | use_frameworks! :linkage => linkage.to_sym
42 | end
43 |
44 | target 'FaceRecognitionSdkExample' do
45 | config = use_native_modules!
46 |
47 | # Flags change depending on the env values.
48 | flags = get_default_flags()
49 |
50 | use_react_native!(
51 | :path => config[:reactNativePath],
52 | # Hermes is now enabled by default. Disable by setting this flag to false.
53 | :hermes_enabled => flags[:hermes_enabled],
54 | :fabric_enabled => flags[:fabric_enabled],
55 | # Enables Flipper.
56 | #
57 | # Note that if you have use_frameworks! enabled, Flipper will not work and
58 | # you should disable the next line.
59 | :flipper_configuration => flipper_config,
60 | # An absolute path to your application root.
61 | :app_path => "#{Pod::Config.instance.installation_root}/.."
62 | )
63 |
64 | target 'FaceRecognitionSdkExampleTests' do
65 | inherit! :complete
66 | # Pods for testing
67 | end
68 |
69 | post_install do |installer|
70 | # https://github.com/facebook/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202
71 | react_native_post_install(
72 | installer,
73 | config[:reactNativePath],
74 | :mac_catalyst_enabled => false
75 | )
76 | __apply_Xcode_12_5_M1_post_install_workaround(installer)
77 | end
78 | end
79 |
--------------------------------------------------------------------------------
/example/jest.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | preset: 'react-native',
3 | };
4 |
--------------------------------------------------------------------------------
/example/metro.config.js:
--------------------------------------------------------------------------------
1 | const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config');
2 | const path = require('path');
3 | const escape = require('escape-string-regexp');
4 | const exclusionList = require('metro-config/src/defaults/exclusionList');
5 | const pak = require('../package.json');
6 |
7 | const root = path.resolve(__dirname, '..');
8 | const modules = Object.keys({ ...pak.peerDependencies });
9 |
10 | /**
11 | * Metro configuration
12 | * https://facebook.github.io/metro/docs/configuration
13 | *
14 | * @type {import('metro-config').MetroConfig}
15 | */
16 | const config = {
17 | watchFolders: [root],
18 |
19 | // We need to make sure that only one version is loaded for peerDependencies
20 | // So we block them at the root, and alias them to the versions in example's node_modules
21 | resolver: {
22 | blacklistRE: exclusionList(
23 | modules.map(
24 | (m) =>
25 | new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`)
26 | )
27 | ),
28 |
29 | extraNodeModules: modules.reduce((acc, name) => {
30 | acc[name] = path.join(__dirname, 'node_modules', name);
31 | return acc;
32 | }, {}),
33 | },
34 |
35 | transformer: {
36 | getTransformOptions: async () => ({
37 | transform: {
38 | experimentalImportSupport: false,
39 | inlineRequires: true,
40 | },
41 | }),
42 | },
43 | };
44 |
45 | module.exports = mergeConfig(getDefaultConfig(__dirname), config);
46 |
--------------------------------------------------------------------------------
/example/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "FaceRecognitionSdkExample",
3 | "version": "0.0.1",
4 | "private": true,
5 | "scripts": {
6 | "android": "react-native run-android",
7 | "ios": "react-native run-ios",
8 | "start": "react-native start",
9 | "pods": "pod-install --quiet"
10 | },
11 | "dependencies": {
12 | "@react-navigation/native": "^6.1.7",
13 | "@react-navigation/native-stack": "^6.9.13",
14 | "react": "18.2.0",
15 | "react-native": "0.72.1",
16 | "react-native-image-picker": "^5.6.0",
17 | "react-native-modal": "^13.0.1",
18 | "react-native-paper": "^5.9.1",
19 | "react-native-picker-select": "^8.0.4",
20 | "react-native-safe-area-context": "^4.7.0",
21 | "react-native-screens": "^3.22.1",
22 | "react-native-settings-list": "^1.8.0",
23 | "react-native-sqlite-storage": "^6.0.1"
24 | },
25 | "devDependencies": {
26 | "@babel/core": "^7.20.0",
27 | "@babel/preset-env": "^7.20.0",
28 | "@babel/runtime": "^7.20.0",
29 | "@react-native/eslint-config": "^0.72.2",
30 | "@react-native/metro-config": "^0.72.7",
31 | "@types/metro-config": "^0.76.3",
32 | "babel-plugin-module-resolver": "^5.0.0",
33 | "metro-react-native-babel-preset": "0.76.5",
34 | "react-native-permissions": "^4.1.5"
35 | },
36 | "engines": {
37 | "node": ">=16"
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/example/react-native.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const pak = require('../package.json');
3 |
4 | module.exports = {
5 | dependencies: {
6 | [pak.name]: {
7 | root: path.join(__dirname, '..'),
8 | },
9 | },
10 | };
11 |
--------------------------------------------------------------------------------
/example/src/AboutPage.tsx:
--------------------------------------------------------------------------------
1 | // AboutPage.js
2 | import React from 'react';
3 | import { View, Text, StyleSheet, Image, TouchableOpacity } from 'react-native';
4 |
5 | const AboutPage = ({ navigation }) => {
6 | const goBackToHome = () => {
7 | navigation.goBack();
8 | };
9 |
10 | return (
11 |
12 |
13 |
14 |
16 |
19 |
20 |
21 | KBY-AI Technology
22 |
23 |
24 |
25 |
26 | We are a leading provider of SDKs for advanced biometric authentication technology, including face recognition, liveness detection, and ID card recognition.
27 |
28 |
29 | In addition to biometric authentication solutions, we provide software development services for computer vision and mobile applications.
30 |
31 |
32 | With our team's extensive knowledge and proficiency in these areas, we can deliver exceptional results to our clients.
33 |
34 |
35 | If you're interested in learning more about how we can help you, please don't hesitate to get in touch with us today.
36 |
37 | Please contact us:
38 |
39 |
40 | Email: contact@kby-ai.com
41 |
42 |
43 |
44 | Skype: live:.cid.66e2522354b1049b
45 |
46 |
47 |
48 | Telegram: kbyai
49 |
50 |
51 |
52 | WhatsApp: +19092802609
53 |
54 |
55 |
56 | Github: https://github.com/kby-ai
57 |
58 |
59 |
60 | );
61 | };
62 |
63 | const styles = StyleSheet.create({
64 | container: {
65 | flex: 1,
66 | backgroundColor: '#1C1B1F'
67 | },
68 | appBar: {
69 | height: 60,
70 | backgroundColor: '#1C1B1F',
71 | justifyContent: 'center',
72 | alignItems: 'center',
73 | },
74 | title: {
75 | marginLeft: 30,
76 | flex: 1,
77 | fontSize: 18,
78 | color: '#FFFFFF',
79 | },
80 | body: {
81 | flex: 1,
82 | margin: 16,
83 | },
84 | description: {
85 | marginBottom: 8,
86 | fontSize: 14,
87 | color: '#FFF',
88 | },
89 | contact: {
90 | marginBottom: 8,
91 | fontSize: 14,
92 | fontWeight: 'bold',
93 | color: '#FFF',
94 | },
95 | contactRow: {
96 | flexDirection: 'row',
97 | alignItems: 'center',
98 | marginBottom: 4,
99 | },
100 | icon: {
101 | width: 24,
102 | height: 24,
103 | marginRight: 4,
104 | tintColor: '#FFFFFF',
105 | },
106 | });
107 |
108 | export default AboutPage;
--------------------------------------------------------------------------------
/example/src/App.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 |
3 | import { StatusBar, StyleSheet, View } from 'react-native';
4 | import { NavigationContainer } from '@react-navigation/native';
5 | import { createNativeStackNavigator } from '@react-navigation/native-stack';
6 | import { FaceRecognitionSdkView } from 'face-recognition-sdk';
7 | import { IconButton } from 'react-native-paper';
8 | import AboutPage from './AboutPage';
9 | import MainPage from './MainPage';
10 | import FaceRecognitionPage from './FaceRecognitionPage';
11 | import SettingsPage from './SettingsPage';
12 | import ResultPage from './ResultPage';
13 |
14 | const Stack = createNativeStackNavigator();
15 |
16 | export default function App() {
17 | const backButton = navigation => (
18 | navigation.goBack()}
21 | />
22 | );
23 |
24 | return (
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 | );
35 | //
36 | //
37 | //
38 | // );
39 | }
40 |
41 |
--------------------------------------------------------------------------------
/example/src/FaceRecognitionPage.tsx:
--------------------------------------------------------------------------------
1 | // FaceRecognitionPage.js
2 | import React, { useEffect, useState, useRef } from 'react';
3 | import { View, Text, StyleSheet, TouchableOpacity, Image, } from 'react-native';
4 | import { FaceRecognitionSdkView, FaceSDKModule } from 'face-recognition-sdk';
5 | import { check, request, PERMISSIONS, RESULTS } from 'react-native-permissions'
6 | import { NativeEventEmitter } from 'react-native';
7 | import ResultPage from './ResultPage';
8 | import { AppState, BackHandler } from 'react-native';
9 | import { useIsFocused } from '@react-navigation/native';
10 |
11 | const cameraPermission = Platform.select({
12 | ios: PERMISSIONS.IOS.CAMERA,
13 | android: PERMISSIONS.ANDROID.CAMERA,
14 | })
15 |
16 | const FaceRecognitionView = () => {
17 | const isFocused = useIsFocused();
18 | const sdkViewRef = useRef(null);
19 |
20 | useEffect(() => {
21 | if (isFocused) {
22 | startCamera();
23 | } else {
24 | stopCamera();
25 | }
26 |
27 | return () => {
28 | if(isFocused) {
29 | stopCamera();
30 | }
31 | };
32 | }, [isFocused]);
33 |
34 | const startCamera = async () => {
35 | await FaceSDKModule.startCamera();
36 | };
37 |
38 | const stopCamera = async () => {
39 | await FaceSDKModule.stopCamera();
40 | };
41 |
42 | const handleViewLayout = () => {
43 | if (isFocused && sdkViewRef.current) {
44 | startCamera();
45 | } else {
46 | stopCamera();
47 | }
48 | };
49 |
50 | return (
51 |
52 |
53 |
59 |
60 |
61 | );
62 | };
63 |
64 | const FaceRecognitionPage = ({ navigation, route }) => {
65 |
66 | const { persons } = route.params;
67 | const [faces, setFaces] = useState([]);
68 | const [cameraShow, setCameraShow] = useState(false);
69 | const isFocused = useIsFocused();
70 |
71 | var recognized = false;
72 |
73 | const goBackToHome = () => {
74 | navigation.goBack();
75 | };
76 |
77 | useEffect(() => {
78 | checkPermission();
79 |
80 | const eventEmitter = new NativeEventEmitter(FaceSDKModule);
81 | let eventListener = eventEmitter.addListener('onFaceDetected', (event) => {
82 | setFaces(event);
83 | if (recognized == false) {
84 | identifyPerson(event);
85 | }
86 | });
87 |
88 | if(isFocused)
89 | recognized = false;
90 | else
91 | recognized = true;
92 |
93 | return () => {
94 | eventListener.remove();
95 | };
96 |
97 | }, [isFocused]);
98 |
99 | const identifyPerson = async (curFaces) => {
100 | let maxSimilarity = -1;
101 | let maxSimilarityName = "";
102 | let maxLiveness = -1;
103 | let maxYaw = -1;
104 | let maxRoll = -1;
105 | let maxPitch = -1;
106 | let enrolledFace, identifiedFace;
107 |
108 | try {
109 | if (curFaces.length > 0) {
110 | const face = curFaces[0];
111 |
112 | for (const person of persons) {
113 | try {
114 | const similarity = await FaceSDKModule.similarityCalculation(
115 | face.templates,
116 | person.templates
117 | );
118 |
119 | console.log('similarity', similarity);
120 |
121 | if (maxSimilarity < similarity) {
122 | maxSimilarity = similarity;
123 | maxSimilarityName = person.name;
124 | maxLiveness = face.liveness;
125 | maxYaw = face.yaw;
126 | maxRoll = face.roll;
127 | maxPitch = face.pitch;
128 | identifiedFace = face.faceJpg;
129 | enrolledFace = person.faceJpg;
130 | }
131 | } catch (error) {
132 | console.error('Error calculating similarity:', error);
133 | }
134 | }
135 | }
136 | } catch (error) {
137 | console.error('Error setting activation:', error);
138 | }
139 |
140 | if (maxSimilarity > 0.8 && maxLiveness > 0.7) {
141 | recognized = true;
142 |
143 | navigation.replace('Result', { enrolledFace, identifiedFace, maxSimilarityName, maxSimilarity, maxLiveness, maxYaw, maxRoll, maxPitch });
144 |
145 | setFaces([]);
146 | }
147 | };
148 |
149 | const checkPermission = async () => {
150 | const permissionStatus = await check(cameraPermission);
151 | handlePermissionStatus(permissionStatus);
152 | };
153 |
154 | const requestPermission = async () => {
155 | const permissionStatus = await request(cameraPermission);
156 | handlePermissionStatus(permissionStatus);
157 | };
158 |
159 | const handlePermissionStatus = (status) => {
160 | switch (status) {
161 | case RESULTS.UNAVAILABLE:
162 | break;
163 | case RESULTS.DENIED:
164 | requestPermission();
165 | break;
166 | case RESULTS.GRANTED:
167 | setCameraShow(true);
168 | break;
169 | case RESULTS.BLOCKED:
170 | break;
171 | }
172 | };
173 |
174 | return (
175 |
176 |
177 |
178 |
180 |
183 |
184 |
185 | Face Recognition
186 |
187 |
188 |
189 | {cameraShow ? (
190 |
191 | ) : (
192 |
193 | Camera permission issue.
194 |
195 | )}
196 |
207 |
208 |
209 |
210 |
211 | );
212 | };
213 |
214 | const FacePainter = ({ faces, livenessThreshold }) => {
215 | const [viewDimensions, setViewDimensions] = useState({ width: 0, height: 0 });
216 |
217 | const onLayout = (event) => {
218 | const { width, height } = event.nativeEvent.layout;
219 | setViewDimensions({ width, height });
220 | };
221 |
222 | const renderFaces = () => {
223 | return faces.map((face, index) => {
224 | const { x1, y1, x2, y2, frameWidth, frameHeight, liveness } = face;
225 | const xScale = frameWidth / viewDimensions.width;
226 | const yScale = frameHeight / viewDimensions.height;
227 | const isRealFace = liveness >= livenessThreshold;
228 |
229 | const rectStyle = isRealFace ? styles.realFaceRect : styles.spoofFaceRect;
230 | const textStyle = isRealFace ? styles.realFaceText : styles.spoofFaceText;
231 | const title = isRealFace ? `Real ${liveness}` : `Spoof ${liveness}`;
232 |
233 | return (
234 |
235 | {title}
236 |
248 |
249 | );
250 | });
251 | };
252 |
253 | return (
254 |
255 | {renderFaces()}
256 |
257 | );
258 | };
259 |
260 | const styles = StyleSheet.create({
261 | container: {
262 | flex: 1,
263 | backgroundColor: '#1C1B1F'
264 | },
265 | appBar: {
266 | height: 70,
267 | backgroundColor: '#1C1B1F',
268 | justifyContent: 'center',
269 | alignItems: 'center',
270 | },
271 | title: {
272 | marginLeft: 30,
273 | flex: 1,
274 | fontSize: 18,
275 | color: '#FFFFFF',
276 | },
277 | body: {
278 | flex: 1,
279 | },
280 | description: {
281 | marginBottom: 8,
282 | fontSize: 14,
283 | color: '#FFF',
284 | },
285 | contact: {
286 | marginBottom: 8,
287 | fontSize: 14,
288 | fontWeight: 'bold',
289 | color: '#FFF',
290 | },
291 | contactRow: {
292 | flexDirection: 'row',
293 | alignItems: 'center',
294 | marginBottom: 4,
295 | },
296 | icon: {
297 | width: 24,
298 | height: 24,
299 | marginRight: 4,
300 | tintColor: '#FFFFFF',
301 | },
302 | box: {
303 | flex: 1,
304 | marginVertical: 0,
305 | },
306 | containerFace: {
307 | ...StyleSheet.absoluteFillObject,
308 | justifyContent: 'center',
309 | alignItems: 'center',
310 | },
311 | faceRect: {
312 | position: 'absolute',
313 | borderWidth: 3,
314 | },
315 | realFaceRect: {
316 | borderColor: '#00FF00',
317 | },
318 | spoofFaceRect: {
319 | borderColor: '#FF0000',
320 | },
321 | faceText: {
322 | position: 'absolute',
323 | fontSize: 20,
324 | },
325 | realFaceText: {
326 | color: '#00FF00',
327 | },
328 | spoofFaceText: {
329 | color: '#FF0000',
330 | },
331 | });
332 |
333 | export default FaceRecognitionPage;
--------------------------------------------------------------------------------
/example/src/Person.tsx:
--------------------------------------------------------------------------------
1 | class Person {
2 | constructor(name, faceJpg, templates) {
3 | this.name = name;
4 | this.faceJpg = faceJpg;
5 | this.templates = templates;
6 | }
7 |
8 | static fromMap(data) {
9 | return new Person(data.name, data.faceJpg, data.templates);
10 | }
11 |
12 | toMap() {
13 | return {
14 | name: this.name,
15 | faceJpg: this.faceJpg,
16 | templates: this.templates,
17 | };
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/example/src/PersonView.tsx:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { View, Text, StyleSheet, Image, TouchableOpacity, FlatList } from 'react-native';
3 |
4 | const PersonView = ({ personList, deletePerson }) => {
5 | const renderItem = ({ item, index }) => {
6 | return (
7 |
11 |
12 |
16 |
17 |
18 | {item.name}
19 |
20 |
21 | deletePerson(index)}>
22 |
26 |
27 |
28 |
29 | );
30 | };
31 |
32 | return (
33 | index.toString()}
37 | />
38 | );
39 | };
40 |
41 | const styles = StyleSheet.create({
42 | buttonIcon: {
43 | width: 24,
44 | height: 24,
45 | marginRight: 4,
46 | tintColor: '#FFFFFF',
47 | },
48 | });
49 |
50 | export default PersonView;
51 |
--------------------------------------------------------------------------------
/example/src/ResultPage.tsx:
--------------------------------------------------------------------------------
1 | // ResultPage.js
2 | import React from 'react';
3 | import { View, Text, StyleSheet, Image, TouchableOpacity } from 'react-native';
4 |
5 | const ResultPage = ({ navigation, route }) => {
6 |
7 | const { enrolledFace, identifiedFace, maxSimilarityName, maxSimilarity, maxLiveness, maxYaw, maxRoll, maxPitch } = route.params;
8 |
9 | const goBackToHome = () => {
10 | navigation.goBack();
11 | };
12 |
13 | return (
14 |
15 |
16 |
17 |
19 |
22 |
23 |
24 | Identify Result
25 |
26 |
27 |
28 |
29 |
30 |
31 | {enrolledFace ? (
32 |
33 |
34 | Enrolled
35 |
36 | ) : (
37 |
38 | )}
39 | {identifiedFace ? (
40 |
41 |
42 | Identified
43 |
44 | ) : (
45 |
46 | )}
47 |
48 |
49 |
50 | Identified: {maxSimilarityName}
51 |
52 |
53 | Similarity: {maxSimilarity}
54 |
55 |
56 | Liveness score: {maxLiveness}
57 |
58 |
59 | Yaw: {maxYaw}
60 |
61 |
62 | Roll: {maxRoll}
63 |
64 |
65 | Pitch: {maxPitch}
66 |
67 |
68 |
69 |
70 | );
71 | };
72 |
73 | const styles = StyleSheet.create({
74 | container: {
75 | flex: 1,
76 | backgroundColor: '#1C1B1F'
77 | },
78 | appBar: {
79 | height: 60,
80 | backgroundColor: '#1C1B1F',
81 | justifyContent: 'center',
82 | alignItems: 'center',
83 | },
84 | title: {
85 | marginLeft: 30,
86 | flex: 1,
87 | fontSize: 18,
88 | color: '#FFFFFF',
89 | },
90 | body: {
91 | flex: 1,
92 | margin: 16,
93 | },
94 | description: {
95 | marginBottom: 8,
96 | fontSize: 14,
97 | color: '#FFF',
98 | },
99 | contact: {
100 | marginBottom: 8,
101 | fontSize: 14,
102 | fontWeight: 'bold',
103 | color: '#FFF',
104 | },
105 | contactRow: {
106 | flexDirection: 'row',
107 | alignItems: 'center',
108 | marginBottom: 4,
109 | },
110 | icon: {
111 | width: 24,
112 | height: 24,
113 | marginRight: 4,
114 | tintColor: '#FFFFFF',
115 | },
116 | });
117 |
118 | export default ResultPage;
--------------------------------------------------------------------------------
/example/src/SettingsPage.tsx:
--------------------------------------------------------------------------------
1 | import React, { useState, useEffect } from 'react';
2 | import { View, Text, StyleSheet, Image, Switch, TextInput, Button, Alert, TouchableOpacity } from 'react-native';
3 | import SettingsList from 'react-native-settings-list';
4 | import RNPickerSelect from 'react-native-picker-select';
5 | import Modal from 'react-native-modal';
6 | // import { Picker } from '@react-native-picker/picker';
7 | // import AsyncStorage from '@react-native-async-storage/async-storage';
8 |
9 |
10 | const SettingsPage = ({ navigation }) => {
11 | const [cameraLens, setCameraLens] = useState(false);
12 | const [livenessThreshold, setLivenessThreshold] = useState('0.7');
13 | const [identifyThreshold, setIdentifyThreshold] = useState('0.8');
14 | const [selectedLivenessLevel, setSelectedLivenessLevel] = useState(0);
15 | const [frontCameraValue, setFrontCameraValue] = useState(true);
16 |
17 | const livenessController = React.createRef();
18 | const identifyController = React.createRef();
19 |
20 | const livenessLevelNames = ['Best Accuracy', 'Light Weight'];
21 |
22 | const goBackToHome = () => {
23 | navigation.goBack();
24 | };
25 |
26 |
27 | useEffect(() => {
28 | loadSettings();
29 | }, []);
30 |
31 | const loadSettings = async () => {
32 | // try {
33 | // const cameraLensValue = await AsyncStorage.getItem('camera_lens');
34 | // const livenessLevelValue = await AsyncStorage.getItem('liveness_level');
35 | // const livenessThresholdValue = await AsyncStorage.getItem('liveness_threshold');
36 | // const identifyThresholdValue = await AsyncStorage.getItem('identify_threshold');
37 |
38 | // setCameraLens(cameraLensValue === '1');
39 | // setLivenessThreshold(livenessThresholdValue || '0.7');
40 | // setIdentifyThreshold(identifyThresholdValue || '0.8');
41 | // setSelectedLivenessLevel(livenessLevelValue ? parseInt(livenessLevelValue) : 0);
42 | // } catch (error) {
43 | // console.log('Error loading settings:', error);
44 | // }
45 | };
46 |
47 | const restoreSettings = async () => {
48 | // try {
49 | // await AsyncStorage.setItem('first_write', '0');
50 | // await initSettings();
51 | // await loadSettings();
52 |
53 | // Alert.alert('Default settings restored!');
54 | // } catch (error) {
55 | // console.log('Error restoring settings:', error);
56 | // }
57 | };
58 |
59 | const deleteAllPerson = async () => {
60 |
61 | };
62 |
63 | const initSettings = async () => {
64 | // try {
65 | // const firstWrite = await AsyncStorage.getItem('first_write');
66 | // if (!firstWrite) {
67 | // await AsyncStorage.setItem('first_write', '1');
68 | // await AsyncStorage.setItem('camera_lens', '1');
69 | // await AsyncStorage.setItem('liveness_level', '0');
70 | // await AsyncStorage.setItem('liveness_threshold', '0.7');
71 | // await AsyncStorage.setItem('identify_threshold', '0.8');
72 | // }
73 | // } catch (error) {
74 | // console.log('Error initializing settings:', error);
75 | // }
76 | };
77 |
78 | // const updateLivenessLevel = async (value) => {
79 | // // try {
80 | // // await AsyncStorage.setItem('liveness_level', value.toString());
81 | // // } catch (error) {
82 | // // console.log('Error updating liveness level:', error);
83 | // // }
84 | // };
85 |
86 | const updateCameraLens = async (value) => {
87 | // try {
88 | // await AsyncStorage.setItem('camera_lens', value ? '1' : '0');
89 | // setCameraLens(value);
90 | // } catch (error) {
91 | // console.log('Error updating camera lens:', error);
92 | // }
93 | };
94 |
95 | const updateLivenessThreshold = async () => {
96 |
97 | // try {
98 | // const doubleValue = parseFloat(livenessController.current.value);
99 | // if (!isNaN(doubleValue) && doubleValue >= 0 && doubleValue < 1.0) {
100 | // await AsyncStorage.setItem('liveness_threshold', livenessController.current.value);
101 | // setLivenessThreshold(livenessController.current.value);
102 | // }
103 | // } catch (error) {
104 | // console.log('Error updating liveness threshold:', error);
105 | // }
106 | };
107 |
108 | const updateIdentifyThreshold = async () => {
109 | // try {
110 | // const doubleValue = parseFloat(identifyController.current.value);
111 | // if (!isNaN(doubleValue) && doubleValue >= 0 && doubleValue < 1.0) {
112 | // await AsyncStorage.setItem('identify_threshold', identifyController.current.value);
113 | // setIdentifyThreshold(identifyController.current.value);
114 | // }
115 | // } catch (error) {
116 | // console.log('Error updating identify threshold:', error);
117 | // }
118 | };
119 |
120 | const showLivenessThresholdPicker = () => {
121 | Alert.prompt(
122 | 'Liveness thresholds',
123 | '',
124 | (text) => {
125 | setLivenessThreshold(text);
126 | console.log('You entered: ' + text);
127 | },
128 | undefined,
129 | livenessThreshold
130 | );
131 | };
132 |
133 | const showLivenessLevelPicker = () => {
134 |
135 | };
136 |
137 | const onFrontChanged = (value) => {
138 | setFrontCameraValue(value)
139 | }
140 |
141 | return (
142 |
143 |
144 |
145 |
147 |
150 |
151 |
152 | Settings
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
163 |
164 |
165 | }
166 | title='Front'
167 | hasNavArrow={false}
168 | hasSwitch={true}
169 | switchState={frontCameraValue}
170 | switchOnValueChange={onFrontChanged}
171 | />
172 |
173 |
176 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |