ZOFTINO.COM android and web dev tutorials

Identify Language of Text with Firebase API Android Example

This post explains how to build a feature in android app that identifies the language of given text. This example uses Firebase ML kit language identification API.

Identify Language of Text Example

The example allows user to enter text in any language and submit the text. The listener in the activity associated with the screen passes the text to Firebase ML language identification API and displays the identified language on the screen.

android language identifier exampleandroid language identifier firebase api example

Firebase ML language identification API

To use Firebase ML language identification API, first you need to instantiate FirebaseLanguageIdentification object by calling getLanguageIdentification() method on FirebaseNaturalLanguage.

    FirebaseLanguageIdentification languageIdentifier =
            FirebaseNaturalLanguage.getInstance().getLanguageIdentification();

Then you can get either a list of possible languages or just the most likely language. To get the most likely language, you need to call identifyLanguage() method on FirebaseLanguageIdentification object by passing the text for which the language needs to be identified and add listeners to the task. The most likely language will be passed to success listener. If language can’t be identified, then the language code will be und.

     languageIdentifier.identifyLanguage(text)
            .addOnSuccessListener(
                        new OnSuccessListener<String>() {
        @Override
        public void onSuccess(@Nullable String languageCode) {
            if (languageCode != "und") {
                Toast.makeText(LanActivity.this,
                        "Language "+languageCode,
                        Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(LanActivity.this,
                        "no language identified",
                        Toast.LENGTH_LONG).show();
            }
        }
    })
            .addOnFailureListener(
                        new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.d("lang id", "exception processing " + e);
        }
    });

To get a list of possible languages, you need to call identifyAllLanguages() on FirebaseLanguageIdentification object. A list of IdentifiedLanguage objects are passed to success listener. You can obtain language code and confidence from the IdentifiedLanguage object.

for (IdentifiedLanguage langs : identifiedLanguages) {
  String languageCode = langs.getLanguageCode();
  float confidenceVal = langs.getConfidence();
  //do somthing  
}

Project Setup

First you need to setup your project for using Firebase by following instructions listed here.

Then add Firebase and Firebase ML language identification API libraries to gradle build script.

implementation 'com.google.firebase:firebase-core:17.0.0'
implementation 'com.google.firebase:firebase-ml-natural-language:21.0.1'
implementation 'com.google.firebase:firebase-ml-natural-language-language-id-model:20.0.4'
implementation 'com.google.android.material:material:1.0.0-alpha1'

Activity

Button onClick event handler captures the text entered by user and passes it to the language identification api. The api returns BCP code of the language identified. Name of the language can be obtained by calling getDisplayLanguage() method on the Locale object which is created passing the BCP code to it. The name of the language identified for the entered text will be displayed in the text view.

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage;
import com.google.firebase.ml.naturallanguage.languageid.FirebaseLanguageIdentification;

import java.util.Locale;

public class LanguageIdentifierActivity extends AppCompatActivity {
    EditText text;
    TextView language;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_language_indentifier);

        text = findViewById(R.id.identify_text);
        language = findViewById(R.id.language);
    }

    public void identifyLanguage(View v) {
        String enteredText = text.getText().toString();
        identifyLanguageUsingFirebase(enteredText);
    }

    //identify language by passing the text using
    //firebase language identifier api
    public void identifyLanguageUsingFirebase(String text) {
        FirebaseLanguageIdentification languageIdentifier =
                FirebaseNaturalLanguage.getInstance().getLanguageIdentification();
        languageIdentifier.identifyLanguage(text)
                .addOnSuccessListener(
                        new OnSuccessListener<String>() {
                            @Override
                            public void onSuccess(@Nullable String languageCode) {
                                if (languageCode != "und") {
                                    //create Locale object to convert
                                    //BCP language code to language name
                                    Locale loc = new Locale(languageCode);
                                    language.setText("The text is in " + loc.getDisplayLanguage());
                                } else {
                                    Toast.makeText(LanguageIdentifierActivity.this,
                                            "Language could not be identified",
                                            Toast.LENGTH_LONG).show();
                                }
                            }
                        })
                .addOnFailureListener(
                        new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Log.e("Language id", "exception processing " + e);
                                Toast.makeText(LanguageIdentifierActivity.this,
                                        "Language could not be identified",
                                        Toast.LENGTH_LONG).show();
                            }
                        });
    }

}

Layout

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LanguageIdentifierActivity">
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:text="Identify Language"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/identify_text_l"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/title"
        android:hint="Enter Text">
        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/identify_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </com.google.android.material.textfield.TextInputLayout>
    <TextView
        android:id="@+id/language"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/identify_text_l"/>
    <Button
        android:id="@+id/identify_language"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Identify Language"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/language"
        android:onClick="identifyLanguage"
        style="@style/Widget.AppCompat.Button.Colored"/>
</androidx.constraintlayout.widget.ConstraintLayout>