react-native-mlkit

repository·main·Indexed 19 days ago

https://github.com/infinitered/react-native-mlkit

A collection of Expo modules providing wrappers for Google's MLKit native libraries. It enables machine learning capabilities in Expo applications, including face detection, text recognition, document scanning, image labeling, and object detection. The library includes a core package (@infinitered/react-native-mlkit-core) with utility hooks for layout and scaling, as well as components like BoundingBoxView and ImageWithBoundingBoxes for rendering detection results.

Tokens
31.6K
Snippets
96
Records
134
Agent score
65%

What's inside react-native-mlkit

  1. Introduction to react-native-mlkit-face-detection

    main

    The react-native-mlkit-face-detection module provides React Native APIs for Google's ML Kit Native Modules (Swift and Kotlin). It allows you to perform face detection within a React Native application using the speed and power of native ML Kit implementations.

    Key Capabilities:

    • Face Detection: Detect faces in an image and identify key facial features.
    • Face Contour Detection: When enabled, provides a list of points for each detected facial feature representing its shape.

    Important Note: This API is designed for face detection (identifying facial features and presence), not face recognition (identifying specific individuals).

  2. Module Organization and Usage

    main

    This repository is a monorepo organized as follows:

    • Apps: Contains the ExampleApp used for demonstrations.
    • Modules: Contains the individual MLKit modules. Each is a separate npm package published under the @infinitered/ scope (e.g., @infinitered/react-native-mlkit-face-detection).
    • Packages: Contains internal, non-published packages (like linter configurations).

    To use a specific module, refer to the README within its respective directory in the modules/ folder. Available modules include:

    • react-native-mlkit-core
    • react-native-mlkit-face-detection
    • react-native-mlkit-text-recognition
    • react-native-mlkit-document-scanner
    • react-native-mlkit-image-labeling
    • react-native-mlkit-object-detection
  3. Understand the Ignite boilerplate project structure

    main

    The example-app uses the Ignite boilerplate, which provides a structured directory layout for React Native applications. Key directories include:

    • app/: The core application logic, containing components, models (MobX State Tree), navigators (React Navigation), screens, services, and theme configuration.
    • assets/: Organized storage for icons and images.
    • ignite/: Contains Ignite-specific CLI tools and customizable templates.
    • test/: Holds Jest configurations and mocks.
    • android/ & ios/: Native platform project files.
  4. How Face Detection context works

    main

    The face detection functionality is powered by a React Context system. The FaceDetectionProvider initializes a RNMLKitFaceDetector and provides it to the component tree via FaceDetectionContext.

    Consumers can then use hooks like useFaceDetection to grab the raw detector instance or useFacesInPhoto to use high-level detection logic. The context value (FaceDetectionContextValue) primarily exposes the faceDetector instance.

  5. Understand FaceDetectionState

    main

    FaceDetectionState represents the lifecycle of the face detection process. Monitoring these states allows you to update your UI (e.g., showing a loading spinner during modelLoading or an error message during error).

    StateDescription
    initInitial state before detector initialization
    modelLoadingML model is currently being loaded
    readyDetector is initialized and ready
    detectingCurrently processing an image
    doneDetection completed successfully
    errorAn error occurred during detection
  6. Organize application logic in the ./app directory

    main

    The app directory is the central location for your application code. It is organized into the following subdirectories:

    • components/: Reusable UI components used to build screens.
    • config/: Application configuration.
    • i18n/: Translation files for react-native-i18n.
    • models/: MobX State Tree models. Each model typically has its own directory containing the model file, tests, actions, and types.
    • navigators/: react-navigation configuration and navigators.
    • screens/: Full-screen React components. Each screen should have its own directory containing the .tsx file and any screen-specific assets.
    • services/: Interfaces with external systems like REST APIs or Push Notifications.
    • theme/: Application styling, including colors, spacing, and typography.
    • utils/: Truly shared helper functions (e.g., date formatters). For component-specific logic, prefer co-locating helpers within the component or model directory.
  7. How object detection models and providers work together

    main

    The object detection module uses a React Context pattern to manage models.

    1. Loading Models: Use the useObjectDetectionModels hook to load either default models or custom TFLite models defined in an ObjectDetectionConfig object. This hook returns the loaded model instances.
    2. Providing Context: Pass the loaded models to useObjectDetectionProvider to obtain an ObjectDetectionModelProvider component. Wrapping your application (or a specific subtree) with this provider makes the models accessible to all child components.
    3. Consuming Models: Use the useObjectDetection<T>(modelName) hook in any child component to retrieve a specific detector by its key (e.g., 'birdDetector').

    This architecture ensures that models are loaded once and efficiently shared across your component tree.

    // 1. Load models
    const models = useObjectDetectionModels<MyModelsConfig>({
      assets: MODELS,
      loadDefaultModel: true,
    });
    
    // 2. Get provider
    const { ObjectDetectionModelProvider } = useObjectDetectionProvider(models);
    
    // 3. Wrap app
    <ObjectDetectionModelProvider>
      <App />
    </ObjectDetectionModelProvider>
    
    // 4. Use in component
    const detector = useObjectDetection<MyModelsConfig>('birdDetector');
  8. Quickstart: Running the example app

    main

    To run the ExampleApp included in this repository, follow these steps in order:

    1. Clone the project

      git clone git@github.com:infinitered/react-native-mlkit.git
    2. Install dependencies

      yarn
    3. Build native modules

      yarn build
    4. Create a development build

    iOS

    Note: MLKit is not supported in the iOS simulator. You must use a hardware device.

    Via Terminal:

    cd apps/ExampleApp
    npx expo run:ios -d

    Via Xcode:

    1. Generate native project folders:
      cd apps/ExampleApp
      npx expo prebuild
    2. Open apps/ExampleApp/ios/ExampleApp.xcworkspace in Xcode.
    3. Select the ExampleApp target and choose a Team in the "Signing & Capabilities" tab.
    4. Select a physical hardware device (simulators are not supported).
    5. Click the Play button to build.

    Android

    Note: Android support is under active development; some modules may not function as intended.

    cd apps/ExampleApp
    npx expo run:android -d
    git clone git@github.com:infinitered/react-native-mlkit.git
    yarn
    yarn build
    cd apps/ExampleApp
    npx expo run:ios -d
  9. Defer Face Detector initialization

    main

    To improve performance or delay setup until a specific user action, you can prevent the face detector from initializing automatically upon mount.

    1. Set the deferInitialization prop on the FaceDetectionProvider.
    2. Manually call the .initialize() method on the detector instance (obtained via useFaceDetection) when you are ready to start using it.
    // 1. Configure the provider to defer initialization
    function App() {
      return (
        <FaceDetectionProvider
          options={FACE_DETECTION_OPTIONS}
          deferInitialization
        >
          {/* rest of your app */}
        </FaceDetectionProvider>
      );
    }
    
    // 2. Manually initialize when needed
    function MyComponent() {
      const detector = useFaceDetection();
      
      useEffect(() => {
        detector.initialize();
      }, [detector]);
    
      // ...
    }