DEV Community

HuaweiDevsLATAM
HuaweiDevsLATAM

Posted on

App básica de traducción con Huawei ML Kit

La traducción es una de las tecnologías de la nueva era que ayuda considerablemente al los usuarios cuando estos buscan comunicar o entender algo al encontrarse en el extranjeto o al colaborar con colegas que no hablan el mismo lenguaje. Con el ML kit de HMS es relativamente simple construir una app de traducción, así que: Let’s create an app!

ML kit provee APIs muy completas y de implementación sencilla. Con este kit podremos obtener una excelente app de traducción con poco esfuerzo durante el desarrollo.
Restricciones
Antes de comenzar a usar ML Kit, debes tener en cuenta lo siguiente:
Algunas de sus características funcionan únicamente en dispositivos Huawei
Las APIs de ML kit que requiren conexión a internet se cobrarán según el uso
La cuota gratuita de traducciones es de 500,000 caractéres
El costo por uso del API de traducción es de 15 euros por cada 1,000,000 de caractéres
Lenguajes soportados
Actualmente el API de traducción de ML kit soporta los siguientes lenguajes
Árabe
Danés
Alemán
Inglés
Español
Finlandés
Francés
Italiano
Japones
Coreano
Polaco
Portugués
Ruso
Sueco
Thaitiano
Turco
Chino
Chino Tradicional
Malayo
Norwego
Vietnamita
Indonesio
Checo
Hebreo
Griego
Hindi
Tagalog
Serbio
Rumano
Configuración básica de HMS
Inicia sesión en la consola de AppGallery Connect y sigue los siguientes pasos
Crea un proyecto
Agrega una app al proyecto
Habilita el API de ML kit
Agrega el SHA-256 Certificate Fingerprint a la consola de AGC
Descarga el archivo de configuración agconnect-services.json y agregalo a tu proyecto
Agrega el SDK de HMS Core a tu proyecto Android
Para más detalles, consulta la guía de inicio para crear una app con HMS.
Agregando el SDK de ML Kit
ML Kit cuenta con APIs para realizar la traducción online y offline, para ello es necesario agregar las siguientes dependencias.

dependencies{
// Real-Time Translation
implementation 'com.huawei.hms:ml-computer-translate:2.0.5.300'
// Import the base SDK.
implementation 'com.huawei.hms:ml-computer-translate:2.0.5.300'
// Import the translation algorithm package.
implementation 'com.huawei.hms:ml-computer-translate-model:2.0.5.300'
}
Enter fullscreen mode Exit fullscreen mode

Añade los permisos necesarios en el AndroidManifest

<manifest
...
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<meta-data
android:name="com.huawei.hms.ml.DEPENDENCY"
android:value= "translate"/>
...
</manifest>
Enter fullscreen mode Exit fullscreen mode

Traducción en tiempo real (online)
Usa la clase MLRemoteTranslateSetting para crear un traductor de tiempo real

// Create a text translator using custom parameter settings.
MLRemoteTranslateSetting setting = new MLRemoteTranslateSetting
.Factory()
// Set the source language code. The BCP-47 standard is used for Traditional Chinese, and the ISO 639-1 standard is used for other languages. This parameter is optional. If this parameter is not set, the system automatically detects the language.
.setSourceLangCode("zh")
// Set the target language code. The BCP-47 standard is used for Traditional Chinese, and the ISO 639-1 standard is used for other languages.
.setTargetLangCode("en")
.create();
MLRemoteTranslator mlRemoteTranslator = MLTranslatorFactory.getInstance().getRemoteTranslator(setting);
Enter fullscreen mode Exit fullscreen mode

Obtén los resultados de la traducción usando las APIs síncrona o asíncrona

//Sample code for calling the asynchronous method:
MLTranslateLanguage.getCloudAllLanguages().addOnSuccessListener(
new OnSuccessListener<Set<String>>() {
@Override
public void onSuccess(Set<String> result) {
// Languages supported by real-time translation are successfully obtained.
}
});
//Sample code for calling the synchronous method:
try {
Set<String> result = MLTranslateLanguage.syncGetCloudAllLanguages();
// Languages supported by real-time translation are successfully obtained.
} catch (MLException e) {
// Catch exceptions on languages supported for real-time translation.
}
Enter fullscreen mode Exit fullscreen mode

Llama al API de traducción (se recomienda el API asíncrona)

//Sample code for calling the asynchronous method:
// sourceText: text to be translated, with up to 5000 characters.
final Task<String> task = mlRemoteTranslator.asyncTranslate(sourceText);
task.addOnSuccessListener(new OnSuccessListener<String>() {
@Override
public void onSuccess(String text) {
// Processing logic for recognition success.
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// Processing logic for recognition failure.
try {
MLException mlException = (MLException)e;
// Obtain the result code. You can process the result code and customize respective messages displayed to users.
int errorCode = mlException.getErrCode();
// Obtain the error information. You can quickly locate the fault based on the result code.
String errorMessage = mlException.getMessage();
} catch (Exception error) {
// Handle the conversion error.
}
}
});
//Sample code for calling the synchronous method:
try {
String output = mlRemoteTranslator .syncTranslate(sourceText);
// Processing logic for recognition success.
} catch (MLException e) {
// Processing logic for detection failure.
// Obtain the result code. You can process the result code and customize respective messages displayed to users.
int errorCode = mlException.getErrCode();
// Obtain the error information. You can quickly locate the fault based on the result code.
String errorMessage = mlException.getMessage();
}
Enter fullscreen mode Exit fullscreen mode

