# TensorFlow Lite in Google Play services Java API TensorFlow Lite in Google Play services can also be accessed using Java APIs, in addition to the Native API. In particular, TensorFlow Lite in Google Play services is available through the [TensorFlow Lite Task API](https://www.tensorflow.org/lite/api_docs/java/org/tensorflow/lite/task/core/package-summary) and the [TensorFlow Lite Interpreter API](https://www.tensorflow.org/lite/api_docs/java/org/tensorflow/lite/InterpreterApi). The Task Library provides optimized out-of-the-box model interfaces for common machine learning tasks using visual, audio, and text data. The TensorFlow Lite Interpreter API, provided by the TensorFlow runtime, provides a more general-purpose interface for building and running ML models. The following sections provide instructions on how to use the Interpreter and Task Library APIs with TensorFlow Lite in Google Play services. While it is possible for an app to use both the Interpreter APIs and Task Library APIs, most apps should only use one set of APIs. ### Using the Task Library APIs The TensorFlow Lite Task API wraps the Interpreter API and provides a high-level programming interface for common machine learning tasks that use visual, audio, and text data. You should use the Task API if your application requires one of the [supported tasks](../inference_with_metadata/task_library/overview.md#supported-tasks). #### 1. Add project dependencies Your project dependency depends on your machine learning use case. The Task APIs contain the following libraries: * Vision library: `org.tensorflow:tensorflow-lite-task-vision-play-services` * Audio library: `org.tensorflow:tensorflow-lite-task-audio-play-services` * Text library: `org.tensorflow:tensorflow-lite-task-text-play-services` Add one of the dependencies to your app project code to access the Play services API for TensorFlow Lite. For example, use the following to implement a vision task: ``` dependencies { ... implementation 'org.tensorflow:tensorflow-lite-task-vision-play-services:0.4.2' ... } ``` Caution: The TensorFlow Lite Tasks Audio library version 0.4.2 maven repository is incomplete. Use version 0.4.2.1 for this library instead: `org.tensorflow:tensorflow-lite-task-audio-play-services:0.4.2.1`. #### 2. Add initialization of TensorFlow Lite Initialize the TensorFlow Lite component of the Google Play services API *before* using the TensorFlow Lite APIs. The following example initializes the vision library:
init {
TfLiteVision.initialize(context)
}
fun detect(...) {
if (!TfLiteVision.isInitialized()) {
Log.e(TAG, "detect: TfLiteVision is not initialized yet")
return
}
if (objectDetector == null) {
setupObjectDetector()
}
...
}
val initializeTask: Task<Void> by lazy { TfLite.initialize(this) }
Task<Void> initializeTask = TfLite.initialize(context);
import org.tensorflow.lite.InterpreterApi
import org.tensorflow.lite.InterpreterApi.Options.TfLiteRuntime
...
private lateinit var interpreter: InterpreterApi
...
initializeTask.addOnSuccessListener {
val interpreterOption =
InterpreterApi.Options().setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY)
interpreter = InterpreterApi.create(
modelBuffer,
interpreterOption
)}
.addOnFailureListener { e ->
Log.e("Interpreter", "Cannot initialize interpreter", e)
}
import org.tensorflow.lite.InterpreterApi
import org.tensorflow.lite.InterpreterApi.Options.TfLiteRuntime
...
private InterpreterApi interpreter;
...
initializeTask.addOnSuccessListener(a -> {
interpreter = InterpreterApi.create(modelBuffer,
new InterpreterApi.Options().setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY));
})
.addOnFailureListener(e -> {
Log.e("Interpreter", String.format("Cannot initialize interpreter: %s",
e.getMessage()));
});
import androidx.lifecycle.lifecycleScope
...
lifecycleScope.launchWhenStarted { // uses coroutine
initializeTask.await()
}
@BackgroundThread
InterpreterApi initializeInterpreter() {
Tasks.await(initializeTask);
return InterpreterApi.create(...);
}
interpreter.run(inputBuffer, outputBuffer)
interpreter.run(inputBuffer, outputBuffer);
lateinit val optionsTask = useGpuTask.continueWith { task ->
val baseOptionsBuilder = BaseOptions.builder()
if (task.result) {
baseOptionsBuilder.useGpu()
}
ObjectDetectorOptions.builder()
.setBaseOptions(baseOptionsBuilder.build())
.setMaxResults(1)
.build()
}
Task<ObjectDetectorOptions> optionsTask = useGpuTask.continueWith({ task ->
BaseOptions baseOptionsBuilder = BaseOptions.builder();
if (task.getResult()) {
baseOptionsBuilder.useGpu();
}
return ObjectDetectorOptions.builder()
.setBaseOptions(baseOptionsBuilder.build())
.setMaxResults(1)
.build()
});
val interpreterTask = useGpuTask.continueWith { task ->
val interpreterOptions = InterpreterApi.Options()
.setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY)
if (task.result) {
interpreterOptions.addDelegateFactory(GpuDelegateFactory())
}
InterpreterApi.create(FileUtil.loadMappedFile(context, MODEL_PATH), interpreterOptions)
}
Task<InterpreterApi.Options> interpreterOptionsTask = useGpuTask.continueWith({ task ->
InterpreterApi.Options options =
new InterpreterApi.Options().setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY);
if (task.getResult()) {
options.addDelegateFactory(new GpuDelegateFactory());
}
return options;
});
TfLiteVision.initialize(context, TfLiteInitializationOptions.builder().setEnableGpuDelegateSupport(true).build())
TfLiteVision.initialize(context, TfLiteInitializationOptions.builder().setEnableGpuDelegateSupport(true).build());
val baseOptions = BaseOptions.builder().useGpu().build()
BaseOptions baseOptions = BaseOptions.builder().useGpu().build();
val options =
ObjectDetectorOptions.builder()
.setBaseOptions(baseOptions)
.setMaxResults(1)
.build()
ObjectDetectorOptions options =
ObjectDetectorOptions.builder()
.setBaseOptions(baseOptions)
.setMaxResults(1)
.build();
TfLite.initialize(context,
TfLiteInitializationOptions.builder()
.setEnableGpuDelegateSupport(true)
.build())
TfLite.initialize(context,
TfLiteInitializationOptions.builder()
.setEnableGpuDelegateSupport(true)
.build());
val interpreterOption = InterpreterApi.Options()
.setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY)
.addDelegateFactory(GpuDelegateFactory())
Options interpreterOption = InterpreterApi.Options()
.setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY)
.addDelegateFactory(new GpuDelegateFactory());
org.tensorflow:**tensorflow-lite**:*) from your build.gradle
file so that you can reduce your app size.
4. Identify all occurrences of `new Interpreter` object creation in your code,
and modify each one so that it uses the InterpreterApi.create() call. The
new TfLite.initialize is asynchronous, which means in most cases it's not a
drop-in replacement: you must register a listener for when the call
completes. Refer to the code snippet in [Step 3](#step_3_interpreter) code.
5. Add `import org.tensorflow.lite.InterpreterApi;` and `import
org.tensorflow.lite.InterpreterApi.Options.TfLiteRuntime;` to any source
files using the `org.tensorflow.lite.Interpreter` or
`org.tensorflow.lite.InterpreterApi` classes.
6. If any of the resulting calls to `InterpreterApi.create()` have only a
single argument, append `new InterpreterApi.Options()` to the argument list.
7. Append `.setRuntime(TfLiteRuntime.FROM_SYSTEM_ONLY)` to the last argument of
any calls to `InterpreterApi.create()`.
8. Replace all other occurrences of the `org.tensorflow.lite.Interpreter` class
with `org.tensorflow.lite.InterpreterApi`.
If you want to use stand-alone TensorFlow Lite and the Play services API
side-by-side, you must use TensorFlow Lite 2.9 (or later). TensorFlow Lite 2.8
and earlier versions are not compatible with the Play services API version.