您可以使用机器学习套件实现语言之间的文本互译。机器学习套件可以在 50 多种语言之间互译。
试试看
- 试用示例应用,了解此 API 的使用示例。
准备工作
- 请务必在项目级
build.gradle
文件中的buildscript
和allprojects
部分添加 Google 的 Maven 代码库。 - 将 Android 版机器学习套件库的依赖项添加到模块的应用级 Gradle 文件(通常为
app/build.gradle
):dependencies { // ... implementation 'com.google.mlkit:translate:17.0.3' }
翻译文本字符串
如需在两种语言之间翻译字符串,请执行以下操作:
创建一个
Translator
对象,并使用源语言和目标语言对其进行配置:Kotlin
// Create an English-German translator: val options = TranslatorOptions.Builder() .setSourceLanguage(TranslateLanguage.ENGLISH) .setTargetLanguage(TranslateLanguage.GERMAN) .build() val englishGermanTranslator = Translation.getClient(options)
Java
// Create an English-German translator: TranslatorOptions options = new TranslatorOptions.Builder() .setSourceLanguage(TranslateLanguage.ENGLISH) .setTargetLanguage(TranslateLanguage.GERMAN) .build(); final Translator englishGermanTranslator = Translation.getClient(options);
如果您不知道输入文本的语言,可以使用语言识别 API,它会为您提供语言标记。然后,使用
TranslateLanguage.fromLanguageTag()
将标记转换为TranslateLanguage
。避免在设备上同时保留太多语言模型。
确保已将所需的翻译模型下载到设备上。 确信模型可用之后,再调用
translate()
。Kotlin
var conditions = DownloadConditions.Builder() .requireWifi() .build() englishGermanTranslator.downloadModelIfNeeded(conditions) .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. // ... }
Java
DownloadConditions conditions = new DownloadConditions.Builder() .requireWifi() .build(); englishGermanTranslator.downloadModelIfNeeded(conditions) .addOnSuccessListener( new OnSuccessListener
() { @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. // ... } }); 语言模型大小约为 30 MB,因此若非必要,请勿下载。此外,除非用户另行指定,否则应仅使用 Wi-Fi 下载语言模型。您还应删除不需要的模型。 请参阅显式管理翻译模型。
确认模型已下载后,将源语言的文本字符串传递至
translate()
:Kotlin
englishGermanTranslator.translate(text) .addOnSuccessListener { translatedText -> // Translation successful. } .addOnFailureListener { exception -> // Error. // ... }
Java
englishGermanTranslator.translate(text) .addOnSuccessListener( new OnSuccessListener
() { @Override public void onSuccess(@NonNull String translatedText) { // Translation successful. } }) .addOnFailureListener( new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Error. // ... } }); 采用配置的目标语言的译文即会传递给成功监听器。
确保在不再使用
Translator
对象时调用close()
方法。如果您要在 fragment 或 AppCompatActivity 中使用 Translator,一种简单的方法是在 fragment 或 AppCompatActivity 上调用 LifecycleOwner.getLifecycle(),然后调用 Lifecycle.addObserver。例如:
Kotlin
val options = ... val translator = Translation.getClient(options) getLifecycle().addObserver(translator)
Java
TranslatorOptions options = ... Translator translator = Translation.getClient(options); getLifecycle().addObserver(translator); ... use translator ...
请注意,这假定代码位于实现 LifecycleOwner 的类(例如 Fragment 或 AppCompatActivity)内。
显式管理翻译模型
在您按上文所述使用翻译 API 时,机器学习套件会根据需要自动将特定语言的翻译模型下载到设备。您还可以使用机器学习套件的翻译模型管理 API 来显式管理设备上可用的翻译模型。如果您想提前下载模型或从设备中删除不需要的模型,此方法会非常有用。
Kotlin
val modelManager = RemoteModelManager.getInstance() // Get translation models stored on the device. modelManager.getDownloadedModels(TranslateRemoteModel::class.java) .addOnSuccessListener { models -> // ... } .addOnFailureListener { // Error. } // Delete the German model if it's on the device. val germanModel = TranslateRemoteModel.Builder(TranslateLanguage.GERMAN).build() modelManager.deleteDownloadedModel(germanModel) .addOnSuccessListener { // Model deleted. } .addOnFailureListener { // Error. } // Download the French model. val frenchModel = TranslateRemoteModel.Builder(TranslateLanguage.FRENCH).build() val conditions = DownloadConditions.Builder() .requireWifi() .build() modelManager.download(frenchModel, conditions) .addOnSuccessListener { // Model downloaded. } .addOnFailureListener { // Error. }
Java
RemoteModelManager modelManager = RemoteModelManager.getInstance(); // Get translation models stored on the device. modelManager.getDownloadedModels(TranslateRemoteModel.class) .addOnSuccessListener(new OnSuccessListener<Set>() { @Override public void onSuccess(Set models) { // ... } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Error. } }); // Delete the German model if it's on the device. TranslateRemoteModel germanModel = new TranslateRemoteModel.Builder(TranslateLanguage.GERMAN).build(); modelManager.deleteDownloadedModel(germanModel) .addOnSuccessListener(new OnSuccessListener () { @Override public void onSuccess(Void v) { // Model deleted. } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Error. } }); // Download the French model. TranslateRemoteModel frenchModel = new TranslateRemoteModel.Builder(TranslateLanguage.FRENCH).build(); DownloadConditions conditions = new DownloadConditions.Builder() .requireWifi() .build(); modelManager.download(frenchModel, conditions) .addOnSuccessListener(new OnSuccessListener () { @Override public void onSuccess(Void v) { // Model downloaded. } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Error. } });