blob: d307ba2f866675d09b1bc202b4c874c6c4c13ed6 [file] [log] [blame]
satok30088252010-12-01 21:22:15 +09001/*
2**
3** Copyright 2010, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9** http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
satok48e432c2010-12-06 17:38:58 +090018#include <assert.h>
satok30088252010-12-01 21:22:15 +090019#include <fcntl.h>
satokf5cded12010-12-06 21:28:24 +090020#include <stdio.h>
satok30088252010-12-01 21:22:15 +090021#include <string.h>
22
satoke808e432010-12-02 14:53:24 +090023#define LOG_TAG "LatinIME: unigram_dictionary.cpp"
satok30088252010-12-01 21:22:15 +090024
satok30088252010-12-01 21:22:15 +090025#include "basechars.h"
26#include "char_utils.h"
satoke808e432010-12-02 14:53:24 +090027#include "dictionary.h"
28#include "unigram_dictionary.h"
satok30088252010-12-01 21:22:15 +090029
30namespace latinime {
31
satoke808e432010-12-02 14:53:24 +090032UnigramDictionary::UnigramDictionary(const unsigned char *dict, int typedLetterMultiplier,
33 int fullWordMultiplier, int maxWordLength, int maxWords, int maxAlternatives,
satok18c28f42010-12-02 18:11:54 +090034 const bool isLatestDictVersion)
satoke808e432010-12-02 14:53:24 +090035 : DICT(dict), MAX_WORD_LENGTH(maxWordLength),MAX_WORDS(maxWords),
36 MAX_ALTERNATIVES(maxAlternatives), IS_LATEST_DICT_VERSION(isLatestDictVersion),
satok18c28f42010-12-02 18:11:54 +090037 TYPED_LETTER_MULTIPLIER(typedLetterMultiplier), FULL_WORD_MULTIPLIER(fullWordMultiplier) {
satok30088252010-12-01 21:22:15 +090038 LOGI("UnigramDictionary - constructor");
satok30088252010-12-01 21:22:15 +090039}
40
satok18c28f42010-12-02 18:11:54 +090041UnigramDictionary::~UnigramDictionary() {}
satok30088252010-12-01 21:22:15 +090042
satok18c28f42010-12-02 18:11:54 +090043int UnigramDictionary::getSuggestions(int *codes, int codesSize, unsigned short *outWords,
44 int *frequencies, int *nextLetters, int nextLettersSize)
satok30088252010-12-01 21:22:15 +090045{
46
47 initSuggestions(codes, codesSize, outWords, frequencies);
48
49 int suggestedWordsCount = getSuggestionCandidates(codesSize, -1, nextLetters,
50 nextLettersSize);
51
52 // If there aren't sufficient suggestions, search for words by allowing wild cards at
53 // the different character positions. This feature is not ready for prime-time as we need
54 // to figure out the best ranking for such words compared to proximity corrections and
55 // completions.
56 if (SUGGEST_MISSING_CHARACTERS && suggestedWordsCount < SUGGEST_MISSING_CHARACTERS_THRESHOLD) {
57 for (int i = 0; i < codesSize; ++i) {
58 int tempCount = getSuggestionCandidates(codesSize, i, NULL, 0);
59 if (tempCount > suggestedWordsCount) {
60 suggestedWordsCount = tempCount;
61 break;
62 }
63 }
64 }
65
66 if (DEBUG_DICT) {
67 LOGI("Returning %d words", suggestedWordsCount);
68 LOGI("Next letters: ");
69 for (int k = 0; k < nextLettersSize; k++) {
70 if (nextLetters[k] > 0) {
71 LOGI("%c = %d,", k, nextLetters[k]);
72 }
73 }
74 LOGI("\n");
75 }
76 return suggestedWordsCount;
77}
78
79void UnigramDictionary::initSuggestions(int *codes, int codesSize, unsigned short *outWords,
80 int *frequencies) {
satokf5cded12010-12-06 21:28:24 +090081 if (DEBUG_DICT) LOGI("initSuggest");
satok30088252010-12-01 21:22:15 +090082 mFrequencies = frequencies;
83 mOutputChars = outWords;
84 mInputCodes = codes;
85 mInputLength = codesSize;
86 mMaxEditDistance = mInputLength < 5 ? 2 : mInputLength / 2;
87}
88
89int UnigramDictionary::getSuggestionCandidates(int inputLength, int skipPos,
90 int *nextLetters, int nextLettersSize) {
satokf5cded12010-12-06 21:28:24 +090091 if (DEBUG_DICT) LOGI("getSuggestionCandidates");
satok68319262010-12-03 19:38:08 +090092 int initialPos = 0;
satoke808e432010-12-02 14:53:24 +090093 if (IS_LATEST_DICT_VERSION) {
satok68319262010-12-03 19:38:08 +090094 initialPos = DICTIONARY_HEADER_SIZE;
satok30088252010-12-01 21:22:15 +090095 }
satok68319262010-12-03 19:38:08 +090096 getWords(initialPos, inputLength, skipPos, nextLetters, nextLettersSize);
satok30088252010-12-01 21:22:15 +090097
98 // Get the word count
99 int suggestedWordsCount = 0;
100 while (suggestedWordsCount < MAX_WORDS && mFrequencies[suggestedWordsCount] > 0) {
101 suggestedWordsCount++;
102 }
103 return suggestedWordsCount;
104}
105
satok715514d2010-12-02 20:19:59 +0900106void UnigramDictionary::registerNextLetter(
107 unsigned short c, int *nextLetters, int nextLettersSize) {
satok30088252010-12-01 21:22:15 +0900108 if (c < nextLettersSize) {
109 nextLetters[c]++;
110 }
111}
112
satok28bd03b2010-12-03 16:39:16 +0900113bool UnigramDictionary::addWord(unsigned short *word, int length, int frequency) {
satok30088252010-12-01 21:22:15 +0900114 word[length] = 0;
115 if (DEBUG_DICT) {
116 char s[length + 1];
117 for (int i = 0; i <= length; i++) s[i] = word[i];
118 LOGI("Found word = %s, freq = %d : \n", s, frequency);
119 }
satokf5cded12010-12-06 21:28:24 +0900120 if (length > MAX_WORD_LENGTH) {
121 if (DEBUG_DICT) LOGI("Exceeded max word length.");
122 return false;
123 }
satok30088252010-12-01 21:22:15 +0900124
125 // Find the right insertion point
126 int insertAt = 0;
127 while (insertAt < MAX_WORDS) {
satok715514d2010-12-02 20:19:59 +0900128 if (frequency > mFrequencies[insertAt] || (mFrequencies[insertAt] == frequency
129 && length < Dictionary::wideStrLen(mOutputChars + insertAt * MAX_WORD_LENGTH))) {
satok30088252010-12-01 21:22:15 +0900130 break;
131 }
132 insertAt++;
133 }
134 if (insertAt < MAX_WORDS) {
135 memmove((char*) mFrequencies + (insertAt + 1) * sizeof(mFrequencies[0]),
136 (char*) mFrequencies + insertAt * sizeof(mFrequencies[0]),
137 (MAX_WORDS - insertAt - 1) * sizeof(mFrequencies[0]));
138 mFrequencies[insertAt] = frequency;
139 memmove((char*) mOutputChars + (insertAt + 1) * MAX_WORD_LENGTH * sizeof(short),
satok715514d2010-12-02 20:19:59 +0900140 (char*) mOutputChars + insertAt * MAX_WORD_LENGTH * sizeof(short),
satok30088252010-12-01 21:22:15 +0900141 (MAX_WORDS - insertAt - 1) * sizeof(short) * MAX_WORD_LENGTH);
satok715514d2010-12-02 20:19:59 +0900142 unsigned short *dest = mOutputChars + insertAt * MAX_WORD_LENGTH;
satok30088252010-12-01 21:22:15 +0900143 while (length--) {
144 *dest++ = *word++;
145 }
146 *dest = 0; // NULL terminate
147 if (DEBUG_DICT) LOGI("Added word at %d\n", insertAt);
148 return true;
149 }
150 return false;
151}
152
satok28bd03b2010-12-03 16:39:16 +0900153unsigned short UnigramDictionary::toLowerCase(unsigned short c) {
satok30088252010-12-01 21:22:15 +0900154 if (c < sizeof(BASE_CHARS) / sizeof(BASE_CHARS[0])) {
155 c = BASE_CHARS[c];
156 }
157 if (c >='A' && c <= 'Z') {
158 c |= 32;
159 } else if (c > 127) {
160 c = latin_tolower(c);
161 }
162 return c;
163}
164
satok28bd03b2010-12-03 16:39:16 +0900165bool UnigramDictionary::sameAsTyped(unsigned short *word, int length) {
satok30088252010-12-01 21:22:15 +0900166 if (length != mInputLength) {
167 return false;
168 }
169 int *inputCodes = mInputCodes;
170 while (length--) {
171 if ((unsigned int) *inputCodes != (unsigned int) *word) {
172 return false;
173 }
174 inputCodes += MAX_ALTERNATIVES;
175 word++;
176 }
177 return true;
178}
179
satok715514d2010-12-02 20:19:59 +0900180static const char QUOTE = '\'';
satok30088252010-12-01 21:22:15 +0900181
satokd2997922010-12-07 13:08:39 +0900182// Keep this for comparing spec to new getWords
183void UnigramDictionary::getWordsOld(const int initialPos, const int inputLength, const int skipPos,
satok68319262010-12-03 19:38:08 +0900184 int *nextLetters, const int nextLettersSize) {
185 int initialPosition = initialPos;
186 const int count = Dictionary::getCount(DICT, &initialPosition);
satokf5cded12010-12-06 21:28:24 +0900187 getWordsRec(count, initialPosition, 0,
188 min(inputLength * MAX_DEPTH_MULTIPLIER, MAX_WORD_LENGTH),
satok68319262010-12-03 19:38:08 +0900189 mInputLength <= 0, 1, 0, 0, skipPos, nextLetters, nextLettersSize);
190}
satok30088252010-12-01 21:22:15 +0900191
satokd2997922010-12-07 13:08:39 +0900192void UnigramDictionary::getWords(const int rootPos, const int inputLength, const int skipPos,
193 int *nextLetters, const int nextLettersSize) {
194 int rootPosition = rootPos;
195 const int MAX_DEPTH = min(inputLength * MAX_DEPTH_MULTIPLIER, MAX_WORD_LENGTH);
196 // Get the number of child of root, then increment the position
197 int childCount = Dictionary::getCount(DICT, &rootPosition);
198 int depth = 0;
199
200 mStackChildCount[0] = childCount;
201 mStackTraverseAll[0] = (mInputLength <= 0);
202 mStackNodeFreq[0] = 1;
203 mStackInputIndex[0] = 0;
204 mStackDiffs[0] = 0;
205 mStackSiblingPos[0] = rootPosition;
206
207 while (depth >= 0) {
208 if (mStackChildCount[depth] > 0) {
209 --mStackChildCount[depth];
210 bool traverseAllNodes = mStackTraverseAll[depth];
211 int snr = mStackNodeFreq[depth];
212 int inputIndex = mStackInputIndex[depth];
213 int diffs = mStackDiffs[depth];
214 int siblingPos = mStackSiblingPos[depth];
215 int firstChildPos;
216 // depth will never be greater than MAX_DEPTH because in that case,
217 // needsToTraverseChildrenNodes should be false
218 const bool needsToTraverseChildrenNodes = processCurrentNode(siblingPos, depth,
219 MAX_DEPTH, traverseAllNodes, snr, inputIndex, diffs, skipPos, nextLetters,
220 nextLettersSize, &childCount, &firstChildPos, &traverseAllNodes, &snr,
221 &inputIndex, &diffs, &siblingPos);
222 // Next sibling pos
223 mStackSiblingPos[depth] = siblingPos;
224 if (needsToTraverseChildrenNodes) {
225 // Goes to child node
226 ++depth;
227 mStackChildCount[depth] = childCount;
228 mStackTraverseAll[depth] = traverseAllNodes;
229 mStackNodeFreq[depth] = snr;
230 mStackInputIndex[depth] = inputIndex;
231 mStackDiffs[depth] = diffs;
232 mStackSiblingPos[depth] = firstChildPos;
233 }
234 } else {
235 // Goes to parent node
236 --depth;
237 }
238 }
239}
240
satok68319262010-12-03 19:38:08 +0900241// snr : frequency?
242void UnigramDictionary::getWordsRec(const int childrenCount, const int pos, const int depth,
243 const int maxDepth, const bool traverseAllNodes, const int snr, const int inputIndex,
244 const int diffs, const int skipPos, int *nextLetters, const int nextLettersSize) {
satok48e432c2010-12-06 17:38:58 +0900245 int siblingPos = pos;
satok68319262010-12-03 19:38:08 +0900246 for (int i = 0; i < childrenCount; ++i) {
satok48e432c2010-12-06 17:38:58 +0900247 int newCount;
248 int newChildPosition;
satokd2997922010-12-07 13:08:39 +0900249 const int newDepth = depth + 1;
satok48e432c2010-12-06 17:38:58 +0900250 bool newTraverseAllNodes;
251 int newSnr;
252 int newInputIndex;
253 int newDiffs;
254 int newSiblingPos;
255 const bool needsToTraverseChildrenNodes = processCurrentNode(siblingPos, depth, maxDepth,
256 traverseAllNodes, snr, inputIndex, diffs, skipPos, nextLetters, nextLettersSize,
satokd2997922010-12-07 13:08:39 +0900257 &newCount, &newChildPosition, &newTraverseAllNodes, &newSnr,
satok48e432c2010-12-06 17:38:58 +0900258 &newInputIndex, &newDiffs, &newSiblingPos);
259 siblingPos = newSiblingPos;
satok30088252010-12-01 21:22:15 +0900260
satok48e432c2010-12-06 17:38:58 +0900261 if (needsToTraverseChildrenNodes) {
262 getWordsRec(newCount, newChildPosition, newDepth, maxDepth, newTraverseAllNodes,
satok28bd03b2010-12-03 16:39:16 +0900263 newSnr, newInputIndex, newDiffs, skipPos, nextLetters, nextLettersSize);
satok30088252010-12-01 21:22:15 +0900264 }
265 }
266}
267
satok715514d2010-12-02 20:19:59 +0900268inline void UnigramDictionary::onTerminalWhenUserTypedLengthIsGreaterThanInputLength(
269 unsigned short *word, const int inputLength, const int depth, const int snr,
270 int *nextLetters, const int nextLettersSize, const int skipPos, const int freq) {
271 addWord(word, depth + 1, freq * snr);
272 if (depth >= inputLength && skipPos < 0) {
273 registerNextLetter(mWord[mInputLength], nextLetters, nextLettersSize);
274 }
275}
276
277inline void UnigramDictionary::onTerminalWhenUserTypedLengthIsSameAsInputLength(
278 unsigned short *word, const int depth, const int snr, const int skipPos, const int freq,
279 const int addedWeight) {
280 if (!sameAsTyped(word, depth + 1)) {
281 int finalFreq = freq * snr * addedWeight;
282 // Proximity collection will promote a word of the same length as
283 // what user typed.
284 if (skipPos < 0) finalFreq *= FULL_WORD_MULTIPLIER;
285 addWord(word, depth + 1, finalFreq);
286 }
287}
satok28bd03b2010-12-03 16:39:16 +0900288
289inline bool UnigramDictionary::needsToSkipCurrentNode(const unsigned short c,
satok68319262010-12-03 19:38:08 +0900290 const int inputIndex, const int skipPos, const int depth) {
291 const unsigned short userTypedChar = (mInputCodes + (inputIndex * MAX_ALTERNATIVES))[0];
satok28bd03b2010-12-03 16:39:16 +0900292 // Skip the ' or other letter and continue deeper
293 return (c == QUOTE && userTypedChar != QUOTE) || skipPos == depth;
294}
295
296inline int UnigramDictionary::getMatchedProximityId(const int *currentChars,
satok48e432c2010-12-06 17:38:58 +0900297 const unsigned short c, const int skipPos) {
298 const unsigned short lowerC = toLowerCase(c);
satok28bd03b2010-12-03 16:39:16 +0900299 int j = 0;
300 while (currentChars[j] > 0) {
satok68319262010-12-03 19:38:08 +0900301 const bool matched = (currentChars[j] == lowerC || currentChars[j] == c);
satok28bd03b2010-12-03 16:39:16 +0900302 // If skipPos is defined, not to search proximity collections.
303 // First char is what user typed.
304 if (matched) {
305 return j;
306 } else if (skipPos >= 0) {
307 return -1;
308 }
309 ++j;
310 }
311 return -1;
312}
313
satok48e432c2010-12-06 17:38:58 +0900314inline bool UnigramDictionary::processCurrentNode(const int pos, const int depth,
315 const int maxDepth, const bool traverseAllNodes, const int snr, const int inputIndex,
316 const int diffs, const int skipPos, int *nextLetters, const int nextLettersSize,
satokd2997922010-12-07 13:08:39 +0900317 int *newCount, int *newChildPosition, bool *newTraverseAllNodes,
satok48e432c2010-12-06 17:38:58 +0900318 int *newSnr, int*newInputIndex, int *newDiffs, int *nextSiblingPosition) {
319 unsigned short c;
320 int childPosition;
321 bool terminal;
322 int freq;
323 *nextSiblingPosition = Dictionary::setDictionaryValues(DICT, IS_LATEST_DICT_VERSION, pos, &c,
324 &childPosition, &terminal, &freq);
325
326 const bool needsToTraverseChildrenNodes = childPosition != 0;
327
328 // If we are only doing traverseAllNodes, no need to look at the typed characters.
329 if (traverseAllNodes || needsToSkipCurrentNode(c, inputIndex, skipPos, depth)) {
330 mWord[depth] = c;
331 if (traverseAllNodes && terminal) {
332 onTerminalWhenUserTypedLengthIsGreaterThanInputLength(mWord, mInputLength, depth,
333 snr, nextLetters, nextLettersSize, skipPos, freq);
334 }
335 if (!needsToTraverseChildrenNodes) return false;
336 *newTraverseAllNodes = traverseAllNodes;
337 *newSnr = snr;
338 *newDiffs = diffs;
339 *newInputIndex = inputIndex;
satok48e432c2010-12-06 17:38:58 +0900340 } else {
341 int *currentChars = mInputCodes + (inputIndex * MAX_ALTERNATIVES);
342 int matchedProximityCharId = getMatchedProximityId(currentChars, c, skipPos);
343 if (matchedProximityCharId < 0) return false;
344 mWord[depth] = c;
345 // If inputIndex is greater than mInputLength, that means there is no
346 // proximity chars. So, we don't need to check proximity.
347 const int addedWeight = matchedProximityCharId == 0 ? TYPED_LETTER_MULTIPLIER : 1;
348 const bool isSameAsUserTypedLength = mInputLength == inputIndex + 1;
349 if (isSameAsUserTypedLength && terminal) {
350 onTerminalWhenUserTypedLengthIsSameAsInputLength(mWord, depth, snr,
351 skipPos, freq, addedWeight);
352 }
353 if (!needsToTraverseChildrenNodes) return false;
354 // Start traversing all nodes after the index exceeds the user typed length
355 *newTraverseAllNodes = isSameAsUserTypedLength;
356 *newSnr = snr * addedWeight;
357 *newDiffs = diffs + (matchedProximityCharId > 0);
358 *newInputIndex = inputIndex + 1;
satok48e432c2010-12-06 17:38:58 +0900359 }
360 // Optimization: Prune out words that are too long compared to how much was typed.
satokd2997922010-12-07 13:08:39 +0900361 if (depth >= maxDepth || *newDiffs > mMaxEditDistance) {
satok48e432c2010-12-06 17:38:58 +0900362 return false;
363 }
364
365 // If inputIndex is greater than mInputLength, that means there are no proximity chars.
366 if (mInputLength <= *newInputIndex) {
367 *newTraverseAllNodes = true;
368 }
369 // get the count of nodes and increment childAddress.
370 *newCount = Dictionary::getCount(DICT, &childPosition);
371 *newChildPosition = childPosition;
372 if (DEBUG_DICT) assert(needsToTraverseChildrenNodes);
373 return needsToTraverseChildrenNodes;
374}
375
satok30088252010-12-01 21:22:15 +0900376} // namespace latinime