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