]> gitweb.fperrin.net Git - Dictionary.git/blob - src/com/hughes/android/dictionary/engine/Index.java
0c07472dabf207f82c1e206785d2a5471d67ce84
[Dictionary.git] / src / com / hughes / android / dictionary / engine / Index.java
1 // Copyright 2011 Google Inc. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package com.hughes.android.dictionary.engine;
16
17 import java.io.DataInput;
18 import java.io.DataOutput;
19 import java.io.IOException;
20 import java.io.PrintStream;
21 import java.io.RandomAccessFile;
22 import java.util.AbstractList;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.Comparator;
27 import java.util.EnumMap;
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Set;
33 import java.util.concurrent.atomic.AtomicBoolean;
34 import java.util.regex.Pattern;
35
36 import com.hughes.android.dictionary.DictionaryInfo;
37 import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
38 import com.hughes.android.dictionary.engine.RowBase.RowKey;
39 import com.hughes.util.CachingList;
40 import com.hughes.util.DataInputBuffer;
41 import com.hughes.util.StringUtil;
42 import com.hughes.util.TransformingList;
43 import com.hughes.util.raf.RAFList;
44 import com.hughes.util.raf.RAFSerializer;
45 import com.hughes.util.raf.UniformRAFList;
46 import com.ibm.icu.text.Transliterator;
47
48 public final class Index {
49
50     private static final int CACHE_SIZE = 5000;
51
52     public final Dictionary dict;
53
54     public final String shortName; // Typically the ISO code for the language.
55     public final String longName;
56
57     // persisted: tells how the entries are sorted.
58     public final Language sortLanguage;
59     public final String normalizerRules;
60
61     // Built from the two above.
62     private Transliterator normalizer;
63
64     // persisted
65     public final List<IndexEntry> sortedIndexEntries;
66
67     // persisted.
68     public final Set<String> stoplist;
69
70     // One big list!
71     // Various sub-types.
72     // persisted
73     public final List<RowBase> rows;
74     public final boolean swapPairEntries;
75
76     // Version 2:
77     @SuppressWarnings("WeakerAccess")
78     public int mainTokenCount = -1;
79
80     // --------------------------------------------------------------------------
81
82     public Index(final Dictionary dict, final String shortName, final String longName,
83                  final Language sortLanguage, final String normalizerRules,
84                  final boolean swapPairEntries, final Set<String> stoplist) {
85         this.dict = dict;
86         this.shortName = shortName;
87         this.longName = longName;
88         this.sortLanguage = sortLanguage;
89         this.normalizerRules = normalizerRules;
90         this.swapPairEntries = swapPairEntries;
91         sortedIndexEntries = new ArrayList<>();
92         this.stoplist = stoplist;
93         rows = new ArrayList<>();
94
95         normalizer = null;
96     }
97
98     /**
99      * Deferred initialization because it can be slow.
100      */
101     @SuppressWarnings("WeakerAccess")
102     public synchronized Transliterator normalizer() {
103         if (normalizer == null) {
104             normalizer = TransliteratorManager.get(normalizerRules);
105         }
106         return normalizer;
107     }
108
109     /**
110      * Note that using this comparator probably involves doing too many text
111      * normalizations.
112      */
113     @SuppressWarnings("WeakerAccess")
114     public NormalizeComparator getSortComparator() {
115         return new NormalizeComparator(normalizer(), sortLanguage.getCollator(), dict.dictFileVersion);
116     }
117
118     public Index(final Dictionary dict, final DataInputBuffer raf) throws IOException {
119         this.dict = dict;
120         shortName = raf.readUTF();
121         longName = raf.readUTF();
122         final String languageCode = raf.readUTF();
123         sortLanguage = Language.lookup(languageCode);
124         normalizerRules = raf.readUTF();
125         swapPairEntries = raf.readBoolean();
126         if (dict.dictFileVersion >= 2) {
127             mainTokenCount = raf.readInt();
128         }
129         sortedIndexEntries = CachingList.create(
130                                  RAFList.create(raf, new IndexEntrySerializer(),
131                                                 dict.dictFileVersion, dict.dictInfo + " idx " + languageCode + ": "), CACHE_SIZE, true);
132         if (dict.dictFileVersion >= 7) {
133             int count = StringUtil.readVarInt(raf);
134             stoplist = new HashSet<>(count);
135             for (int i = 0; i < count; ++i) {
136                 stoplist.add(raf.readUTF());
137             }
138         } else if (dict.dictFileVersion >= 4) {
139             stoplist = new HashSet<>();
140             raf.readInt(); // length
141             raf.skipBytes(18);
142             byte b = raf.readByte();
143             raf.skipBytes(b == 'L' ? 71 : 33);
144             while ((b = raf.readByte()) == 0x74) {
145                 stoplist.add(raf.readUTF());
146             }
147             if (b != 0x78) throw new IOException("Invalid data in dictionary stoplist!");
148         } else {
149             stoplist = Collections.emptySet();
150         }
151         rows = CachingList.create(
152                    UniformRAFList.create(raf, new RowBase.Serializer(this)),
153                    CACHE_SIZE, true);
154     }
155
156     public void write(final DataOutput out) throws IOException {
157         RandomAccessFile raf = (RandomAccessFile)out;
158         raf.writeUTF(shortName);
159         raf.writeUTF(longName);
160         raf.writeUTF(sortLanguage.getIsoCode());
161         raf.writeUTF(normalizerRules);
162         raf.writeBoolean(swapPairEntries);
163         raf.writeInt(mainTokenCount);
164         RAFList.write(raf, sortedIndexEntries, new IndexEntrySerializer(), 32, true);
165         StringUtil.writeVarInt(raf, stoplist.size());
166         for (String i : stoplist) {
167             raf.writeUTF(i);
168         }
169         UniformRAFList.write(raf, rows, new RowBase.Serializer(this), 3 /* bytes per entry */);
170     }
171
172     public void print(final PrintStream out) {
173         for (final RowBase row : rows) {
174             row.print(out);
175         }
176     }
177
178     private final class IndexEntrySerializer implements RAFSerializer<IndexEntry> {
179         @Override
180         public IndexEntry read(DataInput raf) throws IOException {
181             return new IndexEntry(Index.this, raf);
182         }
183
184         @Override
185         public void write(DataOutput raf, IndexEntry t) throws IOException {
186             t.write(raf);
187         }
188     }
189
190     public static final class IndexEntry {
191         public final String token;
192         private final String normalizedToken;
193         public final int startRow;
194         final int numRows; // doesn't count the token row!
195         public List<HtmlEntry> htmlEntries;
196
197         public IndexEntry(final Index index, final String token, final String normalizedToken,
198                           final int startRow, final int numRows) {
199             assert token.equals(token.trim());
200             assert token.length() > 0;
201             this.token = token;
202             this.normalizedToken = normalizedToken;
203             this.startRow = startRow;
204             this.numRows = numRows;
205             this.htmlEntries = new ArrayList<>();
206         }
207
208         IndexEntry(final Index index, final DataInput raf) throws IOException {
209             token = raf.readUTF();
210             if (index.dict.dictFileVersion >= 7) {
211                 startRow = StringUtil.readVarInt(raf);
212                 numRows = StringUtil.readVarInt(raf);
213             } else {
214                 startRow = raf.readInt();
215                 numRows = raf.readInt();
216             }
217             final boolean hasNormalizedForm = raf.readBoolean();
218             normalizedToken = hasNormalizedForm ? raf.readUTF() : token;
219             if (index.dict.dictFileVersion >= 7) {
220                 int size = StringUtil.readVarInt(raf);
221                 if (size == 0) {
222                     this.htmlEntries = Collections.emptyList();
223                 } else {
224                     final int[] htmlEntryIndices = new int[size];
225                     for (int i = 0; i < size; ++i) {
226                         htmlEntryIndices[i] = StringUtil.readVarInt(raf);
227                     }
228                     this.htmlEntries = new AbstractList<HtmlEntry>() {
229                         @Override
230                         public HtmlEntry get(int i) {
231                             return index.dict.htmlEntries.get(htmlEntryIndices[i]);
232                         }
233
234                         @Override
235                         public int size() {
236                             return htmlEntryIndices.length;
237                         }
238                     };
239                 }
240             } else if (index.dict.dictFileVersion >= 6) {
241                 this.htmlEntries = CachingList.create(
242                                        RAFList.create((DataInputBuffer)raf, index.dict.htmlEntryIndexSerializer,
243                                                       index.dict.dictFileVersion,
244                                                       index.dict.dictInfo + " htmlEntries: "), 1, false);
245             } else {
246                 this.htmlEntries = Collections.emptyList();
247             }
248         }
249
250         public void write(DataOutput raf) throws IOException {
251             raf.writeUTF(token);
252             StringUtil.writeVarInt(raf, startRow);
253             StringUtil.writeVarInt(raf, numRows);
254             final boolean hasNormalizedForm = !token.equals(normalizedToken);
255             raf.writeBoolean(hasNormalizedForm);
256             if (hasNormalizedForm) {
257                 raf.writeUTF(normalizedToken);
258             }
259             StringUtil.writeVarInt(raf, htmlEntries.size());
260             for (HtmlEntry e : htmlEntries)
261                 StringUtil.writeVarInt(raf, e.index());
262         }
263
264         public String toString() {
265             return String.format("%s@%d(%d)", token, startRow, numRows);
266         }
267
268         String normalizedToken() {
269             return normalizedToken;
270         }
271     }
272
273     private static final TransformingList.Transformer<IndexEntry, String> INDEX_ENTRY_TO_TOKEN = new TransformingList.Transformer<IndexEntry, String>() {
274         @Override
275         public String transform(IndexEntry t1) {
276             return t1.token;
277         }
278     };
279
280     public IndexEntry findExact(final String exactToken) {
281         final int result = Collections.binarySearch(
282                                TransformingList.create(sortedIndexEntries, INDEX_ENTRY_TO_TOKEN), exactToken,
283                                getSortComparator());
284         if (result >= 0) {
285             return sortedIndexEntries.get(result);
286         }
287         return null;
288     }
289
290     public IndexEntry findInsertionPoint(String token, final AtomicBoolean interrupted) {
291         final int index = findInsertionPointIndex(token, interrupted);
292         return index != -1 ? sortedIndexEntries.get(index) : null;
293     }
294
295     private int compareIdx(String token, final Comparator<Object> sortCollator, int idx) {
296         final IndexEntry entry = sortedIndexEntries.get(idx);
297         return NormalizeComparator.compareWithoutDash(token, entry.normalizedToken(), sortCollator, dict.dictFileVersion);
298     }
299
300     private int findMatchLen(final Comparator<Object> sortCollator, String a, String b) {
301         int start = 0;
302         int end = Math.min(a.length(), b.length());
303         while (start < end)
304         {
305             int mid = (start + end + 1) / 2;
306             if (sortCollator.compare(a.substring(0, mid), b.substring(0, mid)) == 0)
307                 start = mid;
308             else
309                 end = mid - 1;
310         }
311         return start;
312     }
313
314     private int findInsertionPointIndex(String token, final AtomicBoolean interrupted) {
315         String orig_token = token;
316         token = normalizeToken(token);
317
318         int start = 0;
319         int end = sortedIndexEntries.size();
320
321         final Comparator<Object> sortCollator = sortLanguage.getCollator();
322         while (start < end) {
323             final int mid = (start + end) / 2;
324             if (interrupted.get()) {
325                 return -1;
326             }
327             final IndexEntry midEntry = sortedIndexEntries.get(mid);
328
329             int comp = NormalizeComparator.compareWithoutDash(token, midEntry.normalizedToken(), sortCollator, dict.dictFileVersion);
330             if (comp == 0)
331                 comp = sortCollator.compare(token, midEntry.normalizedToken());
332             if (comp == 0) {
333                 start = end = mid;
334                 break;
335             } else if (comp < 0) {
336                 // System.out.println("Upper bound: " + midEntry + ", norm=" +
337                 // midEntry.normalizedToken() + ", mid=" + mid);
338
339                 // Hack for robustness if sort order is broken
340                 if (mid + 2 < end &&
341                     compareIdx(token, sortCollator, mid + 1) > 0 &&
342                     compareIdx(token, sortCollator, mid + 2) > 0) {
343                     start = mid;
344                 } else {
345                     end = mid;
346                 }
347             } else {
348                 // System.out.println("Lower bound: " + midEntry + ", norm=" +
349                 // midEntry.normalizedToken() + ", mid=" + mid);
350
351                 // Hack for robustness if sort order is broken
352                 if (mid - 2 >= start &&
353                     compareIdx(token, sortCollator, mid - 1) < 0 &&
354                     compareIdx(token, sortCollator, mid - 2) < 0) {
355                     end = mid + 1;
356                 } else {
357                     start = mid + 1;
358                 }
359             }
360         }
361
362         // if the word before is the better match, move
363         // our result to it
364         if (start > 0 && start < sortedIndexEntries.size()) {
365             String prev = sortedIndexEntries.get(start - 1).normalizedToken();
366             String next = sortedIndexEntries.get(start).normalizedToken();
367             if (findMatchLen(sortCollator, token, prev) >= findMatchLen(sortCollator, token, next))
368                 start--;
369         }
370
371         // If the search term was normalized, try to find an exact match first
372         if (!orig_token.equalsIgnoreCase(token)) {
373             int matchLen = findMatchLen(sortCollator, token, sortedIndexEntries.get(start).normalizedToken());
374             int scan = start;
375             while (scan >= 0 && scan < sortedIndexEntries.size()) {
376                 IndexEntry e = sortedIndexEntries.get(scan);
377                 if (e.token.equalsIgnoreCase(orig_token))
378                 {
379                     return scan;
380                 }
381                 if (matchLen > findMatchLen(sortCollator, token, e.normalizedToken()))
382                     break;
383                 if (interrupted.get()) return start;
384                 scan++;
385             }
386         }
387
388         // If we search for a substring of a string that's in there, return
389         // that.
390         int result = Math.min(start, sortedIndexEntries.size() - 1);
391         result = windBackCase(sortedIndexEntries.get(result).normalizedToken(), result, interrupted);
392         return result;
393     }
394
395     private int windBackCase(final String token, int result, final AtomicBoolean interrupted) {
396         while (result > 0 && sortedIndexEntries.get(result - 1).normalizedToken().equals(token)) {
397             --result;
398             if (interrupted.get()) {
399                 return result;
400             }
401         }
402         return result;
403     }
404
405     public IndexInfo getIndexInfo() {
406         return new DictionaryInfo.IndexInfo(shortName, sortedIndexEntries.size(), mainTokenCount);
407     }
408
409     private static final int MAX_SEARCH_ROWS = 1000;
410
411     private final Map<String, Integer> prefixToNumRows = new HashMap<>();
412
413     private synchronized int getUpperBoundOnRowsStartingWith(final String normalizedPrefix,
414                                                              final int maxRows, final AtomicBoolean interrupted) {
415         final Integer numRows = prefixToNumRows.get(normalizedPrefix);
416         if (numRows != null) {
417             return numRows;
418         }
419         final int insertionPointIndex = findInsertionPointIndex(normalizedPrefix, interrupted);
420
421         int rowCount = 0;
422         for (int index = insertionPointIndex; index < sortedIndexEntries.size(); ++index) {
423             if (interrupted.get()) {
424                 return -1;
425             }
426             final IndexEntry indexEntry = sortedIndexEntries.get(index);
427             if (!indexEntry.normalizedToken.startsWith(normalizedPrefix) &&
428                 !NormalizeComparator.withoutDash(indexEntry.normalizedToken).startsWith(normalizedPrefix)) {
429                 break;
430             }
431             rowCount += indexEntry.numRows + indexEntry.htmlEntries.size();
432             if (rowCount > maxRows) {
433                 System.out.println("Giving up, too many words with prefix: " + normalizedPrefix);
434                 break;
435             }
436         }
437         prefixToNumRows.put(normalizedPrefix, rowCount);
438         return rowCount;
439     }
440
441     public final List<RowBase> multiWordSearch(
442         final String searchText, final List<String> searchTokens,
443         final AtomicBoolean interrupted) {
444         final long startMills = System.currentTimeMillis();
445         final List<RowBase> result = new ArrayList<>();
446
447         final Set<String> normalizedNonStoplist = new HashSet<>();
448
449         String bestPrefix = null;
450         int leastRows = Integer.MAX_VALUE;
451         final StringBuilder searchTokensRegex = new StringBuilder();
452         for (int i = 0; i < searchTokens.size(); ++i) {
453             if (interrupted.get()) {
454                 return null;
455             }
456             final String searchToken = searchTokens.get(i);
457             final String normalized = normalizeToken(searchTokens.get(i));
458             // Normalize them all.
459             searchTokens.set(i, normalized);
460
461             if (!stoplist.contains(searchToken)) {
462                 if (normalizedNonStoplist.add(normalized)) {
463                     final int numRows = getUpperBoundOnRowsStartingWith(normalized,
464                                         MAX_SEARCH_ROWS, interrupted);
465                     if (numRows != -1 && numRows < leastRows) {
466                         if (numRows == 0) {
467                             // We really are done here.
468                             return Collections.emptyList();
469                         }
470                         leastRows = numRows;
471                         bestPrefix = normalized;
472                     }
473                 }
474             }
475
476             if (searchTokensRegex.length() > 0) {
477                 searchTokensRegex.append("[\\s]*");
478             }
479             searchTokensRegex.append(Pattern.quote(normalized));
480         }
481         final Pattern pattern = Pattern.compile(searchTokensRegex.toString());
482
483         if (bestPrefix == null) {
484             bestPrefix = searchTokens.get(0);
485             System.out.println("Everything was in the stoplist!");
486         }
487         System.out.println("Searching using prefix: " + bestPrefix + ", leastRows=" + leastRows
488                            + ", searchTokens=" + searchTokens);
489
490         // Place to store the things that match.
491         final Map<RowMatchType, List<RowBase>> matches = new EnumMap<>(
492                 RowMatchType.class);
493         for (final RowMatchType rowMatchType : RowMatchType.values()) {
494             if (rowMatchType != RowMatchType.NO_MATCH) {
495                 matches.put(rowMatchType, new ArrayList<RowBase>());
496             }
497         }
498
499         int matchCount = 0;
500
501         final int exactMatchIndex = findInsertionPointIndex(searchText, interrupted);
502         if (exactMatchIndex != -1) {
503             final IndexEntry exactMatch = sortedIndexEntries.get(exactMatchIndex);
504             if (pattern.matcher(exactMatch.token).find()) {
505                 matches.get(RowMatchType.TITLE_MATCH).add(rows.get(exactMatch.startRow));
506             }
507         }
508
509         final String searchToken = bestPrefix;
510         final int insertionPointIndex = findInsertionPointIndex(searchToken, interrupted);
511         final Set<RowKey> rowsAlreadySeen = new HashSet<>();
512         for (int index = insertionPointIndex; index < sortedIndexEntries.size()
513                 && matchCount < MAX_SEARCH_ROWS; ++index) {
514             if (interrupted.get()) {
515                 return null;
516             }
517             final IndexEntry indexEntry = sortedIndexEntries.get(index);
518             if (!indexEntry.normalizedToken.startsWith(searchToken) &&
519                 !NormalizeComparator.withoutDash(indexEntry.normalizedToken).startsWith(searchToken)) {
520                 break;
521             }
522
523             // System.out.println("Searching indexEntry: " + indexEntry.token);
524
525             // Extra +1 to skip token row.
526             for (int rowIndex = indexEntry.startRow + 1; rowIndex < indexEntry.startRow + 1
527                     + indexEntry.numRows
528                     && rowIndex < rows.size(); ++rowIndex) {
529                 if (interrupted.get()) {
530                     return null;
531                 }
532                 final RowBase row = rows.get(rowIndex);
533                 final RowBase.RowKey rowKey = row.getRowKey();
534                 if (rowsAlreadySeen.contains(rowKey)) {
535                     continue;
536                 }
537                 rowsAlreadySeen.add(rowKey);
538                 final RowMatchType matchType = row.matches(searchTokens, pattern, normalizer(),
539                                                swapPairEntries);
540                 if (matchType != RowMatchType.NO_MATCH) {
541                     matches.get(matchType).add(row);
542                     ++matchCount;
543                 }
544             }
545         }
546         // } // searchTokens
547
548         // Sort them into a reasonable order.
549         final RowBase.LengthComparator lengthComparator = new RowBase.LengthComparator(
550             swapPairEntries);
551         for (final Collection<RowBase> rows : matches.values()) {
552             final List<RowBase> ordered = new ArrayList<>(rows);
553             Collections.sort(ordered, lengthComparator);
554             result.addAll(ordered);
555         }
556
557         System.out.println("searchDuration: " + (System.currentTimeMillis() - startMills));
558         return result;
559     }
560
561     private String normalizeToken(final String searchToken) {
562         if (TransliteratorManager.init(null, null)) {
563             final Transliterator normalizer = normalizer();
564             return normalizer.transliterate(searchToken);
565         } else {
566             // Do our best since the Transliterators aren't up yet.
567             return searchToken.toLowerCase();
568         }
569     }
570
571 }