在 Android 系统中使用机器学习套件翻译文本

您可以使用机器学习套件实现语言之间的文本互译。机器学习套件目前支持 59 种语言之间的互译。

准备工作

  1. 将 Firebase 添加到您的 Android 项目(如果尚未添加)。
  2. 将 Android 版机器学习套件库的依赖项添加到您的模块(应用级层)Gradle 文件(通常为 app/build.gradle):
    apply plugin: 'com.android.application'
    apply plugin: 'com.google.gms.google-services'
    
    dependencies {
      // ...
    
      implementation 'com.google.firebase:firebase-ml-natural-language:22.0.0'
      implementation 'com.google.firebase:firebase-ml-natural-language-translate-model:20.0.8'
    }

翻译文本字符串

为实现字符串在两种语言之间的互译,请执行以下操作:

  1. 创建一个 FirebaseTranslator 对象,并使用源语言和目标语言对其进行配置:

    Java

    // Create an English-German translator:
    FirebaseTranslatorOptions options =
            new FirebaseTranslatorOptions.Builder()
                    .setSourceLanguage(FirebaseTranslateLanguage.EN)
                    .setTargetLanguage(FirebaseTranslateLanguage.DE)
                    .build();
    final FirebaseTranslator englishGermanTranslator =
            FirebaseNaturalLanguage.getInstance().getTranslator(options);
    

    Kotlin+KTX

    // Create an English-German translator:
    val options = FirebaseTranslatorOptions.Builder()
            .setSourceLanguage(FirebaseTranslateLanguage.EN)
            .setTargetLanguage(FirebaseTranslateLanguage.DE)
            .build()
    val englishGermanTranslator = FirebaseNaturalLanguage.getInstance().getTranslator(options)
    

    如果您不知道输入文本的语言,可以先使用语言识别 API。(但请确保您不会在设备上同时保留太多语言模型。)

  2. 确保已将所需的翻译模型下载到设备上。 确信模型可用之后,再调用 translate()

    Java

    FirebaseModelDownloadConditions conditions = new FirebaseModelDownloadConditions.Builder()
        .requireWifi()
        .build();
    englishGermanTranslator.downloadModelIfNeeded(conditions)
          .addOnSuccessListener(
              new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void v) {
                  // Model downloaded successfully. Okay to start translating.
                  // (Set a flag, unhide the translation UI, etc.)
                }
              })
          .addOnFailureListener(
              new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                  // Model couldn’t be downloaded or other internal error.
                  // ...
                }
              });
    

    Kotlin+KTX

    englishGermanTranslator.downloadModelIfNeeded()
            .addOnSuccessListener {
                // Model downloaded successfully. Okay to start translating.
                // (Set a flag, unhide the translation UI, etc.)
            }
            .addOnFailureListener { exception ->
                // Model couldn’t be downloaded or other internal error.
                // ...
            }
    

    语言模型大小约为 30 MB,因此若非必要,请勿下载。此外,除非用户另行指定,否则应仅使用 WiFi 下载语言模型。您还应删除不需要的模型。 请参阅显式管理翻译模型

  3. 确认模型已下载后,将源语言的文本字符串传递至 translate()

    Java

    englishGermanTranslator.translate(text)
          .addOnSuccessListener(
              new OnSuccessListener<String>() {
                @Override
                public void onSuccess(@NonNull String translatedText) {
                  // Translation successful.
                }
              })
          .addOnFailureListener(
              new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                  // Error.
                  // ...
                }
              });
    

    Kotlin+KTX

    englishGermanTranslator.translate(text)
            .addOnSuccessListener { translatedText ->
                // Translation successful.
            }
            .addOnFailureListener { exception ->
                 // Error.
                 // ...
            }
    

    采用配置的目标语言的译文即会传递给成功监听器。

显式管理翻译模型

在您按上文所述使用翻译 API 时,机器学习套件会根据需要自动将特定语言的翻译模型下载到设备。您还可以使用机器学习套件的翻译模型管理 API 来显式管理设备上可用的翻译模型。如果您想提前下载模型或从设备中删除不需要的模型,此方法会非常有用。

Java

FirebaseModelManager modelManager = FirebaseModelManager.getInstance();

// Get translation models stored on the device.
modelManager.getDownloadedModels(FirebaseTranslateRemoteModel.class)
        .addOnSuccessListener(new OnSuccessListener<Set<FirebaseTranslateRemoteModel>>() {
            @Override
            public void onSuccess(Set<FirebaseTranslateRemoteModel> models) {
                // ...
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // Error.
            }
        });

// Delete the German model if it's on the device.
FirebaseTranslateRemoteModel deModel =
        new FirebaseTranslateRemoteModel.Builder(FirebaseTranslateLanguage.DE).build();
modelManager.deleteDownloadedModel(deModel)
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void v) {
                // Model deleted.
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // Error.
            }
        });

// Download the French model.
FirebaseTranslateRemoteModel frModel =
        new FirebaseTranslateRemoteModel.Builder(FirebaseTranslateLanguage.FR).build();
FirebaseModelDownloadConditions conditions = new FirebaseModelDownloadConditions.Builder()
        .requireWifi()
        .build();
modelManager.download(frModel, conditions)
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void v) {
                // Model downloaded.
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                // Error.
            }
        });

Kotlin+KTX

val modelManager = FirebaseModelManager.getInstance()

// Get translation models stored on the device.
modelManager.getDownloadedModels(FirebaseTranslateRemoteModel::class.java)
    .addOnSuccessListener { models ->
        // ...
    }
    .addOnFailureListener {
        // Error.
    }

// Delete the German model if it's on the device.
val deModel = FirebaseTranslateRemoteModel.Builder(FirebaseTranslateLanguage.DE).build()
modelManager.deleteDownloadedModel(deModel)
    .addOnSuccessListener {
        // Model deleted.
    }
    .addOnFailureListener {
        // Error.
    }

// Download the French model.
val frModel = FirebaseTranslateRemoteModel.Builder(FirebaseTranslateLanguage.FR).build()
val conditions = FirebaseModelDownloadConditions.Builder()
    .requireWifi()
    .build()
modelManager.download(frModel, conditions)
    .addOnSuccessListener {
        // Model downloaded.
    }
    .addOnFailureListener {
        // Error.
    }