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

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

准备工作

  1. 如果您尚未将 Firebase 添加到自己的应用中,请按照入门指南中的步骤执行此操作。
  2. 在 Podfile 中添加机器学习套件库:
    pod 'Firebase/MLNLTranslate', '6.25.0'
    
    在安装或更新项目的 Pod 之后,请务必使用 Xcode 项目的 .xcworkspace 打开该项目。
  3. 在您的应用中导入 Firebase:

    Swift

    import Firebase

    Objective-C

    @import Firebase;

翻译文本字符串

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

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

    Swift

    // Create an English-German translator:
    let options = TranslatorOptions(sourceLanguage: .en, targetLanguage: .de)
    let englishGermanTranslator = NaturalLanguage.naturalLanguage().translator(options: options)
    

    Objective-C

    // Create an English-German translator:
    FIRTranslatorOptions *options =
        [[FIRTranslatorOptions alloc] initWithSourceLanguage:FIRTranslateLanguageEN
                                              targetLanguage:FIRTranslateLanguageDE];
    FIRTranslator *englishGermanTranslator =
        [[FIRNaturalLanguage naturalLanguage] translatorWithOptions:options];
    

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

  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

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

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

  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.
    }];
    

    机器学习套件将文本翻译为您配置的目标语言,然后将译文传递至完成处理程序。

显式管理翻译模型

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

如需获取设备上存储的翻译模型,请运行以下代码:

Swift

let localModels = ModelManager.modelManager().downloadedTranslateModels

Objective-C

NSSet<FIRTranslateRemoteModel *> *localModels =
    [FIRModelManager modelManager].downloadedTranslateModels;

如需删除模型,请运行以下代码:

Swift

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

Objective-C

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

如需下载模型,请运行以下代码:

Swift

// Download the French model.
let frModel = TranslateRemoteModel.translateRemoteModel(language: .fr)

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

如果您想通过 NotificationCenter 获取下载状态,请注册 firebaseMLModelDownloadDidSucceedfirebaseMLModelDownloadDidFail 的观察者。请务必在观察者块中使用对 self 的弱引用,因为下载可能需要一些时间,并且源对象可能到下载完成才会被释放。例如:

NotificationCenter.default.addObserver(
    forName: .firebaseMLModelDownloadDidSucceed,
    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 == frModel
        else { return }
    // The model was downloaded and is available on the device
}

NotificationCenter.default.addObserver(
    forName: .firebaseMLModelDownloadDidFail,
    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.
FIRModelDownloadConditions *conditions =
    [[FIRModelDownloadConditions alloc] initWithAllowsCellularAccess:NO
                                         allowsBackgroundDownloading:YES];
FIRTranslateRemoteModel *frModel =
    [FIRTranslateRemoteModel translateRemoteModelWithLanguage:FIRTranslateLanguageFR];

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

如果您想通过 NSNotificationCenter 获取下载状态,请注册 FIRModelDownloadDidSucceedNotificationFIRModelDownloadDidFailNotification 的观察者。请务必在观察者块中使用对 self 的弱引用,因为下载可能需要一些时间,并且源对象可能到下载完成才会被释放。

__block MyViewController *weakSelf = self;

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

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

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

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