Es importante liberar los recursos una vez que se obtengan los resultados

if (mlRemoteTranslator!= null) {
mlRemoteTranslator.stop();
}
Enter fullscreen mode Exit fullscreen mode

Traducción On Device (offline)
Usa la clase MLLocalTranslateSetting para crear un traductor offline

// Create an offline translator.
MLLocalTranslateSetting setting = new MLLocalTranslateSetting.Factory()
// Set the source language code, which complies with the ISO 639-1 standard. This parameter is mandatory. If this parameter is not set, an error may occur.
.setSourceLangCode("zh")
// Set the target language code, which complies with the ISO 639-1 standard. This parameter is mandatory. If this parameter is not set, an error may occur.
.setTargetLangCode("en")
.create();
final MLLocalTranslator mlLocalTranslator = MLTranslatorFactory.getInstance().getLocalTranslator(setting);
Enter fullscreen mode Exit fullscreen mode

La traducción offline también tiene un API síncrona y una asíncrona para obtener los resultados

//Sample code for calling the asynchronous method:
MLTranslateLanguage.getLocalAllLanguages().addOnSuccessListener(
new OnSuccessListener<Set<String>>() {
@Override
public void onSuccess(Set<String> result) {
// Languages supported by on-device translation are successfully obtained.
}
});
//Sample code for calling the synchronous method:
Set<String> result = MLTranslateLanguage.syncGetLocalAllLanguages();
Enter fullscreen mode Exit fullscreen mode

Los modelos pre entrenados de traducción se pueden descargar de 2 formas:
Método 1
Usa la clase MLLocalModelManager para descargar manualmente el paquete con el modelo pre entrenado.

// After the download is successful, translate text in the onSuccess callback.
// Obtain the model manager.
MLLocalModelManager manager = MLLocalModelManager.getInstance();
MLLocalTranslatorModel model = new MLLocalTranslatorModel.Factory(sourceLangCode).create();
// Set the model download policy.
MLModelDownloadStrategy downloadStrategy = new MLModelDownloadStrategy.Factory()
.needWifi() // It is recommended that you download the package in a Wi-Fi environment.
.create();
// Create a download progress listener.
MLModelDownloadListener modelDownloadListener = new MLModelDownloadListener() {
@Override
public void onProcess(long alreadyDownLength, long totalLength) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// Display the download progress or perform other operations.
}
});
}
};
// Download the model. After the model is downloaded, translate text in the onSuccess callback.
manager.downloadModel(model, downloadStrategy, modelDownloadListener).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
// Called when the model package is successfully downloaded.
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// Called when the model package fails to be downloaded.
}
});
Enter fullscreen mode Exit fullscreen mode

Método 2
Usa el API preparedModel para descargar el modelo automáticamente

// Set the model download policy.
MLModelDownloadStrategy downloadStrategy = new MLModelDownloadStrategy.Factory()
.needWifi() // It is recommended that you download the package in a Wi-Fi environment.
.create();
// Create a download progress listener.
MLModelDownloadListener modelDownloadListener = new MLModelDownloadListener() {
@Override
public void onProcess(long alreadyDownLength, long totalLength) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// Display the download progress or perform other operations.
}
});
}
};
mlLocalTranslator.preparedModel(downloadStrategy, modelDownloadListener).
addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess (Void aVoid){
// Called when the model package is successfully downloaded.
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure (Exception e){
// Called when the model package fails to be downloaded.
}
});
Enter fullscreen mode Exit fullscreen mode

Implementa los métodos de traducción

//Sample code for calling the asynchronous method:
// input is a string of less than 5000 characters.
final Task<String> task = mlLocalTranslator.asyncTranslate(input);
// Before translation, ensure that the models have been successfully downloaded.
task.addOnSuccessListener(new OnSuccessListener<String>() {
@Override
public void onSuccess(String s) {
// Processing logic for detection success.
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// Processing logic for detection failure.
}
});
//Sample code for calling the synchronous method:
try {
// input is a string of less than 5000 characters.
String output = mlLocalTranslator.syncTranslate(input);
// Processing logic for detection success.
} catch (MLException e) {
// Processing logic for detection failure.
}
Enter fullscreen mode Exit fullscreen mode

Borrando un paquete innecesario

// Obtain the model manager.
MLLocalModelManager manager = MLLocalModelManager.getInstance();
MLLocalTranslatorModel model = new MLLocalTranslatorModel
.Factory("zh") // Set the target language code for the model, which complies with the ISO 639-1 standard.
.create();
// Delete a model package.
manager.deleteModel(model).addOnSuccessListener(new OnSuccessListener<Void>() {
public void onSuccess(Void aVoid) {
// Called when the model package fails to be deleted.
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(Exception e) {
// Called when the model package fails to be deleted.
}
});
Enter fullscreen mode Exit fullscreen mode

Eso es todo!
Con estas APIs puedes crear fácilmete un app de traducción o agregar la funcionalidad de traducción a un app existente.

Top comments (0)