Lingua alternatives and similar libraries
Based on the "Natural Language Processing" category
Do you think we are missing an alternative of Lingua or a related project?
- this library tries to solve language detection of very short words and phrases, even shorter than tweets
- makes use of both statistical and rule-based approaches
- outperforms Apache Tika, Apache OpenNLP and Optimaize Language Detector for more than 60 languages
- works within every Java 6+ application and on Android
- no additional training of language models necessary
- offline usage without having to connect to an external service or API
* can be used in a REPL for a quick try-out
Table of Contents
- What does this library do?
- Why does this library exist?
- Which languages are supported?
- How good is it?
- Why is it better than other libraries?
- Test report generation
- How to add it to your project?
7.1 Using Gradle
7.2 Using Maven
- How to build?
- How to use?
9.1 Programmatic use
9.2 Standalone mode
- Do you want to contribute?
- What's next for upcoming versions?
1. What does this library do? Top ▲
Its task is simple: It tells you which language some provided textual data is written in. This is very useful as a preprocessing step for linguistic data in natural language processing applications such as text classification and spell checking. Other use cases, for instance, might include routing e-mails to the right geographically located customer service department, based on the e-mails' languages.
2. Why does this library exist? Top ▲
Language detection is often done as part of large machine learning frameworks or natural language processing applications. In cases where you don't need the full-fledged functionality of those systems or don't want to learn the ropes of those, a small flexible library comes in handy.
So far, three other comprehensive open source libraries working on the JVM for this task are Apache Tika, Apache OpenNLP and Optimaize Language Detector. Unfortunately, especially the latter has three major drawbacks:
- Detection only works with quite lengthy text fragments. For very short text snippets such as Twitter messages, it doesn't provide adequate results.
- The more languages take part in the decision process, the less accurate are the detection results.
- Configuration of the library is quite cumbersome and requires some knowledge about the statistical methods that are used internally.
Lingua aims at eliminating these problems. It nearly doesn't need any configuration and yields pretty accurate results on both long and short text, even on single words and phrases. It draws on both rule-based and statistical methods but does not use any dictionaries of words. It does not need a connection to any external API or service either. Once the library has been downloaded, it can be used completely offline.
3. Which languages are supported? Top ▲
Compared to other language detection libraries, Lingua's focus is on quality over quantity, that is, getting detection right for a small set of languages first before adding new ones. Currently, the following 66 languages are supported:
4. How good is it? Top ▲
Lingua is able to report accuracy statistics for some bundled test data available for each supported language. The test data for each language is split into three parts:
- a list of single words with a minimum length of 5 characters
- a list of word pairs with a minimum length of 10 characters
- a list of complete grammatical sentences of various lengths
Both the language models and the test data have been created from separate documents of the Wortschatz corpora offered by Leipzig University, Germany. Data crawled from various news websites have been used for training, each corpus comprising one million sentences. For testing, corpora made of arbitrarily chosen websites have been used, each comprising ten thousand sentences. From each test corpus, a random unsorted subset of 1000 single words, 1000 word pairs and 1000 sentences has been extracted, respectively.
Given the generated test data, I have compared the detection results of Lingua, Apache Tika, Apache OpenNLP and Optimaize Language Detector using parameterized JUnit tests running over the data of 66 languages. Bokmal, Latin and Nynorsk are currently only supported by Apache OpenNLP and Lingua. For the other two classifiers, Bokmal and Nynorsk are both mapped to Norwegian. Apache OpenNLP does not allow to restrict the set of languages that take part in the decision process. So this classifier might theoretically return one of its 103 supported languages as its result. Apache Tika and Optimaize Language Detector have been configured so that the set of examinable languages is equal to the set supported by Lingua. This restriction makes the detection results more comparable to each other.
The box plot below shows the distribution of the averaged accuracy values for all three performed tasks: Single word detection, word pair detection and sentence detection. Lingua clearly outperforms its contenders. Bar plots for each language and further box plots for the separate detection tasks can be found in the file ACCURACY_PLOTS.md. Detailed statistics including mean, median and standard deviation values for each language and classifier are available in the file ACCURACY_TABLE.md.
5. Why is it better than other libraries? Top ▲
Every language detector uses a probabilistic n-gram model trained on the character distribution in some training corpus. Most libraries only use n-grams of size 3 (trigrams) which is satisfactory for detecting the language of longer text fragments consisting of multiple sentences. For short phrases or single words, however, trigrams are not enough. The shorter the input text is, the less n-grams are available. The probabilities estimated from such few n-grams are not reliable. This is why Lingua makes use of n-grams of sizes 1 up to 5 which results in much more accurate prediction of the correct language.
A second important difference is that Lingua does not only use such a statistical model, but also a rule-based engine. This engine first determines the alphabet of the input text and searches for characters which are unique in one or more languages. If exactly one language can be reliably chosen this way, the statistical model is not necessary anymore. In any case, the rule-based engine filters out languages that do not satisfy the conditions of the input text. Only then, in a second step, the probabilistic n-gram model is taken into consideration. This makes sense because loading less language models means less memory consumption and better runtime performance.
In general, it is always a good idea to restrict the set of languages to be considered in the classification process using the respective api methods. If you know beforehand that certain languages are never to occur in an input text, do not let those take part in the classifcation process. The filtering mechanism of the rule-based engine is quite good, however, filtering based on your own knowledge of the input text is always preferable.
6. Test report and plot generation Top ▲
If you want to reproduce the accuracy results above, you can generate the test reports yourself for all four classifiers and all languages by doing:
You can also restrict the classifiers and languages to generate reports for by passing arguments to the Gradle task. The following task generates reports for Lingua and the languages English and German only:
./gradlew writeAccuracyReports -Pdetectors=Lingua -Planguages=English,German
By default, only a single CPU core is used for report generation. If you have a multi-core CPU in your machine, you can fork as many processes as you have CPU cores. This speeds up report generation significantly. However, be aware that forking more than one process can consume a lot of RAM. You do it like this:
./gradlew writeAccuracyReports -PcpuCores=2
For each detector and language, a test report file is then written into
/accuracy-reports, to be found next to the
As an example, here is the current output of the Lingua German report:
com.github.pemistahl.lingua.report.lingua.GermanDetectionAccuracyReport ##### GERMAN ##### >>> Accuracy on average: 89,47% >> Detection of 1000 single words (average length: 9 chars) Accuracy: 74,30% Erroneously classified as LATIN: 2,40%, DUTCH: 2,40%, ENGLISH: 2,20%, DANISH: 2,20%, NORWEGIAN: 1,90%, ITALIAN: 1,40%, ESPERANTO: 1,30%, SWEDISH: 1,20%, BASQUE: 1,20%, FRENCH: 1,20%, AFRIKAANS: 0,90%, WELSH: 0,80%, PORTUGUESE: 0,60%, ESTONIAN: 0,60%, FINNISH: 0,50%, SPANISH: 0,40%, TAGALOG: 0,40%, IRISH: 0,40%, ICELANDIC: 0,40%, POLISH: 0,40%, SOMALI: 0,30%, TURKISH: 0,30%, ALBANIAN: 0,30%, CATALAN: 0,30%, BOSNIAN: 0,30%, LITHUANIAN: 0,20%, INDONESIAN: 0,20%, LATVIAN: 0,20%, SLOVAK: 0,20%, CROATIAN: 0,20%, ROMANIAN: 0,20%, MALAY: 0,10%, SLOVENE: 0,10% >> Detection of 1000 word pairs (average length: 18 chars) Accuracy: 94,40% Erroneously classified as DUTCH: 0,90%, LATIN: 0,80%, ENGLISH: 0,70%, SWEDISH: 0,60%, DANISH: 0,60%, FRENCH: 0,40%, NORWEGIAN: 0,30%, TURKISH: 0,20%, TAGALOG: 0,20%, WELSH: 0,20%, IRISH: 0,20%, ESTONIAN: 0,10%, FINNISH: 0,10%, ITALIAN: 0,10%, ICELANDIC: 0,10%, AFRIKAANS: 0,10% >> Detection of 1000 sentences (average length: 111 chars) Accuracy: 99,70% Erroneously classified as DUTCH: 0,20%, LATIN: 0,10%
The plots have been created with Python and the libraries Pandas, Matplotlib and Seaborn. If you have a global Python 3 installation and the
python3 command available on your command line, you can redraw the plots after modifying the test reports by executing the following Gradle task:
The detailed table in the file ACCURACY_TABLE.md containing all accuracy values can be written with:
7. How to add it to your project? Top ▲
7.1 Using Gradle
// Groovy syntax implementation 'com.github.pemistahl:lingua:0.6.0' // Kotlin syntax implementation("com.github.pemistahl:lingua:0.6.0")
7.2 Using Maven
<dependency> <groupId>com.github.pemistahl</groupId> <artifactId>lingua</artifactId> <version>0.6.0</version> </dependency>
8. How to build? Top ▲
Lingua uses Gradle to build.
git clone https://github.com/pemistahl/lingua.git cd lingua ./gradlew build
Several jar archives can be created from the project.
lingua-0.6.0.jarcontaining the compiled sources only.
lingua-0.6.0-sources.jarcontaining the plain source code.
lingua-0.6.0-with-dependencies.jarcontaining the compiled sources and all external dependencies needed at runtime. This jar file can be included in projects without dependency management systems. You should be able to use it in your Android project as well by putting it in your project's
libfolder. This jar file can also be used to run Lingua in standalone mode (see below).
9. How to use? Top ▲
Lingua can be used programmatically in your own code or in standalone mode.
9.1 Programmatic use Top ▲
The API is pretty straightforward and can be used in both Kotlin and Java code.
/* Kotlin */ import com.github.pemistahl.lingua.api.LanguageDetectorBuilder import com.github.pemistahl.lingua.api.LanguageDetector import com.github.pemistahl.lingua.api.Language import com.github.pemistahl.lingua.api.Language.* import com.github.pemistahl.lingua.api.IsoCode639_1 import com.github.pemistahl.lingua.api.IsoCode639_3 val detector: LanguageDetector = LanguageDetectorBuilder.fromLanguages(ENGLISH, FRENCH, GERMAN, SPANISH).build() val detectedLanguage: Language = detector.detectLanguageOf(text = "languages are awesome") // ENGLISH
By default, Lingua returns the most likely language for a given input text. However, there are certain words that are spelled the same in more than one language. The word prologue, for instance, is both a valid English and French word. Lingua would output either English or French which might be wrong in the given context. For cases like that, it is possible to specify a minimum relative distance that the logarithmized and summed up probabilities for each possible language have to satisfy. It can be stated in the following way:
val detector = LanguageDetectorBuilder .fromAllBuiltInLanguages() .withMinimumRelativeDistance(0.25) // minimum: 0.00 maximum: 0.99 default: 0.00 .build()
Be aware that the distance between the language probabilities is dependent on the length of the input text. The longer the input text, the larger the distance between the languages. So if you want to classify very short text phrases, do not set the minimum relative distance too high. Otherwise you will get most results returned as
Language.UNKNOWN which is the return value for cases where language detection is not reliably possible.
The public API of Lingua never returns
null somewhere, so it is safe to be used from within Java code as well.
/* Java */ import java.util.List; import static com.github.pemistahl.lingua.api.Language.*; import com.github.pemistahl.lingua.api.*; final LanguageDetector detector = LanguageDetectorBuilder.fromLanguages(ENGLISH, FRENCH, GERMAN, SPANISH).build(); final Language detectedLanguage = detector.detectLanguageOf("languages are awesome");
There might be classification tasks where you know beforehand that your language data is definitely not written in Latin, for instance (what a surprise :-). The detection accuracy can become better in such cases if you exclude certain languages from the decision process or just explicitly include relevant languages:
// include all languages available in the library // WARNING: in the worst case this produces high memory // consumption and slow runtime performance LanguageDetectorBuilder.fromAllBuiltInLanguages() // include only languages that are not yet extinct (= currently excludes Latin) LanguageDetectorBuilder.fromAllBuiltInSpokenLanguages() // exclude the Spanish language from the decision algorithm LanguageDetectorBuilder.fromAllBuiltInLanguagesWithout(Language.SPANISH) // only decide between English and German LanguageDetectorBuilder.fromLanguages(Language.ENGLISH, Language.GERMAN) // select languages by ISO 639-1 code LanguageDetectorBuilder.fromIsoCodes639_1(IsoCode639_1.EN, IsoCode639_3.DE) // select languages by ISO 639-3 code LanguageDetectorBuilder.fromIsoCodes639_3(IsoCode639_3.ENG, IsoCode639_3.DEU)
9.2 Standalone mode Top ▲
If you want to try out Lingua before you decide whether to use it or not, you can run it in a REPL and immediately see its detection results.
- With Gradle:
./gradlew runLinguaOnConsole --console=plain
- Without Gradle:
java -jar lingua-0.6.0-with-dependencies.jar
Then just play around:
This is Lingua. Select the language models to load. 1: enter language iso codes manually 2: all supported languages Type a number and press <Enter>. Type :quit to exit. > 1 List some language iso 639-1 codes separated by spaces and press <Enter>. Type :quit to exit. > en fr de es Loading language models... Done. 4 language models loaded lazily. Type some text and press <Enter> to detect its language. Type :quit to exit. > languages ENGLISH > Sprachen GERMAN > langues FRENCH > :quit Bye! Ciao! Tschüss! Salut!
10. Do you want to contribute? Top ▲
In case you want to contribute something to Lingua, then I encourage you to do so. Do you have ideas for improving the API? Are there some specific languages that you want to have supported early? Or have you found any bugs so far? Feel free to open an issue or send a pull request. It's very much appreciated. :-)
11. What's next for upcoming versions? Top ▲
- languages, languages, even more languages :-)
- accuracy improvements
- more unit tests
- API documentation
- for version 1.0.0: public API stability, multiplatform support
*Note that all licence references and agreements mentioned in the Lingua README section above are relevant to that project's source code only.