blob: fa4e29632818b14df327cf463448de84b52ea010 [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 <stdio.h>
20#include <fcntl.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) {
81 mFrequencies = frequencies;
82 mOutputChars = outWords;
83 mInputCodes = codes;
84 mInputLength = codesSize;
85 mMaxEditDistance = mInputLength < 5 ? 2 : mInputLength / 2;
86}
87
88int UnigramDictionary::getSuggestionCandidates(int inputLength, int skipPos,
89 int *nextLetters, int nextLettersSize) {
satok68319262010-12-03 19:38:08 +090090 int initialPos = 0;
satoke808e432010-12-02 14:53:24 +090091 if (IS_LATEST_DICT_VERSION) {
satok68319262010-12-03 19:38:08 +090092 initialPos = DICTIONARY_HEADER_SIZE;
satok30088252010-12-01 21:22:15 +090093 }
satok68319262010-12-03 19:38:08 +090094 getWords(initialPos, inputLength, skipPos, nextLetters, nextLettersSize);
satok30088252010-12-01 21:22:15 +090095
96 // Get the word count
97 int suggestedWordsCount = 0;
98 while (suggestedWordsCount < MAX_WORDS && mFrequencies[suggestedWordsCount] > 0) {
99 suggestedWordsCount++;
100 }
101 return suggestedWordsCount;
102}
103
satok715514d2010-12-02 20:19:59 +0900104void UnigramDictionary::registerNextLetter(
105 unsigned short c, int *nextLetters, int nextLettersSize) {
satok30088252010-12-01 21:22:15 +0900106 if (c < nextLettersSize) {
107 nextLetters[c]++;
108 }
109}
110
satok28bd03b2010-12-03 16:39:16 +0900111bool UnigramDictionary::addWord(unsigned short *word, int length, int frequency) {
satok30088252010-12-01 21:22:15 +0900112 word[length] = 0;
113 if (DEBUG_DICT) {
114 char s[length + 1];
115 for (int i = 0; i <= length; i++) s[i] = word[i];
116 LOGI("Found word = %s, freq = %d : \n", s, frequency);
117 }
118
119 // Find the right insertion point
120 int insertAt = 0;
121 while (insertAt < MAX_WORDS) {
satok715514d2010-12-02 20:19:59 +0900122 if (frequency > mFrequencies[insertAt] || (mFrequencies[insertAt] == frequency
123 && length < Dictionary::wideStrLen(mOutputChars + insertAt * MAX_WORD_LENGTH))) {
satok30088252010-12-01 21:22:15 +0900124 break;
125 }
126 insertAt++;
127 }
128 if (insertAt < MAX_WORDS) {
129 memmove((char*) mFrequencies + (insertAt + 1) * sizeof(mFrequencies[0]),
130 (char*) mFrequencies + insertAt * sizeof(mFrequencies[0]),
131 (MAX_WORDS - insertAt - 1) * sizeof(mFrequencies[0]));
132 mFrequencies[insertAt] = frequency;
133 memmove((char*) mOutputChars + (insertAt + 1) * MAX_WORD_LENGTH * sizeof(short),
satok715514d2010-12-02 20:19:59 +0900134 (char*) mOutputChars + insertAt * MAX_WORD_LENGTH * sizeof(short),
satok30088252010-12-01 21:22:15 +0900135 (MAX_WORDS - insertAt - 1) * sizeof(short) * MAX_WORD_LENGTH);
satok715514d2010-12-02 20:19:59 +0900136 unsigned short *dest = mOutputChars + insertAt * MAX_WORD_LENGTH;
satok30088252010-12-01 21:22:15 +0900137 while (length--) {
138 *dest++ = *word++;
139 }
140 *dest = 0; // NULL terminate
141 if (DEBUG_DICT) LOGI("Added word at %d\n", insertAt);
142 return true;
143 }
144 return false;
145}
146
satok28bd03b2010-12-03 16:39:16 +0900147unsigned short UnigramDictionary::toLowerCase(unsigned short c) {
satok30088252010-12-01 21:22:15 +0900148 if (c < sizeof(BASE_CHARS) / sizeof(BASE_CHARS[0])) {
149 c = BASE_CHARS[c];
150 }
151 if (c >='A' && c <= 'Z') {
152 c |= 32;
153 } else if (c > 127) {
154 c = latin_tolower(c);
155 }
156 return c;
157}
158
satok28bd03b2010-12-03 16:39:16 +0900159bool UnigramDictionary::sameAsTyped(unsigned short *word, int length) {
satok30088252010-12-01 21:22:15 +0900160 if (length != mInputLength) {
161 return false;
162 }
163 int *inputCodes = mInputCodes;
164 while (length--) {
165 if ((unsigned int) *inputCodes != (unsigned int) *word) {
166 return false;
167 }
168 inputCodes += MAX_ALTERNATIVES;
169 word++;
170 }
171 return true;
172}
173
satok715514d2010-12-02 20:19:59 +0900174static const char QUOTE = '\'';
satok30088252010-12-01 21:22:15 +0900175
satok68319262010-12-03 19:38:08 +0900176void UnigramDictionary::getWords(const int initialPos, const int inputLength, const int skipPos,
177 int *nextLetters, const int nextLettersSize) {
178 int initialPosition = initialPos;
179 const int count = Dictionary::getCount(DICT, &initialPosition);
180 getWordsRec(count, initialPosition, 0, inputLength * MAX_DEPTH_MULTIPLIER,
181 mInputLength <= 0, 1, 0, 0, skipPos, nextLetters, nextLettersSize);
182}
satok30088252010-12-01 21:22:15 +0900183
satok68319262010-12-03 19:38:08 +0900184// snr : frequency?
185void UnigramDictionary::getWordsRec(const int childrenCount, const int pos, const int depth,
186 const int maxDepth, const bool traverseAllNodes, const int snr, const int inputIndex,
187 const int diffs, const int skipPos, int *nextLetters, const int nextLettersSize) {
satok48e432c2010-12-06 17:38:58 +0900188 int siblingPos = pos;
satok68319262010-12-03 19:38:08 +0900189 for (int i = 0; i < childrenCount; ++i) {
satok48e432c2010-12-06 17:38:58 +0900190 int newCount;
191 int newChildPosition;
192 int newDepth;
193 bool newTraverseAllNodes;
194 int newSnr;
195 int newInputIndex;
196 int newDiffs;
197 int newSiblingPos;
198 const bool needsToTraverseChildrenNodes = processCurrentNode(siblingPos, depth, maxDepth,
199 traverseAllNodes, snr, inputIndex, diffs, skipPos, nextLetters, nextLettersSize,
200 &newCount, &newChildPosition, &newDepth, &newTraverseAllNodes, &newSnr,
201 &newInputIndex, &newDiffs, &newSiblingPos);
202 siblingPos = newSiblingPos;
satok30088252010-12-01 21:22:15 +0900203
satok48e432c2010-12-06 17:38:58 +0900204 if (needsToTraverseChildrenNodes) {
205 getWordsRec(newCount, newChildPosition, newDepth, maxDepth, newTraverseAllNodes,
satok28bd03b2010-12-03 16:39:16 +0900206 newSnr, newInputIndex, newDiffs, skipPos, nextLetters, nextLettersSize);
satok30088252010-12-01 21:22:15 +0900207 }
208 }
209}
210
satok715514d2010-12-02 20:19:59 +0900211inline void UnigramDictionary::onTerminalWhenUserTypedLengthIsGreaterThanInputLength(
212 unsigned short *word, const int inputLength, const int depth, const int snr,
213 int *nextLetters, const int nextLettersSize, const int skipPos, const int freq) {
214 addWord(word, depth + 1, freq * snr);
215 if (depth >= inputLength && skipPos < 0) {
216 registerNextLetter(mWord[mInputLength], nextLetters, nextLettersSize);
217 }
218}
219
220inline void UnigramDictionary::onTerminalWhenUserTypedLengthIsSameAsInputLength(
221 unsigned short *word, const int depth, const int snr, const int skipPos, const int freq,
222 const int addedWeight) {
223 if (!sameAsTyped(word, depth + 1)) {
224 int finalFreq = freq * snr * addedWeight;
225 // Proximity collection will promote a word of the same length as
226 // what user typed.
227 if (skipPos < 0) finalFreq *= FULL_WORD_MULTIPLIER;
228 addWord(word, depth + 1, finalFreq);
229 }
230}
satok28bd03b2010-12-03 16:39:16 +0900231
232inline bool UnigramDictionary::needsToSkipCurrentNode(const unsigned short c,
satok68319262010-12-03 19:38:08 +0900233 const int inputIndex, const int skipPos, const int depth) {
234 const unsigned short userTypedChar = (mInputCodes + (inputIndex * MAX_ALTERNATIVES))[0];
satok28bd03b2010-12-03 16:39:16 +0900235 // Skip the ' or other letter and continue deeper
236 return (c == QUOTE && userTypedChar != QUOTE) || skipPos == depth;
237}
238
239inline int UnigramDictionary::getMatchedProximityId(const int *currentChars,
satok48e432c2010-12-06 17:38:58 +0900240 const unsigned short c, const int skipPos) {
241 const unsigned short lowerC = toLowerCase(c);
satok28bd03b2010-12-03 16:39:16 +0900242 int j = 0;
243 while (currentChars[j] > 0) {
satok68319262010-12-03 19:38:08 +0900244 const bool matched = (currentChars[j] == lowerC || currentChars[j] == c);
satok28bd03b2010-12-03 16:39:16 +0900245 // If skipPos is defined, not to search proximity collections.
246 // First char is what user typed.
247 if (matched) {
248 return j;
249 } else if (skipPos >= 0) {
250 return -1;
251 }
252 ++j;
253 }
254 return -1;
255}
256
satok48e432c2010-12-06 17:38:58 +0900257inline bool UnigramDictionary::processCurrentNode(const int pos, const int depth,
258 const int maxDepth, const bool traverseAllNodes, const int snr, const int inputIndex,
259 const int diffs, const int skipPos, int *nextLetters, const int nextLettersSize,
260 int *newCount, int *newChildPosition, int *newDepth, bool *newTraverseAllNodes,
261 int *newSnr, int*newInputIndex, int *newDiffs, int *nextSiblingPosition) {
262 unsigned short c;
263 int childPosition;
264 bool terminal;
265 int freq;
266 *nextSiblingPosition = Dictionary::setDictionaryValues(DICT, IS_LATEST_DICT_VERSION, pos, &c,
267 &childPosition, &terminal, &freq);
268
269 const bool needsToTraverseChildrenNodes = childPosition != 0;
270
271 // If we are only doing traverseAllNodes, no need to look at the typed characters.
272 if (traverseAllNodes || needsToSkipCurrentNode(c, inputIndex, skipPos, depth)) {
273 mWord[depth] = c;
274 if (traverseAllNodes && terminal) {
275 onTerminalWhenUserTypedLengthIsGreaterThanInputLength(mWord, mInputLength, depth,
276 snr, nextLetters, nextLettersSize, skipPos, freq);
277 }
278 if (!needsToTraverseChildrenNodes) return false;
279 *newTraverseAllNodes = traverseAllNodes;
280 *newSnr = snr;
281 *newDiffs = diffs;
282 *newInputIndex = inputIndex;
283 *newDepth = depth + 1;
284 } else {
285 int *currentChars = mInputCodes + (inputIndex * MAX_ALTERNATIVES);
286 int matchedProximityCharId = getMatchedProximityId(currentChars, c, skipPos);
287 if (matchedProximityCharId < 0) return false;
288 mWord[depth] = c;
289 // If inputIndex is greater than mInputLength, that means there is no
290 // proximity chars. So, we don't need to check proximity.
291 const int addedWeight = matchedProximityCharId == 0 ? TYPED_LETTER_MULTIPLIER : 1;
292 const bool isSameAsUserTypedLength = mInputLength == inputIndex + 1;
293 if (isSameAsUserTypedLength && terminal) {
294 onTerminalWhenUserTypedLengthIsSameAsInputLength(mWord, depth, snr,
295 skipPos, freq, addedWeight);
296 }
297 if (!needsToTraverseChildrenNodes) return false;
298 // Start traversing all nodes after the index exceeds the user typed length
299 *newTraverseAllNodes = isSameAsUserTypedLength;
300 *newSnr = snr * addedWeight;
301 *newDiffs = diffs + (matchedProximityCharId > 0);
302 *newInputIndex = inputIndex + 1;
303 *newDepth = depth + 1;
304 }
305 // Optimization: Prune out words that are too long compared to how much was typed.
306 if (*newDepth > maxDepth || *newDiffs > mMaxEditDistance) {
307 return false;
308 }
309
310 // If inputIndex is greater than mInputLength, that means there are no proximity chars.
311 if (mInputLength <= *newInputIndex) {
312 *newTraverseAllNodes = true;
313 }
314 // get the count of nodes and increment childAddress.
315 *newCount = Dictionary::getCount(DICT, &childPosition);
316 *newChildPosition = childPosition;
317 if (DEBUG_DICT) assert(needsToTraverseChildrenNodes);
318 return needsToTraverseChildrenNodes;
319}
320
satok30088252010-12-01 21:22:15 +0900321} // namespace latinime