I'm 5+ years of experience in building Mobile apps developer, I have worked on Android, and iOS projects
app/build.gradle
dependencies {
// ...
// Use this dependency to bundle the model with your app
implementation 'com.google.mlkit:language-id:17.0.1'
// Use this dependency to use the dynamically downloaded model in Google Play Services
implementation 'com.google.android.gms:play-services-mlkit-language-id:16.0.0-beta2'
// Use this dependency to use the translate text
implementation 'com.google.mlkit:translate:16.1.2'
}
AndroidManifest.xml
<application ...>
...
<meta-data
android:name="com.google.mlkit.vision.DEPENDENCIES"
android:value="langid" />
<!-- To use multiple models: android:value="langid,model2,model3" -->
</application>
LanguageIdentification
to identify the language of the body text. It can identify the language by either returning the language or by providing you with a set of languages. It is a simple function that takes a string as input and then provides an output string that is the language code in the input string. For example, for the input "Hello World" the function will return "en", which is English.LanguageIdentification.getClient().identifyLanguage("Hello World!")
.addOnSuccessListener { languageCode ->
when (languageCode) {
"en" -> { ... }
"und" -> Log.i("TAG", "Language: $languageCode")
else -> Log.i("TAG", "Can't identify language.")
}
}
LanguageIdentificationOptions
object to getClient()
:LanguageIdentification
.getClient(LanguageIdentificationOptions.Builder()
.setConfidenceThreshold(0.34f)
.build())
val frenchModel = TranslateRemoteModel.Builder(TranslateLanguage.FRENCH).build()
val modelManager = RemoteModelManager.getInstance()
modelManager.download(frenchModel, DownloadConditions.Builder().build())
// Create an English-French translator:
val options = TranslatorOptions.Builder()
.setSourceLanguage(TranslateLanguage.ENGLISH)
.setTargetLanguage(TranslateLanguage.FRENCH)
.build()
val englishFrenchTranslator = Translation.getClient(options)
var conditions = DownloadConditions.Builder()
.requireWifi() // download models only by wifi
.build()
englishFrenchTranslator.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.
// ...
}
modelManager.getDownloadedModels(TranslateRemoteModel::class.java)
.addOnSuccessListener { models ->
// ...
}
.addOnFailureListener {
// Error.
}
modelManager.deleteDownloadedModel(frenchModel)
translate():
englishFrenchTranslator.translate(text)
.addOnSuccessListener { translatedText ->
// Translation successful.
}
.addOnFailureListener { exception ->
// Error.
// ...
}