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

您可以使用 ML Kit 來翻譯不同語言的文字。機器學習套件可翻譯超過 50 種語言

立即體驗

事前準備

  1. 在 Podfile 中加入下列機器學習套件 Pod:
    pod 'GoogleMLKit/Translate', '3.2.0'
    
  2. 安裝或更新專案的 Pod 後,使用 .xcworkspace 開啟 Xcode 專案。Xcode 12.4 以上版本支援機器學習套件。

翻譯字串

如何翻譯兩種語言的字串:

  1. 建立 Translator 物件,並設定原文和譯文語言:

    Swift

        // Create an English-German translator:
        let options = TranslatorOptions(sourceLanguage: .english, targetLanguage: .german)
        let englishGermanTranslator = Translator.translator(options: options)

    Objective-C

        // Create an English-German translator:
        MLKTranslatorOptions *options =
            [[MLKTranslatorOptions alloc] initWithSourceLanguage:MLKTranslateLanguageEnglish
                                                  targetLanguage:MLKTranslateLanguageGerman];
        MLKTranslator *englishGermanTranslator =
            [MLKTranslator translatorwithOptions:options];

    如果您不知道輸入文字的文字語言,可以使用 Language Identification API,為您提供語言標記。然後將語言標記轉換為 ML Kit 列舉。此程式碼取決於您使用的語言:

    避免同時在裝置上儲存過多的語言模型。

  2. 確認必要的翻譯模型已下載到裝置上。 除非知道模型可用,否則請勿呼叫 translate(_:completion:)

    Swift

    let conditions = ModelDownloadConditions(
        allowsCellularAccess: false,
        allowsBackgroundDownloading: true
    )
    englishGermanTranslator.downloadModelIfNeeded(with: conditions) { error in
        guard error == nil else { return }
    
        // Model downloaded successfully. Okay to start translating.
    }

    Objective-C

    MLKModelDownloadConditions *conditions =
        [[MLKModelDownloadConditions alloc] initWithAllowsCellularAccess:NO
                                             allowsBackgroundDownloading:YES];
    [englishGermanTranslator downloadModelIfNeededWithConditions:conditions
                                                      completion:^(NSError *_Nullable error) {
      if (error != nil) {
        return;
      }
      // Model downloaded successfully. Okay to start translating.
    }];

    語言模型的大小約為 30MB,因此除非必要,否則不要進行不必要的下載,並且只使用 Wi-Fi 下載,不再需要其他模型時,請將其刪除。請參閱明確管理翻譯模型

  3. 確認模型下載完成之後,請將原文語言字串傳送至 translate(_:completion:)

    Swift

          englishGermanTranslator.translate(text) { translatedText, error in
              guard error == nil, let translatedText = translatedText else { return }
    
              // Translation succeeded.
          }

    Objective-C

          [englishGermanTranslator translateText:text
                                      completion:^(NSString *_Nullable translatedText,
                                                   NSError *_Nullable error) {
            if (error != nil || translatedText == nil) {
              return;
            }
    
            // Translation succeeded.
          }];

    ML Kit 會將文字翻譯成您設定的目標語言,並將翻譯後的文字傳送至完成處理常式。

譯者生命週期是由 ARC (自動參照計數) 控制,此為 AiOS 開發作業的建議慣例。移除所有強力參照後,開發人員會預期譯者被取消。

翻譯工具在記憶體中載入時,可佔用 30MB 至 150MB 的空間。建立並行翻譯執行個體時,開發人員應謹記裝置/應用程式的記憶體預算,同時避免裝置上儲存過多的語言模型。

明確管理翻譯模型

如上所述使用 Translation API 時,機器學習套件可視需要將語言專用的翻譯模型自動下載到裝置上。您也可以使用 ML Kit 的翻譯模型管理 API,明確管理要在裝置中使用的翻譯模型。如果您想提前下載模型,或從裝置中刪除不需要的模型,這個方法就非常實用。

如何取得裝置上儲存的翻譯模型:

Swift

let localModels = ModelManager.modelManager().downloadedTranslateModels

Objective-C

NSSet *localModels =
    [MLKModelManager modelManager].downloadedTranslateModels;

如要刪除模型:

Swift

// Delete the German model if it's on the device.
let germanModel = TranslateRemoteModel.translateRemoteModel(language: .german)
ModelManager.modelManager().deleteDownloadedModel(germanModel) { error in
    guard error == nil else { return }
    // Model deleted.
}

Objective-C

// Delete the German model if it's on the device.
MLKTranslateRemoteModel *germanModel =
    [MLKTranslateRemoteModel translateRemoteModelWithLanguage:MLKTranslateLanguageGerman];
[[MLKModelManager modelManager] deleteDownloadedModel:germanModel
                                           completion:^(NSError * _Nullable error) {
                                               if (error != nil) {
                                                   return;
                                               }
                                               // Model deleted.

如何下載模型:

Swift

// Download the French model.
let frenchModel = TranslateRemoteModel.translateRemoteModel(language: .french)

// Keep a reference to the download progress so you can check that the model
// is available before you use it.
progress = ModelManager.modelManager().download(
    frenchModel,
    conditions: ModelDownloadConditions(
        allowsCellularAccess: false,
        allowsBackgroundDownloading: true
    )
)

如要透過 NotificationCenter 取得下載狀態,請為 mlkitModelDownloadDidSucceedmlkitModelDownloadDidFail 註冊觀察器。務必在觀察器區塊中使用 self 的微弱參照,因為下載作業可能需要一些時間,而且當下載完成時可以釋出原始物件。例如:

NotificationCenter.default.addObserver(
    forName: .mlkitModelDownloadDidSucceed,
    object: nil,
    queue: nil
) { [weak self] notification in
    guard let strongSelf = self,
        let userInfo = notification.userInfo,
        let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue]
            as? TranslateRemoteModel,
        model == frenchModel
        else { return }
    // The model was downloaded and is available on the device
}

NotificationCenter.default.addObserver(
    forName: .mlkitModelDownloadDidFail,
    object: nil,
    queue: nil
) { [weak self] notification in
    guard let strongSelf = self,
        let userInfo = notification.userInfo,
        let model = userInfo[ModelDownloadUserInfoKey.remoteModel.rawValue]
            as? TranslateRemoteModel
        else { return }
    let error = userInfo[ModelDownloadUserInfoKey.error.rawValue]
    // ...
}

Objective-C

// Download the French model.
MLKModelDownloadConditions *conditions =
    [[MLKModelDownloadConditions alloc] initWithAllowsCellularAccess:NO
                                         allowsBackgroundDownloading:YES];
MLKTranslateRemoteModel *frenchModel =
    [MLKTranslateRemoteModel translateRemoteModelWithLanguage:MLKTranslateLanguageFrench];

// Keep a reference to the download progress so you can check that the model
// is available before you use it.
self.downloadProgress = [[MLKModelManager modelManager] downloadModel:frenchModel
conditions:conditions];

如要透過 NSNotificationCenter 取得下載狀態,請為 MLKModelDownloadDidSucceedNotificationMLKModelDownloadDidFailNotification 註冊觀察器。務必在觀察器區塊中使用 self 的微弱參照,因為下載可能需要一些時間,而且下載作業可以在下載完成時釋出。

__block MyViewController *weakSelf = self;

[NSNotificationCenter.defaultCenter
 addObserverForName:MLKModelDownloadDidSucceedNotification
 object:nil
 queue:nil
 usingBlock:^(NSNotification * _Nonnull note) {
     if (weakSelf == nil | note.userInfo == nil) {
         return;
     }

     MLKTranslateRemoteModel *model = note.userInfo[MLKModelDownloadUserInfoKeyRemoteModel];
     if ([model isKindOfClass:[MLKTranslateRemoteModel class]]
         && model == frenchModel) {
         // The model was downloaded and is available on the device
     }
 }];

[NSNotificationCenter.defaultCenter
 addObserverForName:MLKModelDownloadDidFailNotification
 object:nil
 queue:nil
 usingBlock:^(NSNotification * _Nonnull note) {
     if (weakSelf == nil | note.userInfo == nil) {
         return;
     }

     NSError *error = note.userInfo[MLKModelDownloadUserInfoKeyError];
 }];