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