source: other-projects/maori-lang-detection/src/org/greenstone/atea/TextLanguageDetector.java@ 33652

Last change on this file since 33652 was 33652, checked in by ak19, 4 years ago

Introducing morphia subpackage

File size: 16.5 KB
Line 
1/**
2 * Class that uses OpenNLP with the Language Detection Model to determine, with a default
3 * or configurable level of confidence, whether text (from a file or stdin) is in a given
4 * language or not.
5 * Internal functions can be used for detecting any of the 103 languages currently supported by
6 * the OpenNLP Language Detection Model.
7 *
8 * http://opennlp.apache.org/news/model-langdetect-183.html
9 * language detector model: http://opennlp.apache.org/models.html
10 * Pre-trained models for OpenNLP 1.5: http://opennlp.sourceforge.net/models-1.5/
11 * Use of Apache OpenNLP in general:
12 * http://opennlp.apache.org/docs/1.9.1/manual/opennlp.html#intro.api
13 * Use of OpenNLP for language detection:
14 * http://opennlp.apache.org/docs/1.9.1/manual/opennlp.html#tools.langdetect
15 *
16 * This code was based on the information and sample code at the above links and the links dispersed throughout this file.
17 * See also the accompanying README file.
18 *
19 * July 2019
20 */
21
22package org.greenstone.atea;
23
24import java.io.*;
25import opennlp.tools.langdetect.*;
26import opennlp.tools.sentdetect.*;
27import opennlp.tools.util.*;
28
29import java.util.ArrayList;
30
31import org.greenstone.atea.morphia.*;
32
33/**
34 * EXPORT OPENNLP_HOME environment variable to be your apache OpenNLP installation.
35 * Create a folder called "models" within the $OPENNLP_HOME folder, and put the file "langdetect-183.bin" in there
36 * (which is the language detection model zipped up and renamed to .bin extension).
37 *
38 * Then, to compile this program, do the following from the "src" folder (the folder containing this java file):
39 * maori-lang-detection/src$ javac -cp ".:$OPENNLP_HOME/lib/opennlp-tools-1.9.1.jar" org/greenstone/atea/TextLanguageDetector.java
40 *
41 * Only the subclass MaoriTextDetector.java has a main method at present that can be run.
42 *
43 */
44public class TextLanguageDetector {
45
46 public static final double DEFAULT_MINIMUM_CONFIDENCE = 0.50;
47
48 /**
49 * Configurable: cut off minimum confidence value,
50 * greater or equal to which determines that the best predicted language is
51 * acceptable to user of TextLanguageDetector.
52 */
53 public final double MINIMUM_CONFIDENCE;
54
55 /** silentMode set to false means TextLanguageDetector won't print helpful messages while running. Set to true to run silently. */
56 public final boolean silentMode;
57
58 private final String OPENNLP_MODELS_RELATIVE_PATH = "models" + File.separator;
59
60 /** Language Detection Model file for OpenNLP is expected to be at $OPENNLP_HOME/models/langdetect-183.bin */
61 private final String LANG_DETECT_MODEL_RELATIVE_PATH = OPENNLP_MODELS_RELATIVE_PATH + "langdetect-183.bin";
62
63 /**
64 * The LanguageDetectorModel object that will do the actual language detection/prediction for us.
65 * Created once in the constructor, can be used as often as needed thereafter.
66 */
67 private LanguageDetector myCategorizer = null;
68
69 /**
70 * The Sentence Detection object that does the sentence splitting for the language
71 * the sentece model was trained for.
72 */
73 private SentenceDetectorME sentenceDetector = null;
74
75
76 /** Constructor with default confidence for language detection.
77 * Does not create sentence model, just the language detection model.
78 */
79 public TextLanguageDetector(boolean silentMode) throws Exception {
80 this(silentMode, DEFAULT_MINIMUM_CONFIDENCE);
81 }
82
83 /** Constructor with configurable min_confidence for language detection
84 * Does not create sentence model, just the language detection model.
85 */
86 public TextLanguageDetector(boolean silentMode, double min_confidence) throws Exception {
87 this.silentMode = silentMode;
88 this.MINIMUM_CONFIDENCE = min_confidence;
89
90 // 1. Check we can find the Language Detect Model file in the correct location (check that $OPENNLP_HOME/models/langdetect-183.bin exists);
91 String langDetectModelPath = System.getenv("OPENNLP_HOME");
92 if(System.getenv("OPENNLP_HOME") == null) {
93 throw new Exception("\n\t*** Environment variable OPENNLP_HOME must be set to your Apache OpenNLP installation folder.");
94 }
95 langDetectModelPath = langDetectModelPath + File.separator + LANG_DETECT_MODEL_RELATIVE_PATH;
96 File langDetectModelBinFile = new File(langDetectModelPath);
97 if(!langDetectModelBinFile.exists()) {
98 throw new Exception("\n\t*** " + langDetectModelBinFile.getPath() + " doesn't exist."
99 + "\n\t*** Ensure the $OPENNLP_HOME folder contains a 'models' folder"
100 + "\n\t*** with the model file 'langdetect-183.bin' in it.");
101 }
102
103
104 // 2. Set up our language detector Model and the Categorizer for language predictions based on the Model.
105 // http://opennlp.apache.org/docs/1.9.1/manual/opennlp.html#intro.api
106 // https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
107 try (InputStream modelIn = new FileInputStream(langDetectModelPath)) {
108
109 LanguageDetectorModel model = new LanguageDetectorModel(modelIn);
110
111 // http://opennlp.apache.org/docs/1.9.1/manual/opennlp.html#tools.langdetect
112 this.myCategorizer = new LanguageDetectorME(model);
113 }/*catch(Exception e) {
114 e.printStackTrace();
115 }*/
116
117 // instantiating function should handle critical exceptions. Constructors shouldn't.
118
119 }
120
121 /** More general constructor that additionally can load up the sentence detector model
122 * for other languages, as long as the provided trained sentence model .bin file exists
123 * in the OPENNLP_MODELS_RELATIVE_PATH folder. */
124 public TextLanguageDetector(boolean silentMode, double min_confidence,
125 String sentenceModelFileName) throws Exception
126 {
127 this(silentMode, min_confidence);
128
129 // 3. Set up our sentence model and SentenceDetector object
130 String sentenceModelPath = System.getenv("OPENNLP_HOME") + File.separator
131 + OPENNLP_MODELS_RELATIVE_PATH + sentenceModelFileName; // "mri-sent_trained.bin" default
132 File sentenceModelBinFile = new File(sentenceModelPath);
133 if(!sentenceModelBinFile.exists()) {
134 throw new Exception("\n\t*** " + sentenceModelBinFile.getPath() + " doesn't exist."
135 + "\n\t*** Ensure the $OPENNLP_HOME folder contains a 'models' folder"
136 + "\n\t*** with the model file "+sentenceModelFileName+" in it.");
137 }
138 try (InputStream modelIn = new FileInputStream(sentenceModelPath)) {
139 // https://www.tutorialspoint.com/opennlp/opennlp_sentence_detection.htm
140 SentenceModel sentenceModel = new SentenceModel(modelIn);
141 this.sentenceDetector = new SentenceDetectorME(sentenceModel);
142
143 } // instantiating function should handle this critical exception
144 }
145
146 /** TODO: Is it sensible to use the Maori Language Sentence Model to split the text
147 * into sentences? What if the text in any other language or a mix of languages?
148 * Doesn't this assume that all languages split sentences alike? */
149 public String[] getAllSentences(String text) {
150
151 // This function doesn't work if the sentenceDetector object wasn't set up
152 if(sentenceDetector == null) return null;
153
154 String[] sentences = sentenceDetector.sentDetect(text);
155 return sentences;
156 }
157
158 public ArrayList<SentenceInfo> getAllSentencesInfo(String[] sentences) {
159
160 if(sentences == null) {
161 return null;
162 }
163
164 ArrayList<SentenceInfo> sentencesList = new ArrayList<SentenceInfo>();
165 for(int i = 0; i < sentences.length; i++) {
166 String sentence = sentences[i];
167
168 //System.err.println(sentence);
169
170 Language bestLanguage = myCategorizer.predictLanguage(sentence);
171 double confidence = bestLanguage.getConfidence();
172
173 sentencesList.add(new SentenceInfo(confidence, bestLanguage.getLang(), sentence));
174 }
175
176 return sentencesList;
177 }
178
179 public ArrayList<SentenceInfo> getAllOverlappingSentencesInfo(String[] sentences) {
180
181 if(sentences == null) {
182 return null;
183 }
184
185 ArrayList<SentenceInfo> sentencesList = new ArrayList<SentenceInfo>();
186 for(int i = 1; i < sentences.length; i++) {
187 // glue every two adjacent sentences together
188 String doubleSentence = sentences[i-1];
189
190 String separator = ". ";
191 // if the sentence already ends with a terminating punctuation character,
192 // then separator is just a space
193 doubleSentence = doubleSentence.trim();
194 if(doubleSentence.endsWith(".") || doubleSentence.endsWith("?") || doubleSentence.endsWith("!")) {
195 separator = " ";
196 }
197 doubleSentence = doubleSentence + separator + sentences[i];
198
199 //System.err.println(sentence);
200
201 Language bestLanguage = myCategorizer.predictLanguage(doubleSentence);
202 double confidence = bestLanguage.getConfidence();
203
204 sentencesList.add(new SentenceInfo(confidence, bestLanguage.getLang(), doubleSentence));
205 }
206
207 return sentencesList;
208 }
209
210 /**
211 * In this class' constructor, need to have set up the Sentence Detection Model
212 * for the langCode passed in to this function in order for the output to make
213 * sense for that language.
214 * Function that takes a text and returns those sentences in the requested language.
215 * @param text: the string of text from which sentences in the requested
216 * language are to be identified and returned.
217 * @param langCode: 3 letter code of requested language
218 * @param confidenceCutoff: minimum confidence for a SINGLE sentence to be selected
219 * even if the language detector determined the requested language as the primary one
220 * for that sentence. The confidence cutoff provides an additional check.
221 * @return null if no Sentence Detection Model set up in constructor
222 * else returns an ArrayList where:
223 * - the first element is the total number of sentences in the text parameter
224 * - remaining elements are the sentences in the text parameter that were in the
225 * requested language.
226 */
227 public ArrayList<String> getAllSentencesInLanguage(String langCode, String text, double confidenceCutoff)
228 {
229 // big assumption here: that we can split incoming text into sentences
230 // for any language using the sentence model trained for a given language (that of
231 // langCode), despite not knowing what language each sentence in the text param are in.
232 // Hinges on sentence detection in langCode being similar to all others?
233
234
235 // This function doesn't work if the sentenceDetector object wasn't set up
236 if(sentenceDetector == null) return null;
237
238 // we'll be storing just those sentences in text that are in the denoted language code
239 ArrayList<String> sentencesInLang = new ArrayList<String>();
240 // OpenNLP language detection works best with a minimum of 2 sentences
241 // See https://opennlp.apache.org/news/model-langdetect-183.html
242 // "It is important to note that this model is trained for and works well with
243 // longer texts that have at least 2 sentences or more from the same language."
244
245 // For evaluating single languages, I used a very small data set and found that
246 // if the primary language detected is MRI AND if the confidence is >= 0.1, the
247 // results appear reasonably to be in te reo Māori.
248
249 String[] sentences = sentenceDetector.sentDetect(text);
250 if(sentences == null) {
251 sentencesInLang.add("0"); // to indicate 0 sentences in requested language
252 return sentencesInLang;
253 }
254
255 // add in first element: how many sentences there were in text.
256 sentencesInLang.add(Integer.toString(sentences.length));
257
258 for(int i = 0; i < sentences.length; i++) {
259 String sentence = sentences[i];
260
261 //System.err.println(sentence);
262
263 Language bestLanguage = myCategorizer.predictLanguage(sentence);
264 double confidence = bestLanguage.getConfidence();
265
266 if(bestLanguage.getLang().equals(langCode) && confidence >= confidenceCutoff) {
267 //System.err.println("Adding sentence: " + sentence + "\n");
268 sentencesInLang.add(sentence);
269 } //else {
270 //System.err.println("SKIPPING sentence: " + sentence + "\n");
271 //}
272 }
273 return sentencesInLang;
274 }
275
276
277 /** @param langCode is 3 letter language code, ISO 639-2/3
278 * https://www.loc.gov/standards/iso639-2/php/code_list.php
279 * https://en.wikipedia.org/wiki/ISO_639-3
280 * @return true if the input text is Maori (mri) with MINIMUM_CONFIDENCE levels of confidence (if set,
281 * else DEFAULT_MINIMUM_CONFIDENCE levels of confidence).
282 */
283 public boolean isTextInLanguage(String langCode, String text) {
284 // Get the most probable language
285 Language bestLanguage = myCategorizer.predictLanguage(text);
286 doPrint("Best language: " + bestLanguage.getLang());
287 doPrint("Best language confidence: " + bestLanguage.getConfidence());
288
289 return (bestLanguage.getLang().equals(langCode) && bestLanguage.getConfidence() >= this.MINIMUM_CONFIDENCE);
290 }
291
292
293 /**
294 * Handle "smaller" textfiles/streams of text read in.
295 * Return value is the same as for isTextInLanguage(String langCode, String text);
296 */
297 public boolean isTextInLanguage(String langCode, BufferedReader reader) throws Exception {
298 // https://stackoverflow.com/questions/326390/how-do-i-create-a-java-string-from-the-contents-of-a-file
299
300 StringBuilder text = new StringBuilder();
301 String line = null;
302
303
304 while((line = reader.readLine()) != null) { // readLine removes newline separator
305 text.append(line + "\n"); // add back (unix style) line ending
306 }
307 return isTextInLanguage(langCode, text.toString());
308 }
309
310
311 /**
312 * Rudimentary attempt to deal with very large files.
313 * Return value is the same as for isTextInLanguage(String langCode, String text);
314 */
315 public boolean isLargeTextInLanguage(String langCode, BufferedReader reader) throws Exception {
316 // https://stackoverflow.com/questions/326390/how-do-i-create-a-java-string-from-the-contents-of-a-file
317
318 final int NUM_LINES = 100; // arbitrary 100 lines read, predict language, calculate confidence
319
320 StringBuilder text = new StringBuilder();
321 String line = null;
322
323 double cumulativeConfidence = 0;
324 int numLoops = 0;
325
326 int i = 0;
327 String language = null;
328
329 while((line = reader.readLine()) != null) { // readLine removes newline separator
330 text.append(line + "\n"); // add back (unix style) line ending
331
332 i++; // read nth line of numLoop
333
334
335 if(i == NUM_LINES) { // arbitrary 100 lines read, predict language, calculate confidence
336
337 Language bestLanguage = myCategorizer.predictLanguage(text.toString());
338 if(language != null && !bestLanguage.getLang().equals(language)) { // predicted lang of current n lines not the same as predicted lang for prev n lines
339 doPrintErr("**** WARNING: text seems to contain content in multiple languages or unable to consistently predict the same language.");
340 }
341 language = bestLanguage.getLang();
342 cumulativeConfidence += bestLanguage.getConfidence();
343
344 doPrintErr("Best predicted language for last " + NUM_LINES + " lines: " + language + "(confidence: " + bestLanguage.getConfidence() + ")");
345
346 // finished analysing language of NUM_LINES of text
347 text = new StringBuilder();
348 i = 0;
349 numLoops++;
350 }
351 }
352
353 // process any (remaining) text that was less than n NUM_LINES
354 if(!text.toString().equals("")) {
355 text.append(line + "\n"); // add back (unix style) line ending
356 i++;
357
358 Language bestLanguage = myCategorizer.predictLanguage(text.toString());
359
360 if(language != null && !bestLanguage.getLang().equals(language)) { // predicted lang of current n lines not the same as predicted lang for prev n lines
361 doPrintErr("**** WARNING: text seems to contain content in multiple languages or unable to consistently predict the same language.");
362 }
363 language = bestLanguage.getLang();
364 cumulativeConfidence += bestLanguage.getConfidence();
365 doPrintErr("Best predicted language for final " + NUM_LINES + " lines: " + language + "(confidence: " + bestLanguage.getConfidence() + ")");
366 }
367
368
369 int totalLinesRead = numLoops * NUM_LINES + i; // not used
370 double avgConfidence = cumulativeConfidence/(numLoops + 1); // not quite the average as the text processed outside the loop may have fewer lines than NUM_LINES
371
372
373 return (language.equals(langCode) && avgConfidence >= this.MINIMUM_CONFIDENCE);
374 }
375
376
377 /**
378 * Prints to STDOUT the predicted languages of the input text in order of descending confidence.
379 * UNUSED.
380 */
381 public void predictedLanguages(String text) {
382 // Get an array with the most probable languages
383
384 Language[] languages = myCategorizer.predictLanguages(text);
385
386 if(languages == null || languages.length <= 0) {
387 doPrintErr("No languages predicted for the input text");
388 } else {
389 for(int i = 0; i < languages.length; i++) {
390 doPrint("Language prediction " + i + ": " + languages[i]);
391 }
392 }
393
394 }
395
396 public void doPrint(String msg) {
397 if(!this.silentMode) System.out.println(msg);
398 }
399 public void doPrintErr(String msg) {
400 if(!this.silentMode) System.err.println(msg);
401 }
402
403}
Note: See TracBrowser for help on using the repository browser.