Skip to content

Commit

Permalink
Tweak Translate Demo.
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 408257771
Change-Id: I6a8f3848e6b4fec71f59f0bbee40ba7e9c27b363
  • Loading branch information
Google ML Kit authored and zhouyiself committed Jan 12, 2022
1 parent 59fadd8 commit cf3c16e
Show file tree
Hide file tree
Showing 7 changed files with 39 additions and 35 deletions.
10 changes: 5 additions & 5 deletions android/translate/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,17 @@ apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
compileSdkVersion 30
compileSdkVersion 31
defaultConfig {
applicationId 'com.google.mlkit.samples.nl.translate'
// The SDK only requires minSdkVersion 16. We are using minSdkVersion
// The SDK only requires minSdkVersion 19. We are using minSdkVersion
// 21 to make some code in the sample shorter.
minSdkVersion 21
targetSdkVersion 30
targetSdkVersion 31
multiDexEnabled true
versionCode 1
versionName "1.0"
setProperty("archivesBaseName", "mlkit_translate_sample")
setProperty("archivesBaseName", "nl-translate")
}

buildTypes {
Expand All @@ -37,7 +37,7 @@ android {

dependencies {
implementation project(':internal:chooserx')
implementation 'com.google.mlkit:translate:16.1.2'
implementation 'com.google.mlkit:translate:17.0.0'

// Those dependencies are not required by the SDK. They are used for the sample itself.
implementation 'androidx.core:core-ktx:1.3.0'
Expand Down
3 changes: 0 additions & 3 deletions android/translate/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@
android:versionCode="1"
android:versionName="v1">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<application
android:allowBackup="true"
android:icon="@drawable/logo_mlkit"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@
package com.google.mlkit.samples.nl.translate.java;

import android.annotation.SuppressLint;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.text.Editable;
Expand All @@ -35,6 +33,8 @@
import android.widget.ToggleButton;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.google.android.material.textfield.TextInputEditText;
import com.google.mlkit.samples.nl.translate.R;
import java.util.List;
Expand Down Expand Up @@ -117,10 +117,15 @@ public void onNothingSelected(AdapterView<?> parent) {
new View.OnClickListener() {
@Override
public void onClick(View v) {
String targetText = targetTextView.getText().toString();
setProgressText(targetTextView);
int sourceLangPosition = sourceLangSelector.getSelectedItemPosition();
sourceLangSelector.setSelection(targetLangSelector.getSelectedItemPosition());
targetLangSelector.setSelection(sourceLangPosition);

// Also update srcTextView with targetText
srcTextView.setText(targetText);
viewModel.sourceText.setValue(targetText);
}
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@
package com.google.mlkit.samples.nl.translate.java;

import android.app.Application;
import android.util.LruCache;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import android.util.LruCache;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.android.gms.tasks.Continuation;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
Expand Down Expand Up @@ -83,6 +83,7 @@ public void onComplete(@NonNull Task<String> task) {
translatedText.setValue(new ResultOrError(task.getResult(), null));
} else {
translatedText.setValue(new ResultOrError(null, task.getException()));
task.getException().printStackTrace();
}
// Update the list of downloaded models as more may have been
// automatically downloaded due to requested translation.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,15 @@ class TranslateFragment : Fragment() {
}
}
switchButton.setOnClickListener {
val targetText = targetTextView.text.toString()
setProgressText(targetTextView)
val sourceLangPosition = sourceLangSelector.selectedItemPosition
sourceLangSelector.setSelection(targetLangSelector.selectedItemPosition)
targetLangSelector.setSelection(sourceLangPosition)

// Also update srcTextView with targetText
srcTextView.setText(targetText)
viewModel.sourceText.setValue(targetText)
}

// Set up toggle buttons to delete or download remote models locally.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,11 @@
package com.google.mlkit.samples.nl.translate.kotlin

import android.app.Application
import android.util.LruCache
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import android.util.LruCache
import com.google.android.gms.tasks.OnCompleteListener
import com.google.android.gms.tasks.Task
import com.google.android.gms.tasks.Tasks
Expand Down Expand Up @@ -63,10 +63,7 @@ class TranslateViewModel(application: Application) : AndroidViewModel(applicatio
val availableModels = MutableLiveData<List<String>>()

// Gets a list of all available translation languages.
val availableLanguages: List<Language> = TranslateLanguage.getAllLanguages()
.map {
Language(it)
}
val availableLanguages: List<Language> = TranslateLanguage.getAllLanguages().map { Language(it) }

init {
// Create a translation result or error object.
Expand Down Expand Up @@ -98,18 +95,18 @@ class TranslateViewModel(application: Application) : AndroidViewModel(applicatio

// Updates the list of downloaded models available for local translation.
private fun fetchDownloadedModels() {
modelManager.getDownloadedModels(TranslateRemoteModel::class.java)
.addOnSuccessListener { remoteModels ->
availableModels.value =
remoteModels.sortedBy { it.language }.map { it.language }
}
modelManager.getDownloadedModels(TranslateRemoteModel::class.java).addOnSuccessListener {
remoteModels ->
availableModels.value = remoteModels.sortedBy { it.language }.map { it.language }
}
}

// Starts downloading a remote model for local translation.
internal fun downloadLanguage(language: Language) {
val model = getModel(TranslateLanguage.fromLanguageTag(language.code)!!)
modelManager.download(model, DownloadConditions.Builder().build())
.addOnCompleteListener { fetchDownloadedModels() }
modelManager.download(model, DownloadConditions.Builder().build()).addOnCompleteListener {
fetchDownloadedModels()
}
}

// Deletes a locally stored translation model.
Expand All @@ -127,10 +124,11 @@ class TranslateViewModel(application: Application) : AndroidViewModel(applicatio
}
val sourceLangCode = TranslateLanguage.fromLanguageTag(source.code)!!
val targetLangCode = TranslateLanguage.fromLanguageTag(target.code)!!
val options = TranslatorOptions.Builder()
.setSourceLanguage(sourceLangCode)
.setTargetLanguage(targetLangCode)
.build()
val options =
TranslatorOptions.Builder()
.setSourceLanguage(sourceLangCode)
.setTargetLanguage(targetLangCode)
.build()
return translators[options].downloadModelIfNeeded().continueWithTask { task ->
if (task.isSuccessful) {
translators[options].translate(text)
Expand All @@ -143,14 +141,12 @@ class TranslateViewModel(application: Application) : AndroidViewModel(applicatio
}
}

/**
* Holds the result of the translation or any error.
*/
/** Holds the result of the translation or any error. */
inner class ResultOrError(var result: String?, var error: Exception?)

/**
* Holds the language code (i.e. "en") and the corresponding localized full language name
* (i.e. "English")
* Holds the language code (i.e. "en") and the corresponding localized full language name (i.e.
* "English")
*/
class Language(val code: String) : Comparable<Language> {

Expand Down
2 changes: 1 addition & 1 deletion android/translate/app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ML Kit - Translate</string>
<string name="app_name">MLKit-Translate</string>
<string name="translated_text_hint">Translated text</string>
<string name="downloaded_models_label">Downloaded models: %1$s</string>
<string name="translate_progress">Translating&#8230;</string>
Expand Down

0 comments on commit cf3c16e

Please sign in to comment.