├── .gitignore ├── LICENSE ├── README.md ├── benchmarks ├── bench.html ├── big-test.txt ├── sentences.txt ├── single-words.txt ├── tweets.txt └── word-pairs.txt ├── demo.html ├── minified ├── README.md ├── eld.M60.min.js ├── eld.M60.min.js.gz ├── eld.XS60.min.js └── eld.XS60.min.js.gz ├── misc ├── sentences-tests-avg-js.png ├── table_accuracy_js.svg └── table_time_js.svg ├── package.json ├── src ├── LanguageResult.js ├── avgScore.js ├── dictionary.js ├── isoLanguages.js ├── languageData.js ├── languageDetector.js ├── ngrams │ ├── ngramsL60.js │ ├── ngramsM60.js │ ├── ngramsS60.js │ └── ngramsXS60.js ├── regexPatterns.js └── saveLanguageSubset.dev.js └── tests ├── testRunner.js ├── tests.html └── tests.js /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2023 Nito T.M. 191 | Author URL: https://github.com/nitotm 192 | 193 | Licensed under the Apache License, Version 2.0 (the "License"); 194 | you may not use this file except in compliance with the License. 195 | You may obtain a copy of the License at 196 | 197 | http://www.apache.org/licenses/LICENSE-2.0 198 | 199 | Unless required by applicable law or agreed to in writing, software 200 | distributed under the License is distributed on an "AS IS" BASIS, 201 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 202 | See the License for the specific language governing permissions and 203 | limitations under the License. 204 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Efficient Language Detector 2 | 3 |
4 | 5 | ![supported Javascript versions](https://img.shields.io/badge/JS-%3E%3D%20ES2015-blue) 6 | ![supported Javascript versions](https://img.shields.io/badge/Node.js-%3E%3D%2016-blue) 7 | [![license](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0) 8 | [![supported languages](https://img.shields.io/badge/supported%20languages-60-brightgreen.svg)](#languages) 9 | 10 |
11 | 12 | Efficient language detector (*Nito-ELD* or *ELD*) is a fast and accurate language detector, is one of the fastest non compiled detectors, while its accuracy is within the range of the heaviest and slowest detectors. 13 | 14 | It's 100% Javascript (vanilla), easy installation and no dependencies. 15 | ELD is also available in [Python](https://github.com/nitotm/efficient-language-detector-py) and [PHP](https://github.com/nitotm/efficient-language-detector). 16 | 17 | 1. [Install](#install) 18 | 2. [How to use](#how-to-use) 19 | 3. [Benchmarks](#benchmarks) 20 | 4. [Languages](#languages) 21 | 22 | ## Install 23 | 24 | - For *Node.js* 25 | ```bash 26 | $ npm install eld 27 | ``` 28 | - For Web, just download or clone the files 29 | `git clone https://github.com/nitotm/efficient-language-detector-js` 30 | 31 | ## How to use? 32 | 33 | ### Load ELD 34 | 35 | - At Node.js REPL 36 | ```javascript 37 | const { eld } = await import('eld') 38 | ``` 39 | - At Node.js 40 | ```javascript 41 | import { eld } from 'eld' // use .mjs extension for version <18 42 | ``` 43 | - At the Web Browser 44 | 45 | ```html 46 | 47 | 51 | ``` 52 | - To load the minified version, which is not a module 53 | ```html 54 | 55 | ``` 56 | 57 | ### Usage 58 | 59 | `detect()` expects a UTF-8 string, and returns an object, with a 'language' variable, with a ISO 639-1 code or empty string 60 | ```javascript 61 | console.log( eld.detect('Hola, cómo te llamas?') ) 62 | // { language: 'es', getScores(): {'es': 0.5, 'et': 0.2}, isReliable(): true } 63 | // returns { language: string, getScores(): Object, isReliable(): boolean } 64 | 65 | console.log( eld.detect('Hola, cómo te llamas?').language ) 66 | // 'es' 67 | ``` 68 | - To reduce the languages to be detected, there are 2 options, they only need to be executed once. (Check available [languages](#languages) below) 69 | ```javascript 70 | let langSubset = ['en', 'es', 'fr', 'it', 'nl', 'de'] 71 | 72 | // Option 1 73 | // Setting dynamicLangSubset(), detect() executes normally but finally filters the excluded languages 74 | eld.dynamicLangSubset(langSubset) // Returns an Object with the validated languages of the subset 75 | // to remove the subset 76 | eld.dynamicLangSubset(false) 77 | 78 | // Option 2 79 | // The optimal way to regularly use the same subset, is using saveSubset() to download a new database 80 | eld.saveSubset(langSubset) // ONLY for the Web Browser, and not included at minified files 81 | // We can load any Ngrams database saved at src/ngrams/, including subsets. Returns true if success 82 | await eld.loadNgrams('ngramsL60.js') // eld.loadNgrams('file').then((loaded) => { if (loaded) { } }) 83 | // To modify the preloaded database, edit the filename loadNgrams('filename') at languageDetector.js 84 | ``` 85 | - Also, we can get the current status of eld: languages, database type and subset 86 | ```javascript 87 | console.log( eld.info() ) 88 | ``` 89 | ## Benchmarks 90 | 91 | I compared *ELD* with a different variety of detectors, since the interesting part is the algorithm. 92 | 93 | | URL | Version | Language | 94 | |:----------------------------------------------------------|:--------------|:-------------| 95 | | https://github.com/nitotm/efficient-language-detector-js/ | 0.9.0 | Javascript | 96 | | https://github.com/nitotm/efficient-language-detector/ | 1.0.0 | PHP | 97 | | https://github.com/pemistahl/lingua-py | 1.3.2 | Python | 98 | | https://github.com/CLD2Owners/cld2 | Aug 21, 2015 | C++ | 99 | | https://github.com/google/cld3 | Aug 28, 2020 | C++ | 100 | | https://github.com/wooorm/franc | 6.1.0 | Javascript | 101 | 102 | Benchmarks: **Tweets**: *760KB*, short sentences of 140 chars max.; **Big test**: *10MB*, sentences in all 60 languages supported; **Sentences**: *8MB*, this is the *Lingua* sentences test, minus unsupported languages. 103 | Short sentences is what *ELD* and most detectors focus on, as very short text is unreliable, but I included the *Lingua* **Word pairs** *1.5MB*, and **Single words** *880KB* tests to see how they all compare beyond their reliable limits. 104 | 105 | These are the results, first, accuracy and then execution time. 106 | 107 | 119 | accuracy table 120 | 121 | 134 | time table 135 | 136 | 1. Lingua could have a small advantage as it participates with 54 languages, 6 less. 137 | 2. CLD2 and CLD3, return a list of languages, the ones not included in this test where discarded, but usually they return one language, I believe they have a disadvantage. 138 | Also, I confirm the results of CLD2 for short text are correct, contrary to the test on the *Lingua* page, they did not use the parameter "bestEffort = True", their benchmark for CLD2 is unfair. 139 | 140 | *Lingua* is the average accuracy winner, but at what cost, the same test that in *ELD* or *CLD2* is below 6 seconds, in Lingua takes more than 5 hours! It acts like a brute-force software. 141 | Also, its lead comes from single and pair words, which are unreliable regardless. 142 | 143 | I added *ELD-L* for comparison, which has a 2.3x bigger database, but only increases execution time marginally, a testament to the efficiency of the algorithm. *ELD-L* is not the main database as it does not improve language detection in sentences. 144 | 145 | For a client side solution, I included an all-in-one detector+Ngrams minified file, of the standard version (M), and XS which still performs great for sentences. 146 | The XS version only weights 865kb, when gzipped it's only 245kb. The standard version is 486kb gzipped. 147 | 148 | Here is the average, per benchmark, of Tweets, Big test & Sentences. 149 | 150 | ![Sentences tests average](https://raw.githubusercontent.com/nitotm/efficient-language-detector-js/main/misc/sentences-tests-avg-js.png) 151 | 162 | 163 | ## Languages 164 | 165 | These are the *ISO 639-1 codes* of the 60 supported languages for *Nito-ELD* v1 166 | 167 | > 'am', 'ar', 'az', 'be', 'bg', 'bn', 'ca', 'cs', 'da', 'de', 'el', 'en', 'es', 'et', 'eu', 'fa', 'fi', 'fr', 'gu', 'he', 'hi', 'hr', 'hu', 'hy', 'is', 'it', 'ja', 'ka', 'kn', 'ko', 'ku', 'lo', 'lt', 'lv', 'ml', 'mr', 'ms', 'nl', 'no', 'or', 'pa', 'pl', 'pt', 'ro', 'ru', 'sk', 'sl', 'sq', 'sr', 'sv', 'ta', 'te', 'th', 'tl', 'tr', 'uk', 'ur', 'vi', 'yo', 'zh' 168 | 169 | 170 | Full name languages: 171 | 172 | > Amharic, Arabic, Azerbaijani (Latin), Belarusian, Bulgarian, Bengali, Catalan, Czech, Danish, German, Greek, English, Spanish, Estonian, Basque, Persian, Finnish, French, Gujarati, Hebrew, Hindi, Croatian, Hungarian, Armenian, Icelandic, Italian, Japanese, Georgian, Kannada, Korean, Kurdish (Arabic), Lao, Lithuanian, Latvian, Malayalam, Marathi, Malay (Latin), Dutch, Norwegian, Oriya, Punjabi, Polish, Portuguese, Romanian, Russian, Slovak, Slovene, Albanian, Serbian (Cyrillic), Swedish, Tamil, Telugu, Thai, Tagalog, Turkish, Ukrainian, Urdu, Vietnamese, Yoruba, Chinese 173 | 174 | 175 | ## Future improvements 176 | 177 | - Train from bigger datasets, and more languages. 178 | - The tokenizer could separate characters from languages that have their own alphabet, potentially improving accuracy and reducing the N-grams database. Retraining and testing is needed. 179 | 180 | **Donate / Hire** 181 | If you wish to Donate for open source improvements, Hire me for private modifications / upgrades, or to Contact me, use the following link: https://linktr.ee/nitotm -------------------------------------------------------------------------------- /benchmarks/bench.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Benchmark 8 | 9 | 10 |
11 |

Benchmark

12 |
See results at the console.
13 |
14 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /demo.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Demo 8 | 9 | 10 |
11 |

Demo

12 |
See results at the console.
13 |
14 | 15 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /minified/README.md: -------------------------------------------------------------------------------- 1 | ### Process used to create minified version 2 | 3 | - Disable saveLanguageSubset.dev.js `import` at languageDetector.js 4 | - Remove function/export of `saveSubset()` at languageDetector.js 5 | - Remove public scope of `loadNgrams()`, from `const eld` at languageDetector.js (Optional) 6 | - Remove `loadNgrams('ngramsM60.js')` at languageDetector.js 7 | - Enable `import { ngramsData }` at languageData.js 8 | - Enable setNgrams(ngramsData) at languageData.js 9 | - Change `export { eld }` to `export { eld as default }` at languageDetector.js 10 | - Bundle code with Rollup: `> rollup languageDetector.js --file bundle.js --format umd --name eld` 11 | - Minify code with Terser: `> terser bundle.js --compress --mangle --output eld.min.js` 12 | 13 | TODO, It would be a good idea to automate the process. -------------------------------------------------------------------------------- /minified/eld.M60.min.js.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nitotm/efficient-language-detector-js/192327ef791f34e50d6f74c2e2f59e29331a6f84/minified/eld.M60.min.js.gz -------------------------------------------------------------------------------- /minified/eld.XS60.min.js.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nitotm/efficient-language-detector-js/192327ef791f34e50d6f74c2e2f59e29331a6f84/minified/eld.XS60.min.js.gz -------------------------------------------------------------------------------- /misc/sentences-tests-avg-js.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nitotm/efficient-language-detector-js/192327ef791f34e50d6f74c2e2f59e29331a6f84/misc/sentences-tests-avg-js.png -------------------------------------------------------------------------------- /misc/table_accuracy_js.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Accuracy 5 | 6 | Nito-ELD 7 | 8 | 99.3% 9 | 10 | 99.4% 11 | 12 | 98.8% 13 | 14 | 87.6% 15 | 16 | 73.3% 17 | 18 | Nito-ELD-L 19 | 20 | 99.4% 21 | 22 | 99.4% 23 | 24 | 98.7% 25 | 26 | 89.6% 27 | 28 | 76.4% 29 | 30 | Nito-ELD-XS 31 | 32 | 99.2% 33 | 34 | 99.4% 35 | 36 | 98.4% 37 | 38 | 84.4% 39 | 40 | 66.8% 41 | 42 | Lingua1 43 | 44 | 98.8% 45 | 46 | 99.1% 47 | 48 | 98.6% 49 | 50 | 93.1% 51 | 52 | 80.0% 53 | 54 | CLD22 55 | 56 | 93.8% 57 | 58 | 97.2% 59 | 60 | 97.2% 61 | 62 | 87.7% 63 | 64 | 69.6% 65 | 66 | Lingua low1 67 | 68 | 96.0% 69 | 70 | 97.2% 71 | 72 | 96.3% 73 | 74 | 83.7% 75 | 76 | 68.0% 77 | 78 | CLD32 79 | 80 | 92.2% 81 | 82 | 95.8% 83 | 84 | 94.7% 85 | 86 | 69.0% 87 | 88 | 51.5% 89 | 90 | franc 91 | 92 | 89.8% 93 | 94 | 92.0% 95 | 96 | 90.5% 97 | 98 | 65.9% 99 | 100 | 52.9% 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | Tweets 117 | 118 | 119 | Big test 120 | 121 | 122 | Sentences 123 | 124 | 125 | Word pairs 126 | 127 | 128 | Single words 129 | 130 | 131 | 132 | -------------------------------------------------------------------------------- /misc/table_time_js.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Seconds 5 | 6 | Nito-ELD-js 7 | 8 | 0.58" 9 | 10 | 5.1" 11 | 12 | 4.3" 13 | 14 | 1.2" 15 | 16 | 0.73" 17 | 18 | Nito-ELD-L-js 19 | 20 | 0.59" 21 | 22 | 5.2" 23 | 24 | 4.5" 25 | 26 | 1.2" 27 | 28 | 0.77" 29 | 30 | Nito-ELD-XS-js 31 | 32 | 0.5" 33 | 34 | 4.6" 35 | 36 | 4" 37 | 38 | 1.1" 39 | 40 | 0.71" 41 | 42 | Lingua 43 | 44 | 4790" 45 | 46 | 24000" 47 | 48 | 18700" 49 | 50 | 8450" 51 | 52 | 6700" 53 | 54 | CLD2 55 | 56 | 0.35" 57 | 58 | 2" 59 | 60 | 1.7" 61 | 62 | 0.98" 63 | 64 | 0.8" 65 | 66 | Lingua low 67 | 68 | 64" 69 | 70 | 370" 71 | 72 | 308" 73 | 74 | 108" 75 | 76 | 85" 77 | 78 | CLD3 79 | 80 | 3.9" 81 | 82 | 29" 83 | 84 | 26" 85 | 86 | 12" 87 | 88 | 11" 89 | 90 | franc 91 | 92 | 1.2" 93 | 94 | 8" 95 | 96 | 7.8" 97 | 98 | 2.8" 99 | 100 | 2" 101 | 102 | 103 | Nito-ELD-php 104 | 105 | 0.31" 106 | 107 | 2.5" 108 | 109 | 2.2" 110 | 111 | 0.66" 112 | 113 | 0.48" 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | Tweets 130 | 131 | 132 | Big test 133 | 134 | 135 | Sentences 136 | 137 | 138 | Word pairs 139 | 140 | 141 | Single words 142 | 143 | 144 | 145 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "eld", 3 | "version": "1.0.1", 4 | "description": "Fast and accurate natural language detection. Detector written in Javascript. Efficient language detector, Nito-ELD, ELD.", 5 | "main": "src/languageDetector.js", 6 | "type": "module", 7 | "repository": { 8 | "type": "git", 9 | "url": "git+https://github.com/nitotm/efficient-language-detector-js.git" 10 | }, 11 | "keywords": [ 12 | "nlp", 13 | "language", 14 | "natural-language-processing", 15 | "natural-language", 16 | "language-detection", 17 | "language-detector", 18 | "language-identification" 19 | ], 20 | "author": { 21 | "name": "Nito T.M.", 22 | "url": "https://github.com/nitotm" 23 | }, 24 | "funding": "https://linktr.ee/nitotm", 25 | "license": "Apache-2.0", 26 | "bugs": { 27 | "url": "https://github.com/nitotm/efficient-language-detector-js/issues" 28 | }, 29 | "homepage": "https://github.com/nitotm/efficient-language-detector-js#readme" 30 | } 31 | -------------------------------------------------------------------------------- /src/LanguageResult.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2023 Nito T.M. 3 | License https://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 4 | Author Nito T.M. (https://github.com/nitotm) 5 | Package npmjs.com/package/eld 6 | */ 7 | 8 | import { avgScore } from './avgScore.js' 9 | 10 | export class LanguageResult { 11 | /** 12 | * Creates an instance of LanguageResult. 13 | * 14 | * @param {string} language 15 | * @param {Object} results 16 | * @param {number} numNgrams 17 | * @param {Object} langCodes 18 | * @memberof LanguageResult 19 | */ 20 | constructor (language, results, numNgrams, langCodes) { 21 | this.language = language 22 | this.getScores = () => getScores(results, langCodes) // returns object 23 | this.isReliable = () => isReliable(results, numNgrams, language) // returns boolean 24 | } 25 | } 26 | 27 | /** 28 | * @param {object} results 29 | * @param {number} numNgrams 30 | * @param {string} language 31 | * @returns {boolean} 32 | */ 33 | function isReliable (results, numNgrams, language) { 34 | if (!results.length || numNgrams < 3) { 35 | return false 36 | } 37 | const nextScore = results.length > 1 ? results[1][0] : 0 38 | // A minimum of a 24% per ngram score from average 39 | return !(avgScore[language] * 0.24 > results[0][1] / numNgrams || 0.01 > 40 | Math.abs(results[0][1] - nextScore)) 41 | 42 | } 43 | 44 | /** 45 | * Converts internal multi-array results, with integer language codes, to final object with ISO 639-1 codes 46 | * @param {Object} results 47 | * @param {Object} langCodes 48 | * @returns {Object} 49 | */ 50 | function getScores (results, langCodes) { 51 | let scores = {} 52 | let key 53 | for (key in results) { 54 | let score = results[key][1] 55 | if (score === 0) { 56 | break 57 | } 58 | scores[langCodes[results[key][0]]] = score 59 | } 60 | return scores 61 | } 62 | 63 | -------------------------------------------------------------------------------- /src/avgScore.js: -------------------------------------------------------------------------------- 1 | // Average score of each language in a correct detection, done with an extended version of big-test benchmark. 2 | export const avgScore = { 3 | am: 0.0661, 4 | ar: 0.0237, 5 | az: 0.0269, 6 | be: 0.0227, 7 | bg: 0.0234, 8 | bn: 0.1373, 9 | ca: 0.0246, 10 | cs: 0.0242, 11 | da: 0.0277, 12 | de: 0.0275, 13 | el: 0.0369, 14 | en: 0.0378, 15 | es: 0.0252, 16 | et: 0.0253, 17 | eu: 0.0369, 18 | fa: 0.0213, 19 | fi: 0.026, 20 | fr: 0.0253, 21 | gu: 0.1197, 22 | he: 0.0402, 23 | hi: 0.0578, 24 | hr: 0.0201, 25 | hu: 0.0208, 26 | hy: 0.0439, 27 | is: 0.032, 28 | it: 0.0251, 29 | ja: 0.0375, 30 | ka: 0.1383, 31 | kn: 0.1305, 32 | ko: 0.0222, 33 | ku: 0.0256, 34 | lo: 0.3488, 35 | lt: 0.0246, 36 | lv: 0.0264, 37 | ml: 0.1322, 38 | mr: 0.0571, 39 | ms: 0.0251, 40 | nl: 0.0342, 41 | no: 0.0266, 42 | or: 0.1269, 43 | pa: 0.1338, 44 | pl: 0.0275, 45 | pt: 0.0252, 46 | ro: 0.0247, 47 | ru: 0.0184, 48 | sk: 0.024, 49 | sl: 0.0253, 50 | sq: 0.0353, 51 | sr: 0.0234, 52 | sv: 0.033, 53 | ta: 0.1513, 54 | te: 0.1547, 55 | th: 0.0882, 56 | tl: 0.0368, 57 | tr: 0.0258, 58 | uk: 0.0206, 59 | ur: 0.0282, 60 | vi: 0.0467, 61 | yo: 0.0329, 62 | zh: 0.0152, 63 | } 64 | 65 | /* Deprecated for now: Some languages score higher with the same amount of text, this multiplier evens it out for 66 | * multi-language strings 67 | * scoreNormalizer = [0.7, 1, 1, 1, 1, 0.6, 0.98, 1, 1, 1, 0.9, 1, 1, 1, 1, 1, 1, 1, 0.6, 1, 0.7, 1, 1, 0.9, 1, 1, 0.8, 68 | * 0.6, 0.6, 1, 1, 0.5, 1, 1, 0.6, 0.7, 1, 0.95, 1, 0.6, 0.6, 1, 1, 1, 1, 1, 1, 0.9, 1, 1, 0.6, 0.6, 0.7, 0.9, 1, 1, 1, 69 | * 0.8, 1, 1.7] 70 | */ 71 | -------------------------------------------------------------------------------- /src/dictionary.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2023 Nito T.M. 3 | License https://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 4 | Author Nito T.M. (https://github.com/nitotm) 5 | Package npmjs.com/package/eld 6 | */ 7 | 8 | // JS does not allow raw byte strings, Uint8Array\hex adds complexity and a heavier database. 9 | // A dictionary for invalid UTF-8 bytes solves all problems. 10 | export const dictionary = [ 11 | ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 12 | ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '\'', ' ', ' ', ' ', ' ', ' ', ' ', 13 | ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 14 | ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 15 | ' ', ' ', ' ', ' ', '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 16 | 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ', ' ', ' ', ' ', ' ', 'M', '2', 'R', 'J', 'O', 'P', '{', 'ä', '>', 'â', 17 | 'ü', 'é', '_', 'Q', 'á', 'ô', 'ë', 'å', 'õ', 'è', 'ï', 'Z', 'û', '}', 'à', '3', 'ù', 'É', 'Y', 'î', 'í', ']', '|', 18 | ')', 'ÿ', '~', '1', 'V', 'D', 'T', '4', '8', 'F', 'I', 'K', '7', 'W', 'S', '/', 'E', 'B', '5', ';', 'N', 'C', 'ê', 19 | '*', 'X', '=', '^', ':', '[', 'H', 'ò', ' ', ' ', '¢', '!', '(', ',', 'ß', ' ', 'ø', 'ó', ' ', ' ', ' ', ' ', 'U', 20 | 'ö', '6', '@', 'À', 'Á', ' ', '<', 'ý', 'G', '-', 'A', 'ñ', 'ú', ' ', ' ', ' ', ' ', '$', 'L', 'æ', '?', '0', '"', 21 | '#', '%', '&', '+', 'ì', '9', '.', 'ç', ' ', 'µ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 22 | ' ', ' ', ' '] 23 | -------------------------------------------------------------------------------- /src/isoLanguages.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2023 Nito T.M. 3 | License https://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 4 | Author Nito T.M. (https://github.com/nitotm) 5 | Package npmjs.com/package/eld 6 | */ 7 | 8 | /** 9 | * Converts ngram database language indexes (integer) to ISO 639-1 code 10 | * 11 | * @param {Array} languageSet 12 | * @param {Object} defaultLanguages 13 | * @returns {Object} 14 | */ 15 | export function isoLanguages (languageSet, defaultLanguages) { 16 | let languageCodes = {} 17 | for (let langID of languageSet) { 18 | languageCodes[langID] = defaultLanguages[langID] 19 | } 20 | return languageCodes 21 | } 22 | -------------------------------------------------------------------------------- /src/languageData.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2023 Nito T.M. 3 | License https://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 4 | Author Nito T.M. (https://github.com/nitotm) 5 | Package npmjs.com/package/eld 6 | */ 7 | 8 | import { avgScore } from './avgScore.js' 9 | // import { ngramsData } from "./ngrams/ngramsM60.js" 10 | 11 | export const languageData = { 12 | langCodes: {}, langScore: [], ngrams: {}, type: '', avgScore: avgScore 13 | } 14 | 15 | /** 16 | * @param {string} file File inside /ngrams/, with ELD ngrams data format 17 | * @returns {boolean|undefined} true if file was loaded 18 | */ 19 | export async function loadNgrams(file) { 20 | return await import('./ngrams/' + file ).then((module) => { 21 | setNgrams(module.ngramsData) 22 | if (languageData.type) { 23 | return true 24 | } 25 | }) 26 | } 27 | // setNgrams(ngramsData) // Used to create minified files with import { ngramsData } 28 | 29 | /** 30 | * @param {Object} data 31 | */ 32 | function setNgrams(data) { 33 | languageData.langCodes = data.languages 34 | languageData.langScore = Array(Object.keys(data.languages).length).fill(0) 35 | languageData.ngrams = data.ngrams 36 | languageData.type = data.type 37 | } 38 | 39 | /* ISO 639-1 codes, for the 60 languages set. 40 | * ['am', 'ar', 'az', 'be', 'bg', 'bn', 'ca', 'cs', 'da', 'de', 'el', 'en', 'es', 'et', 'eu', 'fa', 'fi', 'fr', 'gu', 41 | * 'he', 'hi', 'hr', 'hu', 'hy', 'is', 'it', 'ja', 'ka', 'kn', 'ko', 'ku', 'lo', 'lt', 'lv', 'ml', 'mr', 'ms', 'nl', 42 | * 'no', 'or', 'pa', 'pl', 'pt', 'ro', 'ru', 'sk', 'sl', 'sq', 'sr', 'sv', 'ta', 'te', 'th', 'tl', 'tr', 'uk', 'ur', 43 | * 'vi', 'yo', 'zh'] 44 | * 45 | * ['Amharic', 'Arabic', 'Azerbaijani (Latin)', 'Belarusian', 'Bulgarian', 'Bengali', 'Catalan', 'Czech', 'Danish', 46 | * 'German', 'Greek', 'English', 'Spanish', 'Estonian', 'Basque', 'Persian', 'Finnish', 'French', 'Gujarati', 47 | * 'Hebrew', 'Hindi', 'Croatian', 'Hungarian', 'Armenian', 'Icelandic', 'Italian', 'Japanese', 'Georgian', 'Kannada', 48 | * 'Korean', 'Kurdish (Arabic)', 'Lao', 'Lithuanian', 'Latvian', 'Malayalam', 'Marathi', 'Malay (Latin)', 'Dutch', 49 | * 'Norwegian', 'Oriya', 'Punjabi', 'Polish', 'Portuguese', 'Romanian', 'Russian', 'Slovak', 'Slovene', 'Albanian', 50 | * 'Serbian (Cyrillic)', 'Swedish', 'Tamil', 'Telugu', 'Thai', 'Tagalog', 'Turkish', 'Ukrainian', 'Urdu', 51 | * 'Vietnamese', 'Yoruba', 'Chinese'] 52 | */ 53 | -------------------------------------------------------------------------------- /src/languageDetector.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2023 Nito T.M. 3 | License https://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 4 | Author Nito T.M. (https://github.com/nitotm) 5 | Package npmjs.com/package/eld 6 | */ 7 | 8 | import { languageData, loadNgrams } from './languageData.js' 9 | import { separators, matchDomains } from './regexPatterns.js' 10 | import { dictionary } from './dictionary.js' 11 | import { isoLanguages } from './isoLanguages.js' 12 | import { LanguageResult } from './LanguageResult.js' 13 | import { saveLanguageSubset } from './saveLanguageSubset.dev.js' 14 | 15 | await loadNgrams('ngramsM60.js') 16 | 17 | // Project is ES2015 18 | const eld = (function () { 19 | return { 20 | detect: detect, 21 | cleanText: cleanText, 22 | dynamicLangSubset: dynamicLangSubset, 23 | saveSubset: saveSubset, 24 | loadNgrams: loadNgrams, 25 | info: info 26 | } 27 | })() 28 | 29 | /** @type {boolean|Array} */ 30 | let subset = false 31 | 32 | /** @type {boolean} When true, detect() cleans input text with getCleanTxt() */ 33 | let doCleanText = false 34 | 35 | /** 36 | * detect() identifies the natural language of a UTF-8 string 37 | * Returns an object, with a variable named 'language', with an ISO 639-1 code or empty string 38 | * { language: 'es', getScores(): {'es': 0.5, 'et': 0.2}, isReliable(): true } 39 | * 40 | * @param {string} text UTF-8 41 | * @returns {{language: string, getScores(): Object, isReliable(): boolean}} class LanguageResult 42 | */ 43 | function detect (text) { 44 | if (typeof text !== 'string') return new LanguageResult('', 0, 0,{}) 45 | 46 | if (doCleanText) { 47 | // Removes Urls, emails, alphanumerical & numbers 48 | text = getCleanTxt(text) 49 | } 50 | 51 | const byteWords = textProcessor(text) 52 | const byteNgrams = getByteNgrams(byteWords) 53 | const numNgrams = Object.keys(byteNgrams).length 54 | let results = calculateScores(byteNgrams, numNgrams) 55 | let language = '' 56 | 57 | if (subset) { 58 | results = filterLangSubset(results) 59 | } 60 | if (results.length > 0) { 61 | results.sort((a, b) => b[1] - a[1]) 62 | language = languageData.langCodes[results[0][0]] 63 | } 64 | return new LanguageResult(language, results, numNgrams, languageData.langCodes) 65 | } 66 | 67 | /** 68 | * Public function to change doCleanText value 69 | * 70 | * @param {boolean} bool 71 | */ 72 | function cleanText (bool) { 73 | doCleanText = Boolean(bool) 74 | } 75 | 76 | /** 77 | * Removes parts of a string, that may be considered as "noise" for language detection 78 | * 79 | * @param {string} str 80 | * @returns {string} 81 | */ 82 | function getCleanTxt (str) { 83 | // Remove URLS 84 | str = str.replace(/[hw]((ttps?:\/\/(www\.)?)|ww\.)([^\s/?.#-]+\.?)+(\/\S*)?/gi, ' ') 85 | // Remove emails 86 | str = str.replace(/[a-zA-Z0-9.!$%&’+_`-]+@[A-Za-z0-9.-]+\.[A-Za-z0-9-]{2,64}/g, ' ') 87 | // Remove .com domains 88 | str = str.replace(matchDomains, ' ') 89 | // Remove alphanumerical/number codes 90 | str = str.replace(/[a-zA-Z]*[0-9]+[a-zA-Z0-9]*/g, ' ') 91 | return str 92 | } 93 | 94 | /** 95 | * @param {string} text 96 | * @returns {Array} 97 | */ 98 | function textProcessor (text) { 99 | text = text.substring(0, 1000) 100 | // Normalize special characters/word separators 101 | text = text.replace(separators, ' ') 102 | text = text.trim().toLowerCase() 103 | return strToUtf8Bytes(text) // returns array of words 104 | } 105 | 106 | /** 107 | * Gets Ngrams from a given array of words 108 | * 109 | * @param {Array} words 110 | * @returns {Object} 111 | */ 112 | function getByteNgrams (words) { 113 | let byteNgrams = {} 114 | let countNgrams = 0 115 | let thisBytes 116 | let j 117 | 118 | for (let key in words) { 119 | let word = words[key] 120 | let len = word.length 121 | if (len > 70) { 122 | len = 70 123 | } 124 | 125 | for (j = 0; j + 4 < len; j += 3, ++countNgrams) { 126 | thisBytes = (j === 0 ? ' ' : '') + word.substring(j, j + 4) 127 | byteNgrams[thisBytes] = typeof byteNgrams[thisBytes] !== 'undefined' ? byteNgrams[thisBytes] + 1 : 1 128 | } 129 | thisBytes = (j === 0 ? ' ' : '') + word.substring(len !== 3 ? len - 4 : 0) + ' ' 130 | byteNgrams[thisBytes] = typeof byteNgrams[thisBytes] !== 'undefined' ? byteNgrams[thisBytes] + 1 : 1 131 | countNgrams++ 132 | } 133 | // Frequency is multiplied by 15000 at the ngrams database. A reduced number (13200) seems to work better. 134 | // Linear formulas were tried, decreasing the multiplier for fewer ngram strings, no meaningful improvement. 135 | for (let bytes in byteNgrams) { 136 | byteNgrams[bytes] = (byteNgrams[bytes] / countNgrams) * 13200 137 | } 138 | return byteNgrams 139 | } 140 | 141 | /** 142 | * Calculate scores for each language from the given Ngrams 143 | * 144 | * @param {Object} byteNgrams 145 | * @param {number} numNgrams 146 | * @returns {Array} 147 | */ 148 | function calculateScores (byteNgrams, numNgrams) { 149 | let bytes, globalFrequency, relevancy, langCount, frequency, lang, thisByte 150 | let langScore = [...languageData.langScore] 151 | 152 | for (bytes in byteNgrams) { 153 | frequency = byteNgrams[bytes] 154 | thisByte = languageData.ngrams[bytes] 155 | 156 | if (thisByte) { 157 | langCount = Object.keys(thisByte).length 158 | // Ngram score multiplier, the fewer languages found the more relevancy. Formula can be fine-tuned. 159 | if (langCount === 1) { 160 | relevancy = 27 // Handpicked relevance multiplier, trial-error 161 | } else { 162 | if (langCount < 16) { 163 | relevancy = (16 - langCount) / 2 + 1 164 | } else { 165 | relevancy = 1 166 | } 167 | } 168 | // Most time-consuming loop, do only the strictly necessary inside 169 | for (lang in thisByte) { 170 | globalFrequency = thisByte[lang] 171 | langScore[lang] += (frequency > globalFrequency ? globalFrequency / frequency : frequency / globalFrequency) * 172 | relevancy + 2 173 | } 174 | } 175 | } 176 | 177 | // This divisor will produce a final score between 0 - ~1, score could be >1. Can be improved. 178 | let resultDivisor = numNgrams * 3.2 179 | let results = [] 180 | for (lang in langScore) { 181 | if (langScore[lang]) { 182 | // Javascript does Not guarantee object order, so a multi-array is used 183 | results.push([parseInt(lang), langScore[lang] / resultDivisor]) // * languageData.scoreNormalizer[lang]; 184 | } 185 | } 186 | return results 187 | } 188 | 189 | /** 190 | * Converts each byte to a single character, using our own dictionary, since javascript does not allow raw byte 191 | * strings or invalid UTF-8 characters. We could use TextEncoder() to create an Uint8Array, and then translate to our 192 | * dictionary, but this function is overall faster as it does both jobs at once 193 | * 194 | * Alternatives such as just using Uint8Array/hex for detection adds complexity and or a bigger database 195 | * 196 | * @param {string} str 197 | * @returns {Array} 198 | */ 199 | function strToUtf8Bytes (str) { 200 | let encoded = '' 201 | let words = [] 202 | let countBytes = 0 203 | const cutAfter = 350 // Cut to first whitespace after 350 byte length offset 204 | const enforceCutAfter = 380 // Cut after any UTF-8 character when surpassing 380 byte length 205 | 206 | for (let ii = 0; ii < str.length; ii++) { 207 | let charCode = str.charCodeAt(ii) 208 | 209 | if (charCode < 0x80) { 210 | if (charCode === 32) { 211 | if (encoded !== '') { 212 | words.push(encoded) 213 | encoded = '' 214 | } 215 | if (countBytes > cutAfter) { 216 | break 217 | } 218 | } else { 219 | encoded += str[ii] 220 | } 221 | countBytes++ 222 | } else if (charCode < 0x800) { 223 | encoded += dictionary[0xc0 | (charCode >> 6)] + dictionary[0x80 | (charCode & 0x3f)] 224 | countBytes += 2 225 | } else if (charCode < 0xd800 || charCode >= 0xe000) { 226 | encoded += dictionary[0xe0 | (charCode >> 12)] + dictionary[0x80 | ((charCode >> 6) & 0x3f)] + 227 | dictionary[0x80 | (charCode & 0x3f)] 228 | countBytes += 3 229 | } else { 230 | // UTF-16 231 | ii++ 232 | charCode = 0x10000 + (((charCode & 0x3ff) << 10) | (str.charCodeAt(ii) & 0x3ff)) 233 | encoded += dictionary[0xf0 | (charCode >> 18)] + dictionary[0x80 | ((charCode >> 12) & 0x3f)] + 234 | dictionary[0x80 | ((charCode >> 6) & 0x3f)] + dictionary[0x80 | (charCode & 0x3f)] 235 | countBytes += 4 236 | } 237 | if (countBytes > enforceCutAfter) { 238 | break 239 | } 240 | } 241 | if (encoded !== '') { 242 | words.push(encoded) 243 | // It is faster to build the array than to words.split(/ +/).filter((x) => x !== ' ') later 244 | } 245 | return words 246 | } 247 | 248 | /** 249 | * Filters languages not included in the subset, from the result scores 250 | * 251 | * @param {Array} results 252 | * @returns {Array} 253 | */ 254 | function filterLangSubset (results) { 255 | let subResults = [] 256 | for (let key in results) { 257 | if (subset.indexOf(results[key][0]) > -1) { 258 | subResults.push(results[key]) 259 | } 260 | } 261 | return subResults 262 | } 263 | 264 | /** 265 | * Validates an expected array of ISO 639-1 language code strings, given by the user, and creates a subset of the valid 266 | * languages compared against the current database available languages 267 | * 268 | * @param {Array|boolean} languages 269 | * @returns {Array|boolean} 270 | */ 271 | function makeSubset (languages) { 272 | if (languages) { 273 | subset = [] 274 | for (let key in languages) { 275 | // Validate languages, by checking if they are available at languageData 276 | let lang = Object.keys(languageData.langCodes).find((lkey) => languageData.langCodes[lkey] === languages[key]) 277 | if (lang) { 278 | subset.push(parseInt(lang)) 279 | } 280 | } 281 | if (subset.length) { 282 | subset.sort() 283 | } else { 284 | subset = false 285 | } 286 | } else { 287 | subset = false 288 | } 289 | return subset 290 | } 291 | 292 | /** 293 | * Creates a subset of languages, from which detect() will filter excluded languages from the results 294 | * Call dynamicLangSubset(false) to delete the subset 295 | * 296 | * @param {Array|boolean} languages 297 | * @returns {Object} Returns list of the validated languages for the new subset 298 | */ 299 | function dynamicLangSubset (languages) { 300 | let result = makeSubset(languages) 301 | if (result) { 302 | return isoLanguages(result, languageData.langCodes) 303 | } 304 | return {} 305 | } 306 | 307 | /** 308 | * Creates a download, only available for the web browser, with a file containing the ngrams database, of the validated 309 | * languages from the array argument 310 | * 311 | * @param {Array} languages 312 | */ 313 | function saveSubset (languages) { 314 | const langArray = makeSubset(languages) 315 | makeSubset(false) // remove the global subset, we only need the filtered langArray 316 | saveLanguageSubset.saveSubset(langArray, languageData.ngrams, languageData.langCodes, languageData.type) 317 | } 318 | 319 | function info() { 320 | return { 321 | 'Data type': languageData.type, 322 | 'Languages': languageData.langCodes, 323 | 'Dynamic subset': subset ? isoLanguages(subset, languageData.langCodes) : false 324 | } 325 | } 326 | 327 | export { eld }; -------------------------------------------------------------------------------- /src/regexPatterns.js: -------------------------------------------------------------------------------- 1 | const unicodeRegex = { 2 | 'L': { 3 | 'alias': 'Letter', 4 | 'bmp': 'A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0560-\u0588\u05D0-\u05EA\u05EF-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u0870-\u0887\u0889-\u088E\u08A0-\u08C9\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C5D\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D04-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u1711\u171F-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4C\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1C90-\u1CBA\u1CBD-\u1CBF\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5\u1CF6\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u31A0-\u31BF\u31F0-\u31FF\u3400-\u4DBF\u4E00-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7CA\uA7D0\uA7D1\uA7D3\uA7D5-\uA7D9\uA7F2-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA8FE\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB69\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC', 5 | }, 6 | } 7 | 8 | // separators matches all languages word separators and special characters 9 | export const separators = new RegExp('[^' + unicodeRegex.L.bmp + ']+(?': 61 | return actual > compare 62 | case '<': 63 | return actual < compare 64 | default: 65 | console.log('Invalid assert operator for the next test:') 66 | return false 67 | } 68 | } 69 | 70 | //} 71 | -------------------------------------------------------------------------------- /tests/tests.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Tests 6 | 7 | 8 | Results at the console.
9 | You can also run them at node: >node tests.js 10 | 11 | 12 | -------------------------------------------------------------------------------- /tests/tests.js: -------------------------------------------------------------------------------- 1 | import { eld } from '../src/languageDetector.js' 2 | import runTests from './testRunner.js' 3 | 4 | let txtFile = (typeof window !== 'undefined' 5 | ? '..' 6 | : 'https://github.com/nitotm/efficient-language-detector-js/raw/main') + '/benchmarks/big-test.txt' // Node or Web 7 | const bigTest = await fetch(txtFile).then(response => response.text()) 8 | 9 | // Mostly functional testing, when functions are more mature I will add some more unit tests 10 | const testCases = [ 11 | 12 | { 13 | name: 'Load ELD', assert: '===', compare: 'object', func: function () { 14 | return typeof eld 15 | }, 16 | }, 17 | 18 | { 19 | name: 'Language detection', assert: '===', compare: 'es', func: function () { 20 | return eld.detect('Hola, cómo te llamas?').language 21 | }, 22 | }, 23 | 24 | { 25 | name: 'Get scores', assert: '>', compare: 1, func: function () { 26 | let scores = eld.detect('Hola, cómo te llamas?').getScores() 27 | return Object.keys(scores).length 28 | }, 29 | }, 30 | 31 | { 32 | name: 'Detect, small text', assert: '===', compare: 'en', func: function () { 33 | return eld.detect('To').language 34 | }, 35 | }, /* Not available for now 36 | { name: 'Clean Text', assert: '===', compare: '', func: function() { 37 | let text = "https://www.google.com/\n"+ 38 | "mail@gmail.com\n"+ 39 | "google.com/search?q=search&source=hp\n"+ // this line fails, to be fixed 40 | "12345 A12345\n"; 41 | return eld.cleanText(text).trim(); 42 | } 43 | },*/ 44 | 45 | { 46 | name: 'Check minimum confidence', assert: '===', compare: false, func: function () { 47 | return eld.detect('zxz zcz zvz zbz znz zmz zlz zsz zdz zkz zjz pelo').isReliable() 48 | }, 49 | }, 50 | 51 | { 52 | name: 'Create dynamicLangSubset, detect', assert: '===', compare: '["en"]', func: function () { 53 | eld.dynamicLangSubset(['en']) 54 | let scores = JSON.stringify(Object.keys(eld.detect('How are you? Bien, gracias').getScores())) 55 | eld.dynamicLangSubset(false) 56 | return scores 57 | }, 58 | }, 59 | 60 | { 61 | name: 'Disable dynamicLangSubset, detect', assert: '>', compare: 1, func: function () { 62 | eld.dynamicLangSubset(['en']) 63 | eld.dynamicLangSubset(false) 64 | let scores = eld.detect('How are you? Bien, gracias').getScores() 65 | return Object.keys(scores).length 66 | }, 67 | }, 68 | 69 | { 70 | name: 'Accuracy test: ngrams-m.js + big-test.txt', assert: '>', compare: 99.4, func: function () { 71 | let correct = 0 72 | let fails = 0 73 | const lines = bigTest.split('\n') 74 | lines.forEach(function (line) { 75 | let parts = line.split('\t') 76 | if (eld.detect(parts[1]).language === parts[0]) { 77 | correct++ 78 | } else { 79 | fails++ 80 | } 81 | }) 82 | 83 | if (correct + fails < 60000) { throw 'Could not load big-test.txt correctly. Not an ELD error.' } 84 | 85 | return (correct / (correct + fails)) * 100 86 | }, 87 | }] 88 | 89 | runTests(testCases) --------------------------------------------------------------------------------