blob: d8bb2f030733326b88a90724f982d771381a95ed [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
satokcdbbea72010-12-08 16:04:16 +090049 int suggestedWordsCount = getSuggestionCandidates(codesSize, -1, -1, nextLetters,
satok30088252010-12-01 21:22:15 +090050 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.
satokcdbbea72010-12-08 16:04:16 +090056 if (SUGGEST_MISSING_CHARACTERS) {
satok30088252010-12-01 21:22:15 +090057 for (int i = 0; i < codesSize; ++i) {
satokcdbbea72010-12-08 16:04:16 +090058 if (DEBUG_DICT) LOGI("--- Suggest missing characters %d", i);
59 const int tempCount = getSuggestionCandidates(codesSize, i, -1, NULL, 0);
satok30088252010-12-01 21:22:15 +090060 if (tempCount > suggestedWordsCount) {
61 suggestedWordsCount = tempCount;
satokcdbbea72010-12-08 16:04:16 +090062 }
63 }
64 }
65
66 // Suggest excessive characters
67 if (SUGGEST_EXCESSIVE_CHARACTERS) {
68 for (int i = 0; i < codesSize; ++i) {
69 if (DEBUG_DICT) LOGI("--- Suggest excessive characters %d", i);
70 const int tempCount = getSuggestionCandidates(codesSize, -1, i, NULL, 0);
71 if (tempCount > suggestedWordsCount) {
72 suggestedWordsCount = tempCount;
satok30088252010-12-01 21:22:15 +090073 }
74 }
75 }
76
77 if (DEBUG_DICT) {
78 LOGI("Returning %d words", suggestedWordsCount);
79 LOGI("Next letters: ");
80 for (int k = 0; k < nextLettersSize; k++) {
81 if (nextLetters[k] > 0) {
82 LOGI("%c = %d,", k, nextLetters[k]);
83 }
84 }
85 LOGI("\n");
86 }
87 return suggestedWordsCount;
88}
89
90void UnigramDictionary::initSuggestions(int *codes, int codesSize, unsigned short *outWords,
91 int *frequencies) {
satokf5cded12010-12-06 21:28:24 +090092 if (DEBUG_DICT) LOGI("initSuggest");
satok30088252010-12-01 21:22:15 +090093 mFrequencies = frequencies;
94 mOutputChars = outWords;
95 mInputCodes = codes;
96 mInputLength = codesSize;
97 mMaxEditDistance = mInputLength < 5 ? 2 : mInputLength / 2;
98}
99
satokcdbbea72010-12-08 16:04:16 +0900100int UnigramDictionary::getSuggestionCandidates(int inputLength, int skipPos, int excessivePos,
satok30088252010-12-01 21:22:15 +0900101 int *nextLetters, int nextLettersSize) {
satokf5cded12010-12-06 21:28:24 +0900102 if (DEBUG_DICT) LOGI("getSuggestionCandidates");
satok68319262010-12-03 19:38:08 +0900103 int initialPos = 0;
satoke808e432010-12-02 14:53:24 +0900104 if (IS_LATEST_DICT_VERSION) {
satok68319262010-12-03 19:38:08 +0900105 initialPos = DICTIONARY_HEADER_SIZE;
satok30088252010-12-01 21:22:15 +0900106 }
satokcdbbea72010-12-08 16:04:16 +0900107 getWords(initialPos, inputLength, skipPos, excessivePos, nextLetters, nextLettersSize);
satok30088252010-12-01 21:22:15 +0900108
109 // Get the word count
110 int suggestedWordsCount = 0;
111 while (suggestedWordsCount < MAX_WORDS && mFrequencies[suggestedWordsCount] > 0) {
112 suggestedWordsCount++;
113 }
114 return suggestedWordsCount;
115}
116
satok715514d2010-12-02 20:19:59 +0900117void UnigramDictionary::registerNextLetter(
118 unsigned short c, int *nextLetters, int nextLettersSize) {
satok30088252010-12-01 21:22:15 +0900119 if (c < nextLettersSize) {
120 nextLetters[c]++;
121 }
122}
123
satok28bd03b2010-12-03 16:39:16 +0900124bool UnigramDictionary::addWord(unsigned short *word, int length, int frequency) {
satok30088252010-12-01 21:22:15 +0900125 word[length] = 0;
126 if (DEBUG_DICT) {
127 char s[length + 1];
128 for (int i = 0; i <= length; i++) s[i] = word[i];
satokcdbbea72010-12-08 16:04:16 +0900129 if (DEBUG_SHOW_FOUND_WORD) LOGI("Found word = %s, freq = %d : \n", s, frequency);
satok30088252010-12-01 21:22:15 +0900130 }
satokf5cded12010-12-06 21:28:24 +0900131 if (length > MAX_WORD_LENGTH) {
132 if (DEBUG_DICT) LOGI("Exceeded max word length.");
133 return false;
134 }
satok30088252010-12-01 21:22:15 +0900135
136 // Find the right insertion point
137 int insertAt = 0;
138 while (insertAt < MAX_WORDS) {
satok715514d2010-12-02 20:19:59 +0900139 if (frequency > mFrequencies[insertAt] || (mFrequencies[insertAt] == frequency
140 && length < Dictionary::wideStrLen(mOutputChars + insertAt * MAX_WORD_LENGTH))) {
satok30088252010-12-01 21:22:15 +0900141 break;
142 }
143 insertAt++;
144 }
145 if (insertAt < MAX_WORDS) {
satokcdbbea72010-12-08 16:04:16 +0900146 if (DEBUG_DICT) {
147 char s[length + 1];
148 for (int i = 0; i <= length; i++) s[i] = word[i];
149 LOGI("Added word = %s, freq = %d : \n", s, frequency);
150 }
satok30088252010-12-01 21:22:15 +0900151 memmove((char*) mFrequencies + (insertAt + 1) * sizeof(mFrequencies[0]),
152 (char*) mFrequencies + insertAt * sizeof(mFrequencies[0]),
153 (MAX_WORDS - insertAt - 1) * sizeof(mFrequencies[0]));
154 mFrequencies[insertAt] = frequency;
155 memmove((char*) mOutputChars + (insertAt + 1) * MAX_WORD_LENGTH * sizeof(short),
satok715514d2010-12-02 20:19:59 +0900156 (char*) mOutputChars + insertAt * MAX_WORD_LENGTH * sizeof(short),
satok30088252010-12-01 21:22:15 +0900157 (MAX_WORDS - insertAt - 1) * sizeof(short) * MAX_WORD_LENGTH);
satok715514d2010-12-02 20:19:59 +0900158 unsigned short *dest = mOutputChars + insertAt * MAX_WORD_LENGTH;
satok30088252010-12-01 21:22:15 +0900159 while (length--) {
160 *dest++ = *word++;
161 }
162 *dest = 0; // NULL terminate
163 if (DEBUG_DICT) LOGI("Added word at %d\n", insertAt);
164 return true;
165 }
166 return false;
167}
168
satok28bd03b2010-12-03 16:39:16 +0900169unsigned short UnigramDictionary::toLowerCase(unsigned short c) {
satok30088252010-12-01 21:22:15 +0900170 if (c < sizeof(BASE_CHARS) / sizeof(BASE_CHARS[0])) {
171 c = BASE_CHARS[c];
172 }
173 if (c >='A' && c <= 'Z') {
174 c |= 32;
175 } else if (c > 127) {
176 c = latin_tolower(c);
177 }
178 return c;
179}
180
satok28bd03b2010-12-03 16:39:16 +0900181bool UnigramDictionary::sameAsTyped(unsigned short *word, int length) {
satok30088252010-12-01 21:22:15 +0900182 if (length != mInputLength) {
183 return false;
184 }
185 int *inputCodes = mInputCodes;
186 while (length--) {
187 if ((unsigned int) *inputCodes != (unsigned int) *word) {
188 return false;
189 }
190 inputCodes += MAX_ALTERNATIVES;
191 word++;
192 }
193 return true;
194}
195
satok715514d2010-12-02 20:19:59 +0900196static const char QUOTE = '\'';
satok30088252010-12-01 21:22:15 +0900197
satokd2997922010-12-07 13:08:39 +0900198// Keep this for comparing spec to new getWords
199void UnigramDictionary::getWordsOld(const int initialPos, const int inputLength, const int skipPos,
satokcdbbea72010-12-08 16:04:16 +0900200 const int excessivePos, int *nextLetters, const int nextLettersSize) {
satok68319262010-12-03 19:38:08 +0900201 int initialPosition = initialPos;
202 const int count = Dictionary::getCount(DICT, &initialPosition);
satokf5cded12010-12-06 21:28:24 +0900203 getWordsRec(count, initialPosition, 0,
204 min(inputLength * MAX_DEPTH_MULTIPLIER, MAX_WORD_LENGTH),
satokcdbbea72010-12-08 16:04:16 +0900205 mInputLength <= 0, 1, 0, 0, skipPos, excessivePos, nextLetters, nextLettersSize);
satok68319262010-12-03 19:38:08 +0900206}
satok30088252010-12-01 21:22:15 +0900207
satokd2997922010-12-07 13:08:39 +0900208void UnigramDictionary::getWords(const int rootPos, const int inputLength, const int skipPos,
satokcdbbea72010-12-08 16:04:16 +0900209 const int excessivePos, int *nextLetters, const int nextLettersSize) {
satokd2997922010-12-07 13:08:39 +0900210 int rootPosition = rootPos;
211 const int MAX_DEPTH = min(inputLength * MAX_DEPTH_MULTIPLIER, MAX_WORD_LENGTH);
212 // Get the number of child of root, then increment the position
213 int childCount = Dictionary::getCount(DICT, &rootPosition);
214 int depth = 0;
215
216 mStackChildCount[0] = childCount;
217 mStackTraverseAll[0] = (mInputLength <= 0);
218 mStackNodeFreq[0] = 1;
219 mStackInputIndex[0] = 0;
220 mStackDiffs[0] = 0;
221 mStackSiblingPos[0] = rootPosition;
222
223 while (depth >= 0) {
224 if (mStackChildCount[depth] > 0) {
225 --mStackChildCount[depth];
226 bool traverseAllNodes = mStackTraverseAll[depth];
227 int snr = mStackNodeFreq[depth];
228 int inputIndex = mStackInputIndex[depth];
229 int diffs = mStackDiffs[depth];
230 int siblingPos = mStackSiblingPos[depth];
231 int firstChildPos;
232 // depth will never be greater than MAX_DEPTH because in that case,
233 // needsToTraverseChildrenNodes should be false
234 const bool needsToTraverseChildrenNodes = processCurrentNode(siblingPos, depth,
satokcdbbea72010-12-08 16:04:16 +0900235 MAX_DEPTH, traverseAllNodes, snr, inputIndex, diffs, skipPos, excessivePos,
236 nextLetters, nextLettersSize, &childCount, &firstChildPos, &traverseAllNodes,
237 &snr, &inputIndex, &diffs, &siblingPos);
satokd2997922010-12-07 13:08:39 +0900238 // Next sibling pos
239 mStackSiblingPos[depth] = siblingPos;
240 if (needsToTraverseChildrenNodes) {
241 // Goes to child node
242 ++depth;
243 mStackChildCount[depth] = childCount;
244 mStackTraverseAll[depth] = traverseAllNodes;
245 mStackNodeFreq[depth] = snr;
246 mStackInputIndex[depth] = inputIndex;
247 mStackDiffs[depth] = diffs;
248 mStackSiblingPos[depth] = firstChildPos;
249 }
250 } else {
satokcdbbea72010-12-08 16:04:16 +0900251 // Goes to parent sibling node
satokd2997922010-12-07 13:08:39 +0900252 --depth;
253 }
254 }
255}
256
satok68319262010-12-03 19:38:08 +0900257// snr : frequency?
258void UnigramDictionary::getWordsRec(const int childrenCount, const int pos, const int depth,
259 const int maxDepth, const bool traverseAllNodes, const int snr, const int inputIndex,
satokcdbbea72010-12-08 16:04:16 +0900260 const int diffs, const int skipPos, const int excessivePos, int *nextLetters,
261 const int nextLettersSize) {
satok48e432c2010-12-06 17:38:58 +0900262 int siblingPos = pos;
satok68319262010-12-03 19:38:08 +0900263 for (int i = 0; i < childrenCount; ++i) {
satok48e432c2010-12-06 17:38:58 +0900264 int newCount;
265 int newChildPosition;
satokd2997922010-12-07 13:08:39 +0900266 const int newDepth = depth + 1;
satok48e432c2010-12-06 17:38:58 +0900267 bool newTraverseAllNodes;
268 int newSnr;
269 int newInputIndex;
270 int newDiffs;
271 int newSiblingPos;
272 const bool needsToTraverseChildrenNodes = processCurrentNode(siblingPos, depth, maxDepth,
satokcdbbea72010-12-08 16:04:16 +0900273 traverseAllNodes, snr, inputIndex, diffs, skipPos, excessivePos, nextLetters,
274 nextLettersSize,
satokd2997922010-12-07 13:08:39 +0900275 &newCount, &newChildPosition, &newTraverseAllNodes, &newSnr,
satok48e432c2010-12-06 17:38:58 +0900276 &newInputIndex, &newDiffs, &newSiblingPos);
277 siblingPos = newSiblingPos;
satok30088252010-12-01 21:22:15 +0900278
satok48e432c2010-12-06 17:38:58 +0900279 if (needsToTraverseChildrenNodes) {
280 getWordsRec(newCount, newChildPosition, newDepth, maxDepth, newTraverseAllNodes,
satokcdbbea72010-12-08 16:04:16 +0900281 newSnr, newInputIndex, newDiffs, skipPos, excessivePos, nextLetters,
282 nextLettersSize);
satok30088252010-12-01 21:22:15 +0900283 }
284 }
285}
286
satok715514d2010-12-02 20:19:59 +0900287inline void UnigramDictionary::onTerminalWhenUserTypedLengthIsGreaterThanInputLength(
288 unsigned short *word, const int inputLength, const int depth, const int snr,
289 int *nextLetters, const int nextLettersSize, const int skipPos, const int freq) {
290 addWord(word, depth + 1, freq * snr);
291 if (depth >= inputLength && skipPos < 0) {
292 registerNextLetter(mWord[mInputLength], nextLetters, nextLettersSize);
293 }
294}
295
296inline void UnigramDictionary::onTerminalWhenUserTypedLengthIsSameAsInputLength(
297 unsigned short *word, const int depth, const int snr, const int skipPos, const int freq,
298 const int addedWeight) {
299 if (!sameAsTyped(word, depth + 1)) {
300 int finalFreq = freq * snr * addedWeight;
301 // Proximity collection will promote a word of the same length as
302 // what user typed.
303 if (skipPos < 0) finalFreq *= FULL_WORD_MULTIPLIER;
304 addWord(word, depth + 1, finalFreq);
305 }
306}
satok28bd03b2010-12-03 16:39:16 +0900307
308inline bool UnigramDictionary::needsToSkipCurrentNode(const unsigned short c,
satok68319262010-12-03 19:38:08 +0900309 const int inputIndex, const int skipPos, const int depth) {
310 const unsigned short userTypedChar = (mInputCodes + (inputIndex * MAX_ALTERNATIVES))[0];
satok28bd03b2010-12-03 16:39:16 +0900311 // Skip the ' or other letter and continue deeper
312 return (c == QUOTE && userTypedChar != QUOTE) || skipPos == depth;
313}
314
315inline int UnigramDictionary::getMatchedProximityId(const int *currentChars,
satok48e432c2010-12-06 17:38:58 +0900316 const unsigned short c, const int skipPos) {
317 const unsigned short lowerC = toLowerCase(c);
satok28bd03b2010-12-03 16:39:16 +0900318 int j = 0;
319 while (currentChars[j] > 0) {
satok68319262010-12-03 19:38:08 +0900320 const bool matched = (currentChars[j] == lowerC || currentChars[j] == c);
satok28bd03b2010-12-03 16:39:16 +0900321 // If skipPos is defined, not to search proximity collections.
322 // First char is what user typed.
323 if (matched) {
324 return j;
325 } else if (skipPos >= 0) {
326 return -1;
327 }
328 ++j;
329 }
330 return -1;
331}
332
satok48e432c2010-12-06 17:38:58 +0900333inline bool UnigramDictionary::processCurrentNode(const int pos, const int depth,
satokcdbbea72010-12-08 16:04:16 +0900334 const int maxDepth, const bool traverseAllNodes, const int snr, int inputIndex,
335 const int diffs, const int skipPos, const int excessivePos, int *nextLetters,
336 const int nextLettersSize, int *newCount, int *newChildPosition, bool *newTraverseAllNodes,
satok48e432c2010-12-06 17:38:58 +0900337 int *newSnr, int*newInputIndex, int *newDiffs, int *nextSiblingPosition) {
satokcdbbea72010-12-08 16:04:16 +0900338 if (DEBUG_DICT) assert(skipPos < 0 || excessivePos < 0);
satok48e432c2010-12-06 17:38:58 +0900339 unsigned short c;
340 int childPosition;
341 bool terminal;
342 int freq;
satokcdbbea72010-12-08 16:04:16 +0900343
344 if (excessivePos == depth) ++inputIndex;
345
satok48e432c2010-12-06 17:38:58 +0900346 *nextSiblingPosition = Dictionary::setDictionaryValues(DICT, IS_LATEST_DICT_VERSION, pos, &c,
347 &childPosition, &terminal, &freq);
348
349 const bool needsToTraverseChildrenNodes = childPosition != 0;
350
351 // If we are only doing traverseAllNodes, no need to look at the typed characters.
352 if (traverseAllNodes || needsToSkipCurrentNode(c, inputIndex, skipPos, depth)) {
353 mWord[depth] = c;
354 if (traverseAllNodes && terminal) {
355 onTerminalWhenUserTypedLengthIsGreaterThanInputLength(mWord, mInputLength, depth,
356 snr, nextLetters, nextLettersSize, skipPos, freq);
357 }
358 if (!needsToTraverseChildrenNodes) return false;
359 *newTraverseAllNodes = traverseAllNodes;
360 *newSnr = snr;
361 *newDiffs = diffs;
362 *newInputIndex = inputIndex;
satok48e432c2010-12-06 17:38:58 +0900363 } else {
364 int *currentChars = mInputCodes + (inputIndex * MAX_ALTERNATIVES);
365 int matchedProximityCharId = getMatchedProximityId(currentChars, c, skipPos);
366 if (matchedProximityCharId < 0) return false;
367 mWord[depth] = c;
368 // If inputIndex is greater than mInputLength, that means there is no
369 // proximity chars. So, we don't need to check proximity.
370 const int addedWeight = matchedProximityCharId == 0 ? TYPED_LETTER_MULTIPLIER : 1;
371 const bool isSameAsUserTypedLength = mInputLength == inputIndex + 1;
372 if (isSameAsUserTypedLength && terminal) {
373 onTerminalWhenUserTypedLengthIsSameAsInputLength(mWord, depth, snr,
374 skipPos, freq, addedWeight);
375 }
376 if (!needsToTraverseChildrenNodes) return false;
377 // Start traversing all nodes after the index exceeds the user typed length
378 *newTraverseAllNodes = isSameAsUserTypedLength;
379 *newSnr = snr * addedWeight;
380 *newDiffs = diffs + (matchedProximityCharId > 0);
381 *newInputIndex = inputIndex + 1;
satok48e432c2010-12-06 17:38:58 +0900382 }
383 // Optimization: Prune out words that are too long compared to how much was typed.
satokd2997922010-12-07 13:08:39 +0900384 if (depth >= maxDepth || *newDiffs > mMaxEditDistance) {
satok48e432c2010-12-06 17:38:58 +0900385 return false;
386 }
387
388 // If inputIndex is greater than mInputLength, that means there are no proximity chars.
389 if (mInputLength <= *newInputIndex) {
390 *newTraverseAllNodes = true;
391 }
392 // get the count of nodes and increment childAddress.
393 *newCount = Dictionary::getCount(DICT, &childPosition);
394 *newChildPosition = childPosition;
395 if (DEBUG_DICT) assert(needsToTraverseChildrenNodes);
396 return needsToTraverseChildrenNodes;
397}
398
satok30088252010-12-01 21:22:15 +0900399} // namespace latinime