在 Android 上使用機器學習套件翻譯文字

您可以使用 ML Kit 在語言之間翻譯文本。 ML Kit目前支持59種語言之間的翻譯。

在你開始之前

  1. 如果您尚未將 Firebase 添加到您的 Android 項目中,請將其添加到您的 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.
    }