You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@opennlp.apache.org by kr...@apache.org on 2026/09/01 02:59:03 UTC
(opennlp) branch 2.x-OPENNLP-1904 created (now 8e5b67180)
This is an automated email from the ASF dual-hosted git repository.
krickert pushed a change to branch 2.x-OPENNLP-1904
in repository https://gitbox.apache.org/repos/asf/opennlp.git
at 8e5b67180 [2.x] OPENNLP-1904: Default-locale case folding corrupts lemmatizer models and output
This branch includes the following new commits:
new 8e5b67180 [2.x] OPENNLP-1904: Default-locale case folding corrupts lemmatizer models and output
The 1 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
(opennlp) 01/01: [2.x] OPENNLP-1904: Default-locale case folding corrupts lemmatizer models and output
Posted by kr...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
krickert pushed a commit to branch 2.x-OPENNLP-1904
in repository https://gitbox.apache.org/repos/asf/opennlp.git
commit 8e5b67180966717105598226d5126783abe6eb58
Author: Kristian Rickert <kr...@gmail.com>
AuthorDate: Thu Aug 13 04:28:40 2026 -0400
[2.x] OPENNLP-1904: Default-locale case folding corrupts lemmatizer models and output
* OPENNLP-1904: Fix default-locale case folding in the lemmatizers
getShortestEditScript folded both the word form and the lemma with the JVM
default locale. Those folded strings become the shortest-edit-script labels that
encodeLemmas writes into a trained model, and decodeLemmas folds again with
Locale.ROOT rather than the project's own StringUtil.toLowerCase. The latter maps
code points through Character.toLowerCase, which is context free and disagrees
with String.toLowerCase(Locale.ROOT) on context sensitive mappings such as Greek
final sigma and on one to many mappings such as the sharp s. Every shipped model
was produced on an English locale JVM, whose fold is byte identical to
Locale.ROOT, so this keeps existing models working unchanged. The code point fold
would silently alter them. StringUtilLocaleTest carries a guard that fails if
someone later switches to the code point fold for consistency.
No model regeneration is required.
Backport of #1206 to opennlp-2.x. The tests build the Turkish locale with the Locale constructor, since 2.x targets Java 17 and Locale.of arrived in 19; TrainingParameters keeps its 2.x shape with root-locale lowercasing.
---
.../tools/cmdline/DetailedFMeasureListener.java | 2 +-
.../tools/cmdline/FineGrainedReportListener.java | 32 ++++++---
.../tools/lemmatizer/DictionaryLemmatizer.java | 3 +-
.../opennlp/tools/lemmatizer/LemmatizerME.java | 3 +-
.../java/opennlp/tools/ml/model/AbstractModel.java | 5 +-
.../main/java/opennlp/tools/util/StringUtil.java | 5 +-
.../opennlp/tools/util/TrainingParameters.java | 15 ++---
.../ChunkerDetailedFMeasureListenerTest.java | 37 ++++++++++
.../cmdline/FineGrainedReportListenerTest.java | 71 ++++++++++++++++++++
.../tools/lemmatizer/DictionaryLemmatizerTest.java | 33 +++++++++
.../tools/lemmatizer/LemmatizerMELocaleTest.java | 72 ++++++++++++++++++++
.../opennlp/tools/util/StringUtilLocaleTest.java | 78 ++++++++++++++++++++++
.../opennlp/tools/util/TrainingParametersTest.java | 36 ++++++++++
13 files changed, 369 insertions(+), 23 deletions(-)
diff --git a/opennlp-tools/src/main/java/opennlp/tools/cmdline/DetailedFMeasureListener.java b/opennlp-tools/src/main/java/opennlp/tools/cmdline/DetailedFMeasureListener.java
index 5f6750175..7c6e18631 100644
--- a/opennlp-tools/src/main/java/opennlp/tools/cmdline/DetailedFMeasureListener.java
+++ b/opennlp-tools/src/main/java/opennlp/tools/cmdline/DetailedFMeasureListener.java
@@ -116,7 +116,7 @@ public abstract class DetailedFMeasureListener<T> implements EvaluationMonitor<T
+ " [target: %3d; tp: %3d; fp: %3d]";
public String createReport() {
- return createReport(Locale.getDefault());
+ return createReport(Locale.ROOT);
}
public String createReport(Locale locale) {
diff --git a/opennlp-tools/src/main/java/opennlp/tools/cmdline/FineGrainedReportListener.java b/opennlp-tools/src/main/java/opennlp/tools/cmdline/FineGrainedReportListener.java
index b0ae3ba93..25a6481a6 100644
--- a/opennlp-tools/src/main/java/opennlp/tools/cmdline/FineGrainedReportListener.java
+++ b/opennlp-tools/src/main/java/opennlp/tools/cmdline/FineGrainedReportListener.java
@@ -29,6 +29,7 @@ import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
@@ -163,6 +164,19 @@ public abstract class FineGrainedReportListener {
return stats.getConfusionMatrixTagset(token);
}
+ /**
+ * Applies a {@link MessageFormat} number pattern using {@link Locale#ROOT}, so that the
+ * figures in a report stay identical regardless of the JVM's default {@link Locale}.
+ *
+ * @param pattern The {@link MessageFormat} pattern to apply.
+ * @param value The value to format.
+ *
+ * @return The formatted value.
+ */
+ private static String formatNumber(String pattern, Object value) {
+ return new MessageFormat(pattern, Locale.ROOT).format(new Object[] {value});
+ }
+
private double[][] getConfusionMatrix() {
return stats.getConfusionMatrix();
}
@@ -187,7 +201,7 @@ public abstract class FineGrainedReportListener {
minColumnSize = matrix[i][j].length();
}
}
- matrix[i][j] = MessageFormat.format("{0,number,#.##%}", data[i][j]);
+ matrix[i][j] = formatNumber("{0,number,#.##%}", data[i][j]);
if (data[i][j] == 1 && filter) {
initialIndex = i + 1;
}
@@ -229,12 +243,12 @@ public abstract class FineGrainedReportListener {
String.format("%21s: %6s", "Max sentence size", getMaxSentenceSize())).append("\n");
printStream.append(
String.format("%21s: %6s", "Average sentence size",
- MessageFormat.format("{0,number,#.##}", getAverageSentenceSize()))).append("\n");
+ formatNumber("{0,number,#.##}", getAverageSentenceSize()))).append("\n");
printStream.append(
String.format("%21s: %6s", "Tags count", getNumberOfTags())).append("\n");
printStream.append(
String.format("%21s: %6s", "Accuracy",
- MessageFormat.format("{0,number,#.##%}", getAccuracy()))).append("\n");
+ formatNumber("{0,number,#.##%}", getAccuracy()))).append("\n");
printFooter("Evaluation Corpus Statistics");
}
@@ -308,7 +322,7 @@ public abstract class FineGrainedReportListener {
String tok = tokIterator.next();
int ocurrencies = getTokenFrequency(tok);
int errors = getTokenErrors(tok);
- String rate = MessageFormat.format("{0,number,#.##%}", (double) errors
+ String rate = formatNumber("{0,number,#.##%}", (double) errors
/ ocurrencies);
printStream.append(String.format(format, tok, errors, ocurrencies, rate)
@@ -347,7 +361,7 @@ public abstract class FineGrainedReportListener {
for (String tag : tags) {
int ocurrencies = getTagFrequency(tag);
int errors = getTagErrors(tag);
- String rate = MessageFormat.format("{0,number,#.###}", (double) errors
+ String rate = formatNumber("{0,number,#.###}", (double) errors
/ ocurrencies);
double p = getTagPrecision(tag);
@@ -355,9 +369,9 @@ public abstract class FineGrainedReportListener {
double f = getTagFMeasure(tag);
printStream.append(String.format(format, tag, errors, ocurrencies, rate,
- MessageFormat.format("{0,number,#.###}", p > 0 ? p : 0),
- MessageFormat.format("{0,number,#.###}", r > 0 ? r : 0),
- MessageFormat.format("{0,number,#.###}", f > 0 ? f : 0))
+ formatNumber("{0,number,#.###}", p > 0 ? p : 0),
+ formatNumber("{0,number,#.###}", r > 0 ? r : 0),
+ formatNumber("{0,number,#.###}", f > 0 ? f : 0))
);
}
@@ -405,7 +419,7 @@ public abstract class FineGrainedReportListener {
.append("]\n")
.append(
String.format("%12s: %-8s", "Accuracy",
- MessageFormat.format("{0,number,#.##%}", acc)))
+ formatNumber("{0,number,#.##%}", acc)))
.append("\n");
printStream.append(
String.format("%12s: %-8s", "Ocurrencies",
diff --git a/opennlp-tools/src/main/java/opennlp/tools/lemmatizer/DictionaryLemmatizer.java b/opennlp-tools/src/main/java/opennlp/tools/lemmatizer/DictionaryLemmatizer.java
index 8b68cf676..c6459702c 100644
--- a/opennlp-tools/src/main/java/opennlp/tools/lemmatizer/DictionaryLemmatizer.java
+++ b/opennlp-tools/src/main/java/opennlp/tools/lemmatizer/DictionaryLemmatizer.java
@@ -32,6 +32,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
/**
@@ -161,7 +162,7 @@ public class DictionaryLemmatizer implements Lemmatizer {
* @return Retrieves the dictionary keys (word and postag).
*/
private List<String> getDictKeys(final String word, final String postag) {
- return new ArrayList<>(Arrays.asList(word.toLowerCase(), postag));
+ return new ArrayList<>(Arrays.asList(word.toLowerCase(Locale.ROOT), postag));
}
diff --git a/opennlp-tools/src/main/java/opennlp/tools/lemmatizer/LemmatizerME.java b/opennlp-tools/src/main/java/opennlp/tools/lemmatizer/LemmatizerME.java
index 0d3960d1f..5b31a87d7 100644
--- a/opennlp-tools/src/main/java/opennlp/tools/lemmatizer/LemmatizerME.java
+++ b/opennlp-tools/src/main/java/opennlp/tools/lemmatizer/LemmatizerME.java
@@ -22,6 +22,7 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import opennlp.tools.ml.BeamSearch;
@@ -160,7 +161,7 @@ public class LemmatizerME implements Lemmatizer, Probabilistic {
public static String[] decodeLemmas(String[] toks, String[] preds) {
List<String> lemmas = new ArrayList<>();
for (int i = 0; i < toks.length; i++) {
- String lemma = StringUtil.decodeShortestEditScript(toks[i].toLowerCase(), preds[i]);
+ String lemma = StringUtil.decodeShortestEditScript(toks[i].toLowerCase(Locale.ROOT), preds[i]);
if (lemma.length() == 0) {
lemma = "_";
}
diff --git a/opennlp-tools/src/main/java/opennlp/tools/ml/model/AbstractModel.java b/opennlp-tools/src/main/java/opennlp/tools/ml/model/AbstractModel.java
index fc529a5b7..639ab9b7b 100644
--- a/opennlp-tools/src/main/java/opennlp/tools/ml/model/AbstractModel.java
+++ b/opennlp-tools/src/main/java/opennlp/tools/ml/model/AbstractModel.java
@@ -18,8 +18,10 @@
package opennlp.tools.ml.model;
import java.text.DecimalFormat;
+import java.text.DecimalFormatSymbols;
import java.util.Arrays;
import java.util.LinkedHashMap;
+import java.util.Locale;
import java.util.Map;
import java.util.Objects;
@@ -30,7 +32,8 @@ import opennlp.tools.ml.ArrayMath;
*/
public abstract class AbstractModel implements MaxentModel {
- private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.0000");
+ private static final DecimalFormat DECIMAL_FORMAT =
+ new DecimalFormat("0.0000", DecimalFormatSymbols.getInstance(Locale.ROOT));
/** Mapping between predicates/contexts and an integer representing them. */
protected Map<String, Context> pmap;
diff --git a/opennlp-tools/src/main/java/opennlp/tools/util/StringUtil.java b/opennlp-tools/src/main/java/opennlp/tools/util/StringUtil.java
index c21020e28..8db723d91 100644
--- a/opennlp-tools/src/main/java/opennlp/tools/util/StringUtil.java
+++ b/opennlp-tools/src/main/java/opennlp/tools/util/StringUtil.java
@@ -18,6 +18,7 @@
package opennlp.tools.util;
import java.nio.CharBuffer;
+import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -350,8 +351,8 @@ public class StringUtil {
* @return Retrieves the Shortest Edit Script (SES) required to go from a word to a lemma.
*/
public static String getShortestEditScript(String wordForm, String lemma) {
- String reversedWF = new StringBuffer(wordForm.toLowerCase()).reverse().toString();
- String reversedLemma = new StringBuffer(lemma.toLowerCase()).reverse().toString();
+ String reversedWF = new StringBuffer(wordForm.toLowerCase(Locale.ROOT)).reverse().toString();
+ String reversedLemma = new StringBuffer(lemma.toLowerCase(Locale.ROOT)).reverse().toString();
StringBuffer permutations = new StringBuffer();
String ses;
if (!reversedWF.equals(reversedLemma)) {
diff --git a/opennlp-tools/src/main/java/opennlp/tools/util/TrainingParameters.java b/opennlp-tools/src/main/java/opennlp/tools/util/TrainingParameters.java
index 37f5bd925..82f44dc9e 100644
--- a/opennlp-tools/src/main/java/opennlp/tools/util/TrainingParameters.java
+++ b/opennlp-tools/src/main/java/opennlp/tools/util/TrainingParameters.java
@@ -22,6 +22,7 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.HashMap;
+import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
@@ -559,16 +560,14 @@ public class TrainingParameters {
TrainingParameters mlParams = new TrainingParameters();
mlParams.put(TrainingParameters.ALGORITHM_PARAM , "MAXENT");
mlParams.put(TrainingParameters.TRAINER_TYPE_PARAM , EventTrainer.EVENT_VALUE);
+ final String iterationsFlag = "-" + TrainingParameters.ITERATIONS_PARAM.toLowerCase(Locale.ROOT);
+ final String cutoffFlag = "-" + TrainingParameters.CUTOFF_PARAM.toLowerCase(Locale.ROOT);
mlParams.put(TrainingParameters.ITERATIONS_PARAM ,
- null != CmdLineUtil.getIntParameter("-" +
- TrainingParameters.ITERATIONS_PARAM.toLowerCase() , params) ?
- CmdLineUtil.getIntParameter("-" + TrainingParameters.ITERATIONS_PARAM.toLowerCase() , params) :
- ITERATIONS_DEFAULT_VALUE);
+ null != CmdLineUtil.getIntParameter(iterationsFlag , params) ?
+ CmdLineUtil.getIntParameter(iterationsFlag , params) : ITERATIONS_DEFAULT_VALUE);
mlParams.put(TrainingParameters.CUTOFF_PARAM ,
- null != CmdLineUtil.getIntParameter("-" +
- TrainingParameters.CUTOFF_PARAM.toLowerCase() , params) ?
- CmdLineUtil.getIntParameter("-" + TrainingParameters.CUTOFF_PARAM.toLowerCase() , params) :
- CUTOFF_DEFAULT_VALUE);
+ null != CmdLineUtil.getIntParameter(cutoffFlag , params) ?
+ CmdLineUtil.getIntParameter(cutoffFlag , params) : CUTOFF_DEFAULT_VALUE);
return mlParams;
}
diff --git a/opennlp-tools/src/test/java/opennlp/tools/chunker/ChunkerDetailedFMeasureListenerTest.java b/opennlp-tools/src/test/java/opennlp/tools/chunker/ChunkerDetailedFMeasureListenerTest.java
index 00031b41c..de790cd71 100644
--- a/opennlp-tools/src/test/java/opennlp/tools/chunker/ChunkerDetailedFMeasureListenerTest.java
+++ b/opennlp-tools/src/test/java/opennlp/tools/chunker/ChunkerDetailedFMeasureListenerTest.java
@@ -23,6 +23,7 @@ import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Locale;
+import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -32,6 +33,13 @@ import opennlp.tools.util.PlainTextByLineStream;
public class ChunkerDetailedFMeasureListenerTest {
+ private final Locale defaultLocale = Locale.getDefault();
+
+ @AfterEach
+ void restoreDefaultLocale() {
+ Locale.setDefault(defaultLocale);
+ }
+
@Test
void testEvaluator() throws IOException {
@@ -68,4 +76,33 @@ public class ChunkerDetailedFMeasureListenerTest {
Assertions.assertEquals(expected.toString().trim(), listener.createReport(Locale.ENGLISH).trim());
}
+
+ /**
+ * The no-argument report has to render the same figures everywhere, so a JVM defaulting to
+ * a locale with a comma decimal separator must not change the numbers in the output.
+ */
+ @Test
+ void testReportIsIndependentOfDefaultLocale() throws IOException {
+ ChunkerDetailedFMeasureListener listener = new ChunkerDetailedFMeasureListener();
+ evaluate(listener);
+
+ Locale.setDefault(Locale.GERMANY);
+
+ Assertions.assertEquals(listener.createReport(Locale.ENGLISH).trim(),
+ listener.createReport().trim());
+ }
+
+ private static void evaluate(ChunkerDetailedFMeasureListener listener) throws IOException {
+ ResourceAsStreamFactory inPredicted = new ResourceAsStreamFactory(
+ ChunkerDetailedFMeasureListenerTest.class, "/opennlp/tools/chunker/output.txt");
+ ResourceAsStreamFactory inExpected = new ResourceAsStreamFactory(
+ ChunkerDetailedFMeasureListenerTest.class, "/opennlp/tools/chunker/output.txt");
+
+ DummyChunkSampleStream predictedSample = new DummyChunkSampleStream(
+ new PlainTextByLineStream(inPredicted, StandardCharsets.UTF_8), true);
+ DummyChunkSampleStream expectedSample = new DummyChunkSampleStream(
+ new PlainTextByLineStream(inExpected, StandardCharsets.UTF_8), false);
+
+ new ChunkerEvaluator(new DummyChunker(predictedSample), listener).evaluate(expectedSample);
+ }
}
diff --git a/opennlp-tools/src/test/java/opennlp/tools/cmdline/FineGrainedReportListenerTest.java b/opennlp-tools/src/test/java/opennlp/tools/cmdline/FineGrainedReportListenerTest.java
new file mode 100644
index 000000000..36f6dca6d
--- /dev/null
+++ b/opennlp-tools/src/test/java/opennlp/tools/cmdline/FineGrainedReportListenerTest.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package opennlp.tools.cmdline;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Locale;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import opennlp.tools.cmdline.postag.POSTaggerFineGrainedReportListener;
+import opennlp.tools.postag.POSSample;
+
+/**
+ * Tests that the figures written by a {@link FineGrainedReportListener} do not change with
+ * the JVM's default {@link Locale}.
+ */
+public class FineGrainedReportListenerTest {
+
+ private final Locale defaultLocale = Locale.getDefault();
+
+ @AfterEach
+ void restoreDefaultLocale() {
+ Locale.setDefault(defaultLocale);
+ }
+
+ @Test
+ void testReportIsIndependentOfDefaultLocale() throws Exception {
+ Locale.setDefault(Locale.GERMANY);
+
+ final String report = createReport();
+
+ // Two out of three tags are correct. A locale with a comma decimal separator would
+ // render this as "66,67%" and change every figure in the report along with it.
+ Assertions.assertTrue(report.contains("66.67%"),
+ () -> "Report should contain the Locale.ROOT rendering of the accuracy:\n" + report);
+ Assertions.assertFalse(report.contains("66,67%"),
+ () -> "Report should not render figures with the default locale:\n" + report);
+ }
+
+ private static String createReport() throws Exception {
+ final String[] sentence = {"He", "runs", "fast"};
+ final POSSample reference = new POSSample(sentence, new String[] {"PRP", "VBZ", "RB"});
+ final POSSample prediction = new POSSample(sentence, new String[] {"PRP", "VBZ", "JJ"});
+
+ try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
+ final POSTaggerFineGrainedReportListener listener =
+ new POSTaggerFineGrainedReportListener(out);
+ listener.misclassified(reference, prediction);
+ listener.writeReport();
+ return out.toString(StandardCharsets.UTF_8);
+ }
+ }
+}
diff --git a/opennlp-tools/src/test/java/opennlp/tools/lemmatizer/DictionaryLemmatizerTest.java b/opennlp-tools/src/test/java/opennlp/tools/lemmatizer/DictionaryLemmatizerTest.java
index add85b2d5..7b4ceb714 100644
--- a/opennlp-tools/src/test/java/opennlp/tools/lemmatizer/DictionaryLemmatizerTest.java
+++ b/opennlp-tools/src/test/java/opennlp/tools/lemmatizer/DictionaryLemmatizerTest.java
@@ -17,14 +17,26 @@
package opennlp.tools.lemmatizer;
+import java.io.ByteArrayInputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Locale;
+
+import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class DictionaryLemmatizerTest {
+ /**
+ * Turkish folds {@code 'I'} to the dotless {@code 'ı'} (U+0131) instead of {@code 'i'}.
+ */
+ private static final Locale TURKISH = new Locale("tr", "TR");
+
private static DictionaryLemmatizer dictionaryLemmatizer;
+ private final Locale defaultLocale = Locale.getDefault();
+
@BeforeAll
static void loadDictionary() throws Exception {
dictionaryLemmatizer = new DictionaryLemmatizer(
@@ -49,4 +61,25 @@ public class DictionaryLemmatizerTest {
}
}
+ @AfterEach
+ void restoreDefaultLocale() {
+ Locale.setDefault(defaultLocale);
+ }
+
+ /**
+ * The dictionary is read verbatim but looked up folded, so the fold has to match the
+ * casing of the dictionary file rather than whatever locale the JVM happens to run in.
+ */
+ @Test
+ void testLookupIsIndependentOfDefaultLocale() throws Exception {
+ final String entries = "illinois\tNNP\tIllinois\n" + "indices\tNNS\tindex\n";
+ final DictionaryLemmatizer lemmatizer = new DictionaryLemmatizer(
+ new ByteArrayInputStream(entries.getBytes(StandardCharsets.UTF_8)));
+
+ Locale.setDefault(TURKISH);
+
+ Assertions.assertArrayEquals(new String[] {"Illinois", "index"},
+ lemmatizer.lemmatize(new String[] {"Illinois", "INDICES"}, new String[] {"NNP", "NNS"}));
+ }
+
}
diff --git a/opennlp-tools/src/test/java/opennlp/tools/lemmatizer/LemmatizerMELocaleTest.java b/opennlp-tools/src/test/java/opennlp/tools/lemmatizer/LemmatizerMELocaleTest.java
new file mode 100644
index 000000000..25d5891ba
--- /dev/null
+++ b/opennlp-tools/src/test/java/opennlp/tools/lemmatizer/LemmatizerMELocaleTest.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package opennlp.tools.lemmatizer;
+
+import java.util.Locale;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests that the lemma class encoding and decoding of {@link LemmatizerME} do not depend
+ * on the JVM's default {@link Locale}.
+ * <p>
+ * Encoding produces the outcome labels that are persisted in a trained model, decoding
+ * consumes them at inference time. Both sides therefore have to agree across JVMs.
+ */
+public class LemmatizerMELocaleTest {
+
+ /**
+ * Turkish folds {@code 'I'} to the dotless {@code 'ı'} (U+0131) instead of {@code 'i'}.
+ */
+ private static final Locale TURKISH = new Locale("tr", "TR");
+
+ private static final String[] TOKENS = {"MICE", "INDICES"};
+ private static final String[] LEMMAS = {"mouse", "index"};
+
+ /** The lemma classes an existing, English trained model contains for {@link #TOKENS}. */
+ private static final String[] LEMMA_CLASSES = {"R2ioR1cuI1s", "D3iD2cR0sx"};
+
+ private final Locale defaultLocale = Locale.getDefault();
+
+ @AfterEach
+ void restoreDefaultLocale() {
+ Locale.setDefault(defaultLocale);
+ }
+
+ /**
+ * Training on a Turkish JVM must not write different outcome labels into the model.
+ */
+ @Test
+ void testEncodeLemmasIsIndependentOfDefaultLocale() {
+ Locale.setDefault(TURKISH);
+
+ Assertions.assertArrayEquals(LEMMA_CLASSES, LemmatizerME.encodeLemmas(TOKENS, LEMMAS));
+ }
+
+ /**
+ * Serving an existing model on a Turkish JVM must not corrupt the reconstructed lemmas.
+ */
+ @Test
+ void testDecodeLemmasIsIndependentOfDefaultLocale() {
+ Locale.setDefault(TURKISH);
+
+ Assertions.assertArrayEquals(LEMMAS, LemmatizerME.decodeLemmas(TOKENS, LEMMA_CLASSES));
+ }
+}
diff --git a/opennlp-tools/src/test/java/opennlp/tools/util/StringUtilLocaleTest.java b/opennlp-tools/src/test/java/opennlp/tools/util/StringUtilLocaleTest.java
new file mode 100644
index 000000000..11a5d0603
--- /dev/null
+++ b/opennlp-tools/src/test/java/opennlp/tools/util/StringUtilLocaleTest.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package opennlp.tools.util;
+
+import java.util.Locale;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Tests that the {@link StringUtil} operations feeding the lemmatizer's shortest edit script
+ * are independent of the JVM's default {@link Locale}.
+ */
+public class StringUtilLocaleTest {
+
+ /**
+ * Turkish folds {@code 'I'} to the dotless {@code 'ı'} (U+0131) instead of {@code 'i'},
+ * which makes it the canonical probe for an unqualified {@code String#toLowerCase()}.
+ */
+ private static final Locale TURKISH = new Locale("tr", "TR");
+
+ private final Locale defaultLocale = Locale.getDefault();
+
+ @AfterEach
+ void restoreDefaultLocale() {
+ Locale.setDefault(defaultLocale);
+ }
+
+ /**
+ * The shortest edit script becomes an outcome label inside a trained lemmatizer model.
+ * If it varied with the default locale, a model trained on a Turkish JVM would carry
+ * labels no other JVM could reproduce.
+ */
+ @Test
+ void testGetShortestEditScriptIsIndependentOfDefaultLocale() {
+ Locale.setDefault(TURKISH);
+
+ Assertions.assertEquals("D0s", StringUtil.getShortestEditScript("IMPORTS", "import"));
+ Assertions.assertEquals("R2ioR1cuI1s", StringUtil.getShortestEditScript("MICE", "mouse"));
+ Assertions.assertEquals("D3iD2cR0sx", StringUtil.getShortestEditScript("INDICES", "index"));
+ Assertions.assertEquals("O", StringUtil.getShortestEditScript("Illinois", "illinois"));
+ }
+
+ /**
+ * Guards the choice of {@link Locale#ROOT} over the code point based
+ * {@link StringUtil#toLowerCase(CharSequence)}: the two disagree on context sensitive
+ * mappings such as the Greek final sigma. Existing models were trained with
+ * {@link Locale#ROOT} semantics, so only {@link Locale#ROOT} keeps them readable.
+ */
+ @Test
+ void testGetShortestEditScriptUsesRootFoldingNotCodePointFolding() {
+ // Locale.ROOT maps the trailing capital sigma to the final form 'ς', so both inputs
+ // fold to the same string and no edit is required.
+ Assertions.assertEquals("O", StringUtil.getShortestEditScript("ΟΔΟΣ",
+ "οδος"));
+
+ // Character#toLowerCase is context free and would yield the non final 'σ' instead,
+ // which is a different string and hence a different, model breaking outcome label.
+ Assertions.assertNotEquals("οδος",
+ StringUtil.toLowerCase("ΟΔΟΣ"));
+ }
+}
diff --git a/opennlp-tools/src/test/java/opennlp/tools/util/TrainingParametersTest.java b/opennlp-tools/src/test/java/opennlp/tools/util/TrainingParametersTest.java
index b5de21392..289c5ae8b 100644
--- a/opennlp-tools/src/test/java/opennlp/tools/util/TrainingParametersTest.java
+++ b/opennlp-tools/src/test/java/opennlp/tools/util/TrainingParametersTest.java
@@ -19,8 +19,10 @@ package opennlp.tools.util;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
+import java.util.Locale;
import java.util.Map;
+import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
@@ -28,6 +30,18 @@ import opennlp.tools.ml.EventTrainer;
public class TrainingParametersTest {
+ /**
+ * Turkish folds {@code 'I'} to the dotless {@code 'ı'} (U+0131) instead of {@code 'i'}.
+ */
+ private static final Locale TURKISH = new Locale("tr", "TR");
+
+ private final Locale defaultLocale = Locale.getDefault();
+
+ @AfterEach
+ void restoreDefaultLocale() {
+ Locale.setDefault(defaultLocale);
+ }
+
@Test
void testConstructors() throws Exception {
TrainingParameters tp1 =
@@ -124,6 +138,28 @@ public class TrainingParametersTest {
TrainingParameters.CUTOFF_DEFAULT_VALUE));
}
+ /**
+ * The switch names are derived by folding the parameter constants, which start with a
+ * capital {@code 'I'} respectively {@code 'C'}. Folding them with the default locale makes
+ * a Turkish JVM look for {@code "-\u0131terations"} and silently train with the defaults.
+ */
+ @Test
+ public void testSetParamsIsIndependentOfDefaultLocale() {
+ String[] args =
+ { "-model" , "en-token-test.bin" , "-lang" , "en" , "-data" ,
+ "en-token.train" , "-encoding" , "UTF-8" , "-cutoff" , "10" , "-iterations" , "50" };
+
+ Locale.setDefault(TURKISH);
+ TrainingParameters tr = TrainingParameters.setParams(args);
+
+ Assertions.assertEquals(50 ,
+ tr.getIntParameter(TrainingParameters.ITERATIONS_PARAM ,
+ TrainingParameters.ITERATIONS_DEFAULT_VALUE));
+ Assertions.assertEquals(10 ,
+ tr.getIntParameter(TrainingParameters.CUTOFF_PARAM ,
+ TrainingParameters.CUTOFF_DEFAULT_VALUE));
+ }
+
@Test
void testGetAlgorithm() {
TrainingParameters tp = build("Algorithm=Perceptron,n1.Algorithm=SVM");