获取我们在 Firebase 峰会上发布的所有信息,了解 Firebase 可如何帮助您加快应用开发速度并满怀信心地运行应用。了解详情

在 Android 上使用机器学习套件翻译文本

使用集合让一切井井有条 根据您的偏好保存内容并对其进行分类。

您可以使用 ML Kit 在语言之间翻译文本。 ML Kit 目前支持59 种语言之间的翻译。

在你开始之前

  1. 如果您还没有,请将 Firebase 添加到您的 Android 项目中。
  2. 将 ML Kit 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.
                // ...
            }
    

    语言模型大约 30MB,所以不要不必要地下载它们,只使用 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 时,ML Kit 会根据需要自动将特定语言的翻译模型下载到设备。您还可以使用 ML Kit 的翻译模型管理 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.
    }