| 1 |
package morfologik.stemming; |
| 2 |
|
| 3 |
import static morfologik.fsa.MatchResult.SEQUENCE_IS_A_PREFIX; |
| 4 |
|
| 5 |
import java.nio.ByteBuffer; |
| 6 |
import java.nio.CharBuffer; |
| 7 |
import java.nio.charset.CharsetDecoder; |
| 8 |
import java.nio.charset.CharsetEncoder; |
| 9 |
import java.util.Arrays; |
| 10 |
import java.util.Iterator; |
| 11 |
import java.util.LinkedHashMap; |
| 12 |
import java.util.List; |
| 13 |
import java.util.Map; |
| 14 |
|
| 15 |
import morfologik.fsa.ByteSequenceIterator; |
| 16 |
import morfologik.fsa.FSA; |
| 17 |
import morfologik.fsa.FSATraversal; |
| 18 |
import morfologik.fsa.MatchResult; |
| 19 |
|
| 20 |
/** |
| 21 |
* This class implements a dictionary lookup of an inflected word over a |
| 22 |
* dictionary previously compiled using the |
| 23 |
* <code>dict_compile</code> tool. |
| 24 |
*/ |
| 25 |
public final class DictionaryLookup implements IStemmer, Iterable<WordData> { |
| 26 |
/** An FSA used for lookups. */ |
| 27 |
private final FSATraversal matcher; |
| 28 |
|
| 29 |
/** An iterator for walking along the final states of {@link #fsa}. */ |
| 30 |
private final ByteSequenceIterator finalStatesIterator; |
| 31 |
|
| 32 |
/** FSA's root node. */ |
| 33 |
private final int rootNode; |
| 34 |
|
| 35 |
/** Expand buffers and arrays by this constant. */ |
| 36 |
private final static int EXPAND_SIZE = 10; |
| 37 |
|
| 38 |
/** Private internal array of reusable word data objects. */ |
| 39 |
private WordData[] forms = new WordData[0]; |
| 40 |
|
| 41 |
/** A "view" over an array implementing */ |
| 42 |
private final ArrayViewList<WordData> formsList = new ArrayViewList<WordData>( |
| 43 |
forms, 0, forms.length); |
| 44 |
|
| 45 |
/** |
| 46 |
* Features of the compiled dictionary. |
| 47 |
* |
| 48 |
* @see DictionaryMetadata |
| 49 |
*/ |
| 50 |
private final DictionaryMetadata dictionaryMetadata; |
| 51 |
|
| 52 |
/** |
| 53 |
* Charset encoder for the FSA. |
| 54 |
*/ |
| 55 |
private final CharsetEncoder encoder; |
| 56 |
|
| 57 |
/** |
| 58 |
* Charset decoder for the FSA. |
| 59 |
*/ |
| 60 |
private final CharsetDecoder decoder; |
| 61 |
|
| 62 |
/** |
| 63 |
* The FSA we are using. |
| 64 |
*/ |
| 65 |
private final FSA fsa; |
| 66 |
|
| 67 |
/** |
| 68 |
* @see #getSeparatorChar() |
| 69 |
*/ |
| 70 |
private final char separatorChar; |
| 71 |
|
| 72 |
/** |
| 73 |
* Internal reusable buffer for encoding words into byte arrays using |
| 74 |
* {@link #encoder}. |
| 75 |
*/ |
| 76 |
private ByteBuffer byteBuffer = ByteBuffer.allocate(0); |
| 77 |
|
| 78 |
/** |
| 79 |
* Internal reusable buffer for encoding words into byte arrays using |
| 80 |
* {@link #encoder}. |
| 81 |
*/ |
| 82 |
private CharBuffer charBuffer = CharBuffer.allocate(0); |
| 83 |
|
| 84 |
/** |
| 85 |
* Reusable match result. |
| 86 |
*/ |
| 87 |
private final MatchResult matchResult = new MatchResult(); |
| 88 |
|
| 89 |
/** |
| 90 |
* The {@link Dictionary} this lookup is using. |
| 91 |
*/ |
| 92 |
private final Dictionary dictionary; |
| 93 |
|
| 94 |
private final ISequenceEncoder sequenceEncoder; |
| 95 |
|
| 96 |
/** |
| 97 |
* Creates a new object of this class using the given FSA for word lookups |
| 98 |
* and encoding for converting characters to bytes. |
| 99 |
* |
| 100 |
* @param dictionary The dictionary to use for lookups. |
| 101 |
* @throws IllegalArgumentException |
| 102 |
* if FSA's root node cannot be acquired (dictionary is empty). |
| 103 |
*/ |
| 104 |
public DictionaryLookup(Dictionary dictionary) |
| 105 |
throws IllegalArgumentException { |
| 106 |
this.dictionary = dictionary; |
| 107 |
this.dictionaryMetadata = dictionary.metadata; |
| 108 |
this.sequenceEncoder = dictionary.metadata.getSequenceEncoderType().get(); |
| 109 |
this.rootNode = dictionary.fsa.getRootNode(); |
| 110 |
this.fsa = dictionary.fsa; |
| 111 |
this.matcher = new FSATraversal(fsa); |
| 112 |
this.finalStatesIterator = new ByteSequenceIterator(fsa, fsa.getRootNode()); |
| 113 |
|
| 114 |
if (dictionaryMetadata == null) { |
| 115 |
throw new IllegalArgumentException( |
| 116 |
"Dictionary metadata must not be null."); |
| 117 |
} |
| 118 |
|
| 119 |
decoder = dictionary.metadata.getDecoder(); |
| 120 |
encoder = dictionary.metadata.getEncoder(); |
| 121 |
separatorChar = dictionary.metadata.getSeparatorAsChar(); |
| 122 |
} |
| 123 |
|
| 124 |
/** |
| 125 |
* Searches the automaton for a symbol sequence equal to <code>word</code>, |
| 126 |
* followed by a separator. The result is a stem (decompressed accordingly |
| 127 |
* to the dictionary's specification) and an optional tag data. |
| 128 |
*/ |
| 129 |
@Override |
| 130 |
public List<WordData> lookup(CharSequence word) { |
| 131 |
final byte separator = dictionaryMetadata.getSeparator(); |
| 132 |
final int prefixBytes = sequenceEncoder.prefixBytes(); |
| 133 |
|
| 134 |
if (!dictionaryMetadata.getInputConversionPairs().isEmpty()) { |
| 135 |
word = applyReplacements(word, dictionaryMetadata.getInputConversionPairs()); |
| 136 |
} |
| 137 |
|
| 138 |
// Reset the output list to zero length. |
| 139 |
formsList.wrap(forms, 0, 0); |
| 140 |
|
| 141 |
// Encode word characters into bytes in the same encoding as the FSA's. |
| 142 |
charBuffer = BufferUtils.clearAndEnsureCapacity(charBuffer, word.length()); |
| 143 |
for (int i = 0; i < word.length(); i++) { |
| 144 |
char chr = word.charAt(i); |
| 145 |
if (chr == separatorChar) { |
| 146 |
// No valid input can contain the separator. |
| 147 |
return formsList; |
| 148 |
} |
| 149 |
charBuffer.put(chr); |
| 150 |
} |
| 151 |
charBuffer.flip(); |
| 152 |
try { |
| 153 |
byteBuffer = BufferUtils.charsToBytes(encoder, charBuffer, byteBuffer); |
| 154 |
} catch (UnmappableInputException e) { |
| 155 |
// This should be a rare occurrence, but if it happens it means there is no way |
| 156 |
// the dictionary can contain the input word. |
| 157 |
return formsList; |
| 158 |
} |
| 159 |
|
| 160 |
// Try to find a partial match in the dictionary. |
| 161 |
final MatchResult match = matcher.match(matchResult, byteBuffer |
| 162 |
.array(), 0, byteBuffer.remaining(), rootNode); |
| 163 |
|
| 164 |
if (match.kind == SEQUENCE_IS_A_PREFIX) { |
| 165 |
/* |
| 166 |
* The entire sequence exists in the dictionary. A separator should |
| 167 |
* be the next symbol. |
| 168 |
*/ |
| 169 |
final int arc = fsa.getArc(match.node, separator); |
| 170 |
|
| 171 |
/* |
| 172 |
* The situation when the arc points to a final node should NEVER |
| 173 |
* happen. After all, we want the word to have SOME base form. |
| 174 |
*/ |
| 175 |
if (arc != 0 && !fsa.isArcFinal(arc)) { |
| 176 |
// There is such a word in the dictionary. Return its base forms. |
| 177 |
int formsCount = 0; |
| 178 |
|
| 179 |
finalStatesIterator.restartFrom(fsa.getEndNode(arc)); |
| 180 |
while (finalStatesIterator.hasNext()) { |
| 181 |
final ByteBuffer bb = finalStatesIterator.next(); |
| 182 |
final byte[] ba = bb.array(); |
| 183 |
final int bbSize = bb.remaining(); |
| 184 |
|
| 185 |
if (formsCount >= forms.length) { |
| 186 |
forms = Arrays.copyOf(forms, forms.length + EXPAND_SIZE); |
| 187 |
for (int k = 0; k < forms.length; k++) { |
| 188 |
if (forms[k] == null) |
| 189 |
forms[k] = new WordData(decoder); |
| 190 |
} |
| 191 |
} |
| 192 |
|
| 193 |
/* |
| 194 |
* Now, expand the prefix/ suffix 'compression' and store |
| 195 |
* the base form. |
| 196 |
*/ |
| 197 |
final WordData wordData = forms[formsCount++]; |
| 198 |
if (dictionaryMetadata.getOutputConversionPairs().isEmpty()) { |
| 199 |
wordData.update(byteBuffer, word); |
| 200 |
} else { |
| 201 |
wordData.update(byteBuffer, applyReplacements(word, dictionaryMetadata.getOutputConversionPairs())); |
| 202 |
} |
| 203 |
|
| 204 |
/* |
| 205 |
* Find the separator byte's position splitting the inflection instructions |
| 206 |
* from the tag. |
| 207 |
*/ |
| 208 |
assert prefixBytes <= bbSize : sequenceEncoder.getClass() + " >? " + bbSize; |
| 209 |
int sepPos; |
| 210 |
for (sepPos = prefixBytes; sepPos < bbSize; sepPos++) { |
| 211 |
if (ba[sepPos] == separator) { |
| 212 |
break; |
| 213 |
} |
| 214 |
} |
| 215 |
|
| 216 |
/* |
| 217 |
* Decode the stem into stem buffer. |
| 218 |
*/ |
| 219 |
wordData.stemBuffer = sequenceEncoder.decode(wordData.stemBuffer, |
| 220 |
byteBuffer, |
| 221 |
ByteBuffer.wrap(ba, 0, sepPos)); |
| 222 |
|
| 223 |
// Skip separator character. |
| 224 |
sepPos++; |
| 225 |
|
| 226 |
/* |
| 227 |
* Decode the tag data. |
| 228 |
*/ |
| 229 |
final int tagSize = bbSize - sepPos; |
| 230 |
if (tagSize > 0) { |
| 231 |
wordData.tagBuffer = BufferUtils.clearAndEnsureCapacity(wordData.tagBuffer, tagSize); |
| 232 |
wordData.tagBuffer.put(ba, sepPos, tagSize); |
| 233 |
wordData.tagBuffer.flip(); |
| 234 |
} |
| 235 |
} |
| 236 |
|
| 237 |
formsList.wrap(forms, 0, formsCount); |
| 238 |
} |
| 239 |
} else { |
| 240 |
/* |
| 241 |
* this case is somewhat confusing: we should have hit the separator |
| 242 |
* first... I don't really know how to deal with it at the time |
| 243 |
* being. |
| 244 |
*/ |
| 245 |
} |
| 246 |
return formsList; |
| 247 |
} |
| 248 |
|
| 249 |
/** |
| 250 |
* Apply partial string replacements from a given map. |
| 251 |
* |
| 252 |
* Useful if the word needs to be normalized somehow (i.e., ligatures, |
| 253 |
* apostrophes and such). |
| 254 |
* |
| 255 |
* @param word The word to apply replacements to. |
| 256 |
* @param replacements A map of replacements (from->to). |
| 257 |
* @return new string with all replacements applied. |
| 258 |
*/ |
| 259 |
public static String applyReplacements(CharSequence word, LinkedHashMap<String, String> replacements) { |
| 260 |
// quite horrible from performance point of view; this should really be a transducer. |
| 261 |
StringBuilder sb = new StringBuilder(word); |
| 262 |
for (final Map.Entry<String, String> e : replacements.entrySet()) { |
| 263 |
String key = e.getKey(); |
| 264 |
int index = sb.indexOf(e.getKey()); |
| 265 |
while (index != -1) { |
| 266 |
sb.replace(index, index + key.length(), e.getValue()); |
| 267 |
index = sb.indexOf(key, index + key.length()); |
| 268 |
} |
| 269 |
} |
| 270 |
return sb.toString(); |
| 271 |
} |
| 272 |
|
| 273 |
/** |
| 274 |
* Return an iterator over all {@link WordData} entries available in the |
| 275 |
* embedded {@link Dictionary}. |
| 276 |
*/ |
| 277 |
@Override |
| 278 |
public Iterator<WordData> iterator() { |
| 279 |
return new DictionaryIterator(dictionary, decoder, true); |
| 280 |
} |
| 281 |
|
| 282 |
/** |
| 283 |
* @return Return the {@link Dictionary} used by this object. |
| 284 |
*/ |
| 285 |
public Dictionary getDictionary() { |
| 286 |
return dictionary; |
| 287 |
} |
| 288 |
|
| 289 |
/** |
| 290 |
* @return Returns the logical separator character splitting inflected form, |
| 291 |
* lemma correction token and a tag. Note that this character is a best-effort |
| 292 |
* conversion from a byte in {@link DictionaryMetadata#separator} and |
| 293 |
* may not be valid in the target encoding (although this is highly unlikely). |
| 294 |
*/ |
| 295 |
public char getSeparatorChar() { |
| 296 |
return separatorChar; |
| 297 |
} |
| 298 |
} |