Debian Codegraph @

morfologik-stemming/src/main/java/morfologik/stemming/DictionaryMetadata.java

raw
1 package morfologik.stemming;
2
3 import static morfologik.stemming.DictionaryAttribute.*;
4
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.InputStreamReader;
8 import java.io.Writer;
9 import java.nio.ByteBuffer;
10 import java.nio.CharBuffer;
11 import java.nio.charset.CharacterCodingException;
12 import java.nio.charset.Charset;
13 import java.nio.charset.CharsetDecoder;
14 import java.nio.charset.CharsetEncoder;
15 import java.nio.charset.CodingErrorAction;
16 import java.nio.charset.UnsupportedCharsetException;
17 import java.nio.file.Path;
18 import java.util.Collections;
19 import java.util.EnumMap;
20 import java.util.EnumSet;
21 import java.util.Enumeration;
22 import java.util.HashMap;
23 import java.util.LinkedHashMap;
24 import java.util.List;
25 import java.util.Locale;
26 import java.util.Map;
27 import java.util.Properties;
28
29 /**
30 * Description of attributes, their types and default values.
31 */
32 public final class DictionaryMetadata {
33 /**
34 * Default attribute values.
35 */
36 private static Map<DictionaryAttribute, String> DEFAULT_ATTRIBUTES = new DictionaryMetadataBuilder()
37 .frequencyIncluded(false)
38 .ignorePunctuation()
39 .ignoreNumbers()
40 .ignoreCamelCase()
41 .ignoreAllUppercase()
42 .ignoreDiacritics()
43 .convertCase()
44 .supportRunOnWords()
45 .toMap();
46
47 /**
48 * Required attributes.
49 */
50 private static EnumSet<DictionaryAttribute> REQUIRED_ATTRIBUTES = EnumSet.of(
51 SEPARATOR,
52 ENCODER,
53 ENCODING);
54
55 /**
56 * A separator character between fields (stem, lemma, form). The character
57 * must be within byte range (FSA uses bytes internally).
58 */
59 private byte separator;
60 private char separatorChar;
61
62 /**
63 * Encoding used for converting bytes to characters and vice versa.
64 */
65 private String encoding;
66
67 private Charset charset;
68 private Locale locale = Locale.getDefault();
69
70 /**
71 * Replacement pairs for non-obvious candidate search in a speller dictionary.
72 */
73 private LinkedHashMap<String, List<String>> replacementPairs = new LinkedHashMap<>();
74
75 /**
76 * Conversion pairs for input conversion, for example to replace ligatures.
77 */
78 private LinkedHashMap<String, String> inputConversion = new LinkedHashMap<>();
79
80 /**
81 * Conversion pairs for output conversion, for example to replace ligatures.
82 */
83 private LinkedHashMap<String, String> outputConversion = new LinkedHashMap<>();
84
85 /**
86 * Equivalent characters (treated similarly as equivalent chars with and without
87 * diacritics). For example, Polish <tt>ł</tt> can be specified as equivalent to <tt>l</tt>.
88 *
89 * This implements a feature similar to hunspell MAP in the affix file.
90 */
91 private LinkedHashMap<Character, List<Character>> equivalentChars = new LinkedHashMap<>();
92
93 /**
94 * All attributes.
95 */
96 private final EnumMap<DictionaryAttribute, String> attributes;
97
98 /**
99 * All "enabled" boolean attributes.
100 */
101 private final EnumMap<DictionaryAttribute,Boolean> boolAttributes;
102
103 /**
104 * Sequence encoder.
105 */
106 private EncoderType encoderType;
107
108 /**
109 * Expected metadata file extension.
110 */
111 public final static String METADATA_FILE_EXTENSION = "info";
112
113 /**
114 * @return Return all metadata attributes.
115 */
116 public Map<DictionaryAttribute, String> getAttributes() {
117 return Collections.unmodifiableMap(attributes);
118 }
119
120 // Cached attrs.
121 public String getEncoding() { return encoding; }
122 public byte getSeparator() { return separator; }
123 public Locale getLocale() { return locale; }
124
125 public LinkedHashMap<String, String> getInputConversionPairs() { return inputConversion; }
126 public LinkedHashMap<String, String> getOutputConversionPairs() { return outputConversion; }
127
128 public LinkedHashMap<String, List<String>> getReplacementPairs() { return replacementPairs; }
129 public LinkedHashMap<Character, List<Character>> getEquivalentChars() { return equivalentChars; }
130
131 // Dynamically fetched.
132 public boolean isFrequencyIncluded() { return boolAttributes.get(FREQUENCY_INCLUDED); }
133 public boolean isIgnoringPunctuation() { return boolAttributes.get(IGNORE_PUNCTUATION); }
134 public boolean isIgnoringNumbers() { return boolAttributes.get(IGNORE_NUMBERS); }
135 public boolean isIgnoringCamelCase() { return boolAttributes.get(IGNORE_CAMEL_CASE); }
136 public boolean isIgnoringAllUppercase() { return boolAttributes.get(IGNORE_ALL_UPPERCASE); }
137 public boolean isIgnoringDiacritics() { return boolAttributes.get(IGNORE_DIACRITICS); }
138 public boolean isConvertingCase() { return boolAttributes.get(CONVERT_CASE); }
139 public boolean isSupportingRunOnWords() { return boolAttributes.get(RUN_ON_WORDS); }
140
141 /**
142 * Create an instance from an attribute map.
143 *
144 * @param attrs A set of {@link DictionaryAttribute} keys and their associated values.
145 * @see DictionaryMetadataBuilder
146 */
147 public DictionaryMetadata(Map<DictionaryAttribute, String> attrs) {
148 this.boolAttributes = new EnumMap<DictionaryAttribute,Boolean>(DictionaryAttribute.class);
149 this.attributes = new EnumMap<DictionaryAttribute, String>(DictionaryAttribute.class);
150 this.attributes.putAll(attrs);
151
152 EnumMap<DictionaryAttribute, String> attributeMap = new EnumMap<DictionaryAttribute, String>(DEFAULT_ATTRIBUTES);
153 attributeMap.putAll(attrs);
154
155 // Convert some attrs from the map to local fields for performance reasons.
156 EnumSet<DictionaryAttribute> requiredAttributes = EnumSet.copyOf(REQUIRED_ATTRIBUTES);
157
158 for (Map.Entry<DictionaryAttribute,String> e : attributeMap.entrySet()) {
159 requiredAttributes.remove(e.getKey());
160
161 // Run validation and conversion on all of them.
162 Object value = e.getKey().fromString(e.getValue());
163 switch (e.getKey()) {
164 case ENCODING:
165 this.encoding = e.getValue();
166 if (!Charset.isSupported(encoding)) {
167 throw new IllegalArgumentException("Encoding not supported on this JVM: "
168 + encoding);
169 }
170 this.charset = (Charset) value;
171 break;
172
173 case SEPARATOR:
174 this.separatorChar = (Character) value;
175 break;
176
177 case LOCALE:
178 this.locale = (Locale) value;
179 break;
180
181 case ENCODER:
182 this.encoderType = (EncoderType) value;
183 break;
184
185 case INPUT_CONVERSION:
186 {
187 @SuppressWarnings("unchecked")
188 LinkedHashMap<String, String> gvalue = (LinkedHashMap<String, String>) value;
189 this.inputConversion = gvalue;
190 }
191 break;
192
193 case OUTPUT_CONVERSION:
194 {
195 @SuppressWarnings("unchecked")
196 LinkedHashMap<String, String> gvalue = (LinkedHashMap<String, String>) value;
197 this.outputConversion = gvalue;
198 }
199 break;
200
201 case REPLACEMENT_PAIRS:
202 {
203 @SuppressWarnings("unchecked")
204 LinkedHashMap<String, List<String>> gvalue = (LinkedHashMap<String, List<String>>) value;
205 this.replacementPairs = gvalue;
206 }
207 break;
208
209 case EQUIVALENT_CHARS:
210 {
211 @SuppressWarnings("unchecked")
212 LinkedHashMap<Character, List<Character>> gvalue = (LinkedHashMap<Character, List<Character>>) value;
213 this.equivalentChars = gvalue;
214 }
215 break;
216
217 case IGNORE_PUNCTUATION:
218 case IGNORE_NUMBERS:
219 case IGNORE_CAMEL_CASE:
220 case IGNORE_ALL_UPPERCASE:
221 case IGNORE_DIACRITICS:
222 case CONVERT_CASE:
223 case RUN_ON_WORDS:
224 case FREQUENCY_INCLUDED:
225 this.boolAttributes.put(e.getKey(), (Boolean) value);
226 break;
227
228 case AUTHOR:
229 case LICENSE:
230 case CREATION_DATE:
231 // Just run validation.
232 e.getKey().fromString(e.getValue());
233 break;
234
235 default:
236 throw new RuntimeException("Unexpected code path (attribute should be handled but is not): " + e.getKey());
237 }
238 }
239
240 if (!requiredAttributes.isEmpty()) {
241 throw new IllegalArgumentException("At least one the required attributes was not provided: "
242 + requiredAttributes.toString());
243 }
244
245 // Sanity check.
246 CharsetEncoder encoder = getEncoder();
247 try {
248 ByteBuffer encoded = encoder.encode(CharBuffer.wrap(new char [] { separatorChar }));
249 if (encoded.remaining() > 1) {
250 throw new IllegalArgumentException("Separator character is not a single byte in encoding "
251 + encoding + ": " + separatorChar);
252 }
253 this.separator = encoded.get();
254 } catch (CharacterCodingException e) {
255 throw new IllegalArgumentException("Separator character cannot be converted to a byte in "
256 + encoding + ": " + separatorChar, e);
257 }
258 }
259
260 /**
261 * @return Returns a new {@link CharsetDecoder} for the {@link #encoding}.
262 */
263 public CharsetDecoder getDecoder() {
264 try {
265 return charset.newDecoder()
266 .onMalformedInput(CodingErrorAction.REPORT)
267 .onUnmappableCharacter(CodingErrorAction.REPORT);
268 } catch (UnsupportedCharsetException e) {
269 throw new RuntimeException(
270 "FSA's encoding charset is not supported: " + encoding);
271 }
272 }
273
274 /**
275 * @return Returns a new {@link CharsetEncoder} for the {@link #encoding}.
276 */
277 public CharsetEncoder getEncoder() {
278 try {
279 return charset.newEncoder()
280 .onMalformedInput(CodingErrorAction.REPORT)
281 .onUnmappableCharacter(CodingErrorAction.REPORT);
282 } catch (UnsupportedCharsetException e) {
283 throw new RuntimeException(
284 "FSA's encoding charset is not supported: " + encoding);
285 }
286 }
287
288 /**
289 * @return Return sequence encoder type.
290 */
291 public EncoderType getSequenceEncoderType() {
292 return encoderType;
293 }
294
295 /**
296 * @return Returns the {@link #separator} byte converted to a single
297 * <code>char</code>.
298 * @throws RuntimeException
299 * if this conversion is for some reason impossible (the byte is a
300 * surrogate pair, FSA's {@link #encoding} is not available).
301 */
302 public char getSeparatorAsChar() {
303 return separatorChar;
304 }
305
306 /**
307 * @return A shortcut returning {@link DictionaryMetadataBuilder}.
308 */
309 public static DictionaryMetadataBuilder builder() {
310 return new DictionaryMetadataBuilder();
311 }
312
313 /**
314 * Returns the expected name of the metadata file, based on the name of the
315 * dictionary file. The expected name is resolved by truncating any
316 * file extension of <code>name</code> and appending
317 * {@link DictionaryMetadata#METADATA_FILE_EXTENSION}.
318 *
319 * @param dictionaryFile The name of the dictionary (<code>*.dict</code>) file.
320 * @return Returns the expected name of the metadata file.
321 */
322 public static String getExpectedMetadataFileName(String dictionaryFile) {
323 final int dotIndex = dictionaryFile.lastIndexOf('.');
324 final String featuresName;
325 if (dotIndex >= 0) {
326 featuresName = dictionaryFile.substring(0, dotIndex) + "." + METADATA_FILE_EXTENSION;
327 } else {
328 featuresName = dictionaryFile + "." + METADATA_FILE_EXTENSION;
329 }
330
331 return featuresName;
332 }
333
334 /**
335 * @param dictionary The location of the dictionary file.
336 * @return Returns the expected location of a metadata file.
337 */
338 public static Path getExpectedMetadataLocation(Path dictionary) {
339 return dictionary.resolveSibling(
340 getExpectedMetadataFileName(dictionary.getFileName().toString()));
341 }
342
343 /**
344 * Read dictionary metadata from a property file (stream).
345 *
346 * @param metadataStream The stream with metadata.
347 * @return Returns {@link DictionaryMetadata} read from a the stream (property file).
348 * @throws IOException Thrown if an I/O exception occurs.
349 */
350 public static DictionaryMetadata read(InputStream metadataStream) throws IOException {
351 Map<DictionaryAttribute, String> map = new HashMap<DictionaryAttribute, String>();
352 final Properties properties = new Properties();
353 properties.load(new InputStreamReader(metadataStream, "UTF-8"));
354
355 // Handle back-compatibility for encoder specification.
356 if (!properties.containsKey(DictionaryAttribute.ENCODER.propertyName)) {
357 boolean hasDeprecated = properties.containsKey("fsa.dict.uses-suffixes") ||
358 properties.containsKey("fsa.dict.uses-infixes") ||
359 properties.containsKey("fsa.dict.uses-prefixes");
360
361 boolean usesSuffixes = Boolean.valueOf(properties.getProperty("fsa.dict.uses-suffixes", "true"));
362 boolean usesPrefixes = Boolean.valueOf(properties.getProperty("fsa.dict.uses-prefixes", "false"));
363 boolean usesInfixes = Boolean.valueOf(properties.getProperty("fsa.dict.uses-infixes", "false"));
364
365 final EncoderType encoder;
366 if (usesInfixes) {
367 encoder = EncoderType.INFIX;
368 } else if (usesPrefixes) {
369 encoder = EncoderType.PREFIX;
370 } else if (usesSuffixes) {
371 encoder = EncoderType.SUFFIX;
372 } else {
373 encoder = EncoderType.NONE;
374 }
375
376 if (!hasDeprecated) {
377 throw new IOException("Use an explicit " +
378 DictionaryAttribute.ENCODER.propertyName + "=" + encoder.name() +
379 " metadata key: ");
380 }
381
382 throw new IOException("Deprecated encoder keys in metadata. Use " +
383 DictionaryAttribute.ENCODER.propertyName + "=" + encoder.name());
384 }
385
386 for (Enumeration<?> e = properties.propertyNames(); e.hasMoreElements();) {
387 String key = (String) e.nextElement();
388 map.put(DictionaryAttribute.fromPropertyName(key), properties.getProperty(key));
389 }
390
391 return new DictionaryMetadata(map);
392 }
393
394 /**
395 * Write dictionary attributes (metadata).
396 *
397 * @param writer The writer to write to.
398 * @throws IOException Thrown when an I/O error occurs.
399 */
400 public void write(Writer writer) throws IOException {
401 final Properties properties = new Properties();
402
403 for (Map.Entry<DictionaryAttribute, String> e : getAttributes().entrySet()) {
404 properties.setProperty(e.getKey().propertyName, e.getValue());
405 }
406
407 properties.store(writer, "# " + getClass().getName());
408 }
409 }