Skip to content

Apache Lucene open-source search software

LUCENE-9253: Support custom dictionaries in KoreanTokenizer

Namgyu Kimb2dbd18f96e0
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index d99e43110b9..e48d12232ab 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -179,6 +179,8 @@ Improvements
* LUCENE-9237: Faster UniformSplit intersect TermsEnum. (Bruno Roustant)
+* LUCENE-9253: KoreanTokenizer now supports custom dictionaries(system, unknown). (Namgyu Kim)
+
Optimizations
---------------------
diff --git a/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/KoreanTokenizer.java b/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/KoreanTokenizer.java
index 3efccaf575e..136fd0ea0e3 100644
--- a/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/KoreanTokenizer.java
+++ b/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/KoreanTokenizer.java
@@ -164,37 +164,64 @@ public final class KoreanTokenizer extends Tokenizer {
}
/**
- * Create a new KoreanTokenizer.
+ * Create a new KoreanTokenizer using the system and unknown dictionaries shipped with Lucene.
*
* @param factory the AttributeFactory to use
* @param userDictionary Optional: if non-null, user dictionary.
* @param mode Decompound mode.
- * @param outputUnknownUnigrams If true outputs unigrams for unknown words.
+ * @param outputUnknownUnigrams if true outputs unigrams for unknown words.
*/
public KoreanTokenizer(AttributeFactory factory, UserDictionary userDictionary, DecompoundMode mode, boolean outputUnknownUnigrams) {
this(factory, userDictionary, mode, outputUnknownUnigrams, true);
}
/**
- * Create a new KoreanTokenizer.
+ * Create a new KoreanTokenizer using the system and unknown dictionaries shipped with Lucene.
*
* @param factory the AttributeFactory to use
* @param userDictionary Optional: if non-null, user dictionary.
* @param mode Decompound mode.
- * @param outputUnknownUnigrams If true outputs unigrams for unknown words.
+ * @param outputUnknownUnigrams if true outputs unigrams for unknown words.
* @param discardPunctuation true if punctuation tokens should be dropped from the output.
*/
public KoreanTokenizer(AttributeFactory factory, UserDictionary userDictionary, DecompoundMode mode, boolean outputUnknownUnigrams, boolean discardPunctuation) {
+ this(factory,
+ TokenInfoDictionary.getInstance(),
+ UnknownDictionary.getInstance(),
+ ConnectionCosts.getInstance(),
+ userDictionary, mode, outputUnknownUnigrams, discardPunctuation);
+ }
+
+ /**
+ * <p>Create a new KoreanTokenizer supplying a custom system dictionary and unknown dictionary.
+ * This constructor provides an entry point for users that want to construct custom language models
+ * that can be used as input to {@link org.apache.lucene.analysis.ko.util.DictionaryBuilder}.</p>
+ *
+ * @param factory the AttributeFactory to use
+ * @param systemDictionary a custom known token dictionary
+ * @param unkDictionary a custom unknown token dictionary
+ * @param connectionCosts custom token transition costs
+ * @param userDictionary Optional: if non-null, user dictionary.
+ * @param mode Decompound mode.
+ * @param outputUnknownUnigrams if true outputs unigrams for unknown words.
+ * @param discardPunctuation true if punctuation tokens should be dropped from the output.
+ * @lucene.experimental
+ */
+ public KoreanTokenizer(AttributeFactory factory,
+ TokenInfoDictionary systemDictionary,
+ UnknownDictionary unkDictionary,
+ ConnectionCosts connectionCosts,
+ UserDictionary userDictionary,
+ DecompoundMode mode,
+ boolean outputUnknownUnigrams,
+ boolean discardPunctuation) {
super(factory);
- this.mode = mode;
- this.discardPunctuation = discardPunctuation;
- this.outputUnknownUnigrams = outputUnknownUnigrams;
- dictionary = TokenInfoDictionary.getInstance();
- fst = dictionary.getFST();
- unkDictionary = UnknownDictionary.getInstance();
- characterDefinition = unkDictionary.getCharacterDefinition();
+ this.dictionary = systemDictionary;
+ this.fst = dictionary.getFST();
+ this.unkDictionary = unkDictionary;
+ this.characterDefinition = unkDictionary.getCharacterDefinition();
+ this.costs = connectionCosts;
this.userDictionary = userDictionary;
- costs = ConnectionCosts.getInstance();
fstReader = fst.getBytesReader();
if (userDictionary != null) {
userFST = userDictionary.getFST();
@@ -203,7 +230,9 @@ public final class KoreanTokenizer extends Tokenizer {
userFST = null;
userFSTReader = null;
}
-
+ this.mode = mode;
+ this.outputUnknownUnigrams = outputUnknownUnigrams;
+ this.discardPunctuation = discardPunctuation;
buffer.reset(this.input);
resetState();
diff --git a/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/dict/BinaryDictionary.java b/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/dict/BinaryDictionary.java
index 4d8074c0f45..9698d0fee35 100644
--- a/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/dict/BinaryDictionary.java
+++ b/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/dict/BinaryDictionary.java
@@ -150,7 +150,18 @@ public abstract class BinaryDictionary implements Dictionary {
throw new IllegalStateException("unknown resource scheme " + resourceScheme);
}
}
-
+
+ public static InputStream getResource(ResourceScheme scheme, String path) throws IOException {
+ switch(scheme) {
+ case CLASSPATH:
+ return getClassResource(path);
+ case FILE:
+ return Files.newInputStream(Paths.get(path));
+ default:
+ throw new IllegalStateException("unknown resource scheme " + scheme);
+ }
+ }
+
// util, reused by ConnectionCosts and CharacterDefinition
public static InputStream getClassResource(Class<?> clazz, String suffix) throws IOException {
final InputStream is = clazz.getResourceAsStream(clazz.getSimpleName() + suffix);
@@ -160,7 +171,7 @@ public abstract class BinaryDictionary implements Dictionary {
return is;
}
- private InputStream getClassResource(String path) throws IOException {
+ private static InputStream getClassResource(String path) throws IOException {
final InputStream is = BinaryDictionary.class.getClassLoader().getResourceAsStream(path);
if (is == null) {
throw new FileNotFoundException("Not in classpath: " + path);
diff --git a/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/dict/ConnectionCosts.java b/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/dict/ConnectionCosts.java
index 36cbe1519d5..3d67897d34d 100644
--- a/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/dict/ConnectionCosts.java
+++ b/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/dict/ConnectionCosts.java
@@ -38,12 +38,16 @@ public final class ConnectionCosts {
private final ByteBuffer buffer;
private final int forwardSize;
- private ConnectionCosts() throws IOException {
+ /**
+ * @param scheme - scheme for loading resources (FILE or CLASSPATH).
+ * @param resourcePath - where to load resources from, without the ".dat" suffix
+ */
+ public ConnectionCosts(BinaryDictionary.ResourceScheme scheme, String resourcePath) throws IOException {
InputStream is = null;
ByteBuffer buffer;
boolean success = false;
try {
- is = BinaryDictionary.getClassResource(getClass(), FILENAME_SUFFIX);
+ is = BinaryDictionary.getResource(scheme, resourcePath.replace('.', '/') + FILENAME_SUFFIX);
is = new BufferedInputStream(is);
final DataInput in = new InputStreamDataInput(is);
CodecUtil.checkHeader(in, HEADER, VERSION, VERSION);
@@ -71,7 +75,11 @@ public final class ConnectionCosts {
}
this.buffer = buffer;
}
-
+
+ private ConnectionCosts() throws IOException {
+ this(BinaryDictionary.ResourceScheme.CLASSPATH, ConnectionCosts.class.getName());
+ }
+
public int get(int forwardId, int backwardId) {
// map 2d matrix into a single dimension short array
int offset = (backwardId * forwardSize + forwardId) * 2;
diff --git a/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/dict/TokenInfoDictionary.java b/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/dict/TokenInfoDictionary.java
index 02481e12e0e..b2932933515 100644
--- a/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/dict/TokenInfoDictionary.java
+++ b/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/dict/TokenInfoDictionary.java
@@ -43,7 +43,7 @@ public final class TokenInfoDictionary extends BinaryDictionary {
* @param resourcePath - where to load resources (dictionaries) from. If null, with CLASSPATH scheme only, use
* this class's name as the path.
*/
- TokenInfoDictionary(ResourceScheme resourceScheme, String resourcePath) throws IOException {
+ public TokenInfoDictionary(ResourceScheme resourceScheme, String resourcePath) throws IOException {
super(resourceScheme, resourcePath);
FST<Long> fst;
try (InputStream is = new BufferedInputStream(getResource(FST_FILENAME_SUFFIX))) {
diff --git a/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/dict/UnknownDictionary.java b/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/dict/UnknownDictionary.java
index 6d56b9290d3..8c5ac3b65d0 100644
--- a/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/dict/UnknownDictionary.java
+++ b/lucene/analysis/nori/src/java/org/apache/lucene/analysis/ko/dict/UnknownDictionary.java
@@ -25,6 +25,15 @@ import java.io.IOException;
public final class UnknownDictionary extends BinaryDictionary {
private final CharacterDefinition characterDefinition = CharacterDefinition.getInstance();
+ /**
+ * @param scheme scheme for loading resources (FILE or CLASSPATH).
+ * @param resourcePath where to load resources from; a path, including the file base name without
+ * extension; this is used to match multiple files with the same base name.
+ */
+ public UnknownDictionary(ResourceScheme scheme, String resourcePath) throws IOException {
+ super(scheme, resourcePath);
+ }
+
private UnknownDictionary() throws IOException {
super();
}
diff --git a/lucene/analysis/nori/src/test/org/apache/lucene/analysis/ko/TestKoreanTokenizer.java b/lucene/analysis/nori/src/test/org/apache/lucene/analysis/ko/TestKoreanTokenizer.java
index 6e2e795e87a..2deb2139691 100644
--- a/lucene/analysis/nori/src/test/org/apache/lucene/analysis/ko/TestKoreanTokenizer.java
+++ b/lucene/analysis/nori/src/test/org/apache/lucene/analysis/ko/TestKoreanTokenizer.java
@@ -29,6 +29,10 @@ import org.apache.lucene.analysis.MockGraphTokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.ko.KoreanTokenizer.DecompoundMode;
+import org.apache.lucene.analysis.ko.dict.BinaryDictionary.ResourceScheme;
+import org.apache.lucene.analysis.ko.dict.ConnectionCosts;
+import org.apache.lucene.analysis.ko.dict.TokenInfoDictionary;
+import org.apache.lucene.analysis.ko.dict.UnknownDictionary;
import org.apache.lucene.analysis.ko.dict.UserDictionary;
import org.apache.lucene.analysis.ko.tokenattributes.PartOfSpeechAttribute;
import org.apache.lucene.analysis.ko.tokenattributes.ReadingAttribute;
@@ -357,6 +361,28 @@ public class TestKoreanTokenizer extends BaseTokenStreamTestCase {
);
}
+ // Make sure loading custom dictionaries from classpath works:
+ public void testCustomDictionary() throws Exception {
+ Tokenizer tokenizer = new KoreanTokenizer(newAttributeFactory(),
+ new TokenInfoDictionary(ResourceScheme.CLASSPATH, "org/apache/lucene/analysis/ko/dict/TokenInfoDictionary"),
+ new UnknownDictionary(ResourceScheme.CLASSPATH, "org/apache/lucene/analysis/ko/dict/UnknownDictionary"),
+ new ConnectionCosts(ResourceScheme.CLASSPATH, "org/apache/lucene/analysis/ko/dict/ConnectionCosts"),
+ readDict(), DecompoundMode.NONE, false, false);
+ try (Analyzer a = new Analyzer() {
+ @Override
+ protected Analyzer.TokenStreamComponents createComponents(String fieldName) {
+ return new Analyzer.TokenStreamComponents(tokenizer, tokenizer);
+ }
+ }) {
+ assertTokenStreamContents(a.tokenStream("foo", "커스텀사전검사"),
+ new String[] { "커스텀", "사전", "검사" },
+ new int[] { 0, 3, 5 },
+ new int[] { 3, 5, 7 },
+ 7
+ );
+ }
+ }
+
public void testInterpunct() throws IOException {
assertAnalyzesTo(analyzer, "도로ㆍ지반ㆍ수자원ㆍ건설환경ㆍ건축ㆍ화재설비연구",
new String[]{"도로", "지반", "수자원", "건설", "환경", "건축", "화재", "설비", "연구"},