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