Language detection guide for iOS

The Language Detector task lets you identify the language of a piece of text. These instructions show you how to use the Language Detector in iOS apps. The code sample described in these instructions is available on GitHub.

You can see this task in action by viewing this Web demo. For more information about the capabilities, models, and configuration options of this task, see the Overview.

Code example

The MediaPipe Tasks example code is a basic implementation of a Language Detector app for iOS.

You can use the app as a starting point for your own iOS app, or refer to it when modifying an existing app. You can refer to the Language Detector example code on GitHub.

Download the code

The following instructions show you how to create a local copy of the example code using the git command line tool.

To download the example code:

  1. Clone the git repository using the following command:

    git clone https://github.com/google-ai-edge/mediapipe-samples
    
  2. Optionally, configure your git instance to use sparse checkout, so you have only the files for the Language Detector example app:

    cd mediapipe-samples
    git sparse-checkout init --cone
    git sparse-checkout set examples/language_detector/ios/
    

After creating a local version of the example code, you can install the MediaPipe task library, open the project using Xcode, and run the app. For instructions, see the Setup Guide for iOS.

Key components

The following files contain the crucial code for the Language Detector example application:

Setup

This section describes key steps for setting up your development environment and code projects to use Language Detector. For general information on setting up your development environment for using MediaPipe tasks, including platform version requirements, see the Setup guide for iOS.

Dependencies

Language Detector uses the MediaPipeTasksText library, which must be installed using CocoaPods. The library is compatible with both Swift and Objective-C apps and does not require any additional language-specific setup.

For instructions to install CocoaPods on macOS, refer to the CocoaPods installation guide. For instructions on how to create a Podfile with the necessary pods for your app, refer to Using CocoaPods.

Add the MediaPipeTasksText pod in the Podfile using the following code:

target 'MyLanguageDetectorApp' do
  use_frameworks!
  pod 'MediaPipeTasksText'
end

If your app includes unit test targets, refer to the Set Up Guide for iOS for additional information on setting up your Podfile.

Model

The MediaPipe Language Detector task requires a trained model that is compatible with this task. For more information about the available trained models for Language Detector, see the task overview Models section.

Select and download a model, and add it to your project directory using Xcode. For instructions on how to add files to your Xcode project, refer to Managing files and folders in your Xcode project.

Use the BaseOptions.modelAssetPath property to specify the path to the model in your app bundle. For a code example, see the next section.

Create the task

You can create the Language Detector task by calling one of its initializers. The LanguageDetector(options:) initializer sets values for the configuration options.

If you don't need a Language Detector initialized with customized configuration options, you can use the LanguageDetector(modelPath:) initializer to create a Language Detector with the default options. For more information about configuration options, see Configuration Overview.

The following code demonstrates how to build and configure this task.

Swift

import MediaPipeTasksText

let modelPath = Bundle.main.path(forResource: "model",
                                      ofType: "tflite")

let options = LanguageDetectorOptions()
options.baseOptions.modelAssetPath = modelPath
options.scoreThreshold = 0.6

let languageDetector = try LanguageDetector(options: options)

Objective-C

@import MediaPipeTasksText;

NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"model"
                                                      ofType:@"tflite"];

MPPLanguageDetectorOptions *options = [[MPPLanguageDetectorOptions alloc] init];
options.baseOptions.modelAssetPath = modelPath;
options.scoreThreshold = 0.6;

MPPLanguageDetector *languageDetector =
      [[MPPLanguageDetector alloc] initWithOptions:options error:nil];

Configuration options

This task has the following configuration options for iOS apps:

Option Name Description Value Range Default Value
maxResults Sets the optional maximum number of top-scored language predictions to return. If this value is less than zero, all available results are returned. Any positive numbers -1
scoreThreshold Sets the prediction score threshold that overrides the one provided in the model metadata (if any). Results below this value are rejected. Any float Not set
categoryAllowlist Sets the optional list of allowed language codes. If non-empty, language predictions whose language code is not in this set will be filtered out. This option is mutually exclusive with categoryDenylist and using both results in an error. Any strings Not set
categoryDenylist Sets the optional list of language codes that are not allowed. If non-empty, language predictions whose language code is in this set will be filtered out. This option is mutually exclusive with categoryAllowlist and using both results in an error. Any strings Not set

Prepare data

Language Detector works with text data. The task handles the data input preprocessing, including tokenization and tensor preprocessing.

All preprocessing is handled within the detect(text:) function. There is no need for additional preprocessing of the input text beforehand.

Swift

let text = "The input text to be classified."

Objective-C

NSString *text = @"The input text to be classified.";

Run the task

To run the Language Detector, use the detect(text:) method. The Language Detector returns the predicted languages and their probabilities.

Swift

let result = try languageDetector.detect(text: text)

Objective-C

MPPLanguageDetectorResult *result = [languageDetector detectText:text
                                                           error:nil];

Note: The task blocks the current thread until it finishes running inference on the text. To avoid blocking the current thread, execute the processing in a background thread using iOS Dispatch or NSOperation frameworks.

Handle and display results

Upon running inference, the Language Detector task returns a LanguageDetectorResult object which contains a list of predicted languages with their probabilities.

The following shows an example of the output data from this task:

LanguageDetectorResult:
  LanguagePrediction #0:
    language_code: "fr"
    probability: 0.999781

This result has been obtained by running the model on the input text: "Il y a beaucoup de bouches qui parlent et fort peu de têtes qui pensent.".

The ViewController.swift file in the example code demonstrates how to display the detection results returned from the task.