您可以使用机器学习套件在语言之间翻译文本。机器学习套件 可以在超过 50 种语言。
试试看
- 您可以试用示例应用, 请查看此 API 的用法示例。
准备工作
- 在 Podfile 中添加以下机器学习套件 Pod:
pod 'GoogleMLKit/Translate', '3.2.0'
- 安装或更新项目的 Pod 之后,使用 Xcode 项目的
.xcworkspace
。Xcode 12.4 或更高版本支持机器学习套件。
翻译文本字符串
如需在两种语言之间翻译字符串,请执行以下操作:
创建一个
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];
如果您不知道输入文本的语言,则可以使用语言 Identification API 会给出一个语言标记。然后将语言标记转换为 机器学习套件枚举。代码取决于您使用的语言:
- Swift:调用
TranslateLanguage.fromLanguageTag()
以获取TranslateLanguage
- Objective-C:调用
MLKTranslateLanguageForLanguageTag()
以获取MLKTranslateLanguage
避免同时在设备上保留过多语言模型。
- Swift:调用
确保已将所需的翻译模型下载到设备上。 确信模型可用之后,再调用
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 下载应用。您 应该删除不再需要的模型。 请参阅显式管理翻译模型。
确认模型已下载后,将文本字符串传递给 将源语言设置为
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. }];
机器学习套件会将文本翻译成您配置的目标语言, 将译文传递给完成处理程序。
译者生命周期由 ARC(自动引用计数)控制, 这是推荐用于 iOS 开发的惯例。开发者可以 所有强引用均移除所有后要取消分配的译者。
译者在内存中加载时可能会占用 30MB-150MB。开发者应 在创建并发机制时,要考虑到设备/应用的内存预算 翻译实例,并避免在设备上保留过多语言模型 。
显式管理翻译模型
当您按上述说明使用 Translation API 时,机器学习套件会自动 根据需要将特定语言的翻译模型下载到设备。您 还可以明确管理您希望在集群上提供的 使用机器学习套件的翻译模型管理 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
的下载状态,请注册
mlkitModelDownloadDidSucceed
和
mlkitModelDownloadDidFail
。请务必使用对 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
的下载状态,请注册
MLKModelDownloadDidSucceedNotification
和
MLKModelDownloadDidFailNotification
。请务必使用弱引用
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]; }];