blob: 8a9742bbf40f39e236c18811505a56e0dacd80d2 [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
18#include <stdio.h>
19#include <fcntl.h>
20#include <sys/mman.h>
21#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) {
188 int position = pos;
189 // If inputIndex is greater than mInputLength, that means there are no proximity chars.
190 for (int i = 0; i < childrenCount; ++i) {
satok30088252010-12-01 21:22:15 +0900191 // -- at char
satok68319262010-12-03 19:38:08 +0900192 const unsigned short c = Dictionary::getChar(DICT, &position);
satok30088252010-12-01 21:22:15 +0900193 // -- at flag/add
satok28bd03b2010-12-03 16:39:16 +0900194 const unsigned short lowerC = toLowerCase(c);
satok68319262010-12-03 19:38:08 +0900195 const bool terminal = Dictionary::getTerminal(DICT, &position);
196 int childrenPosition = Dictionary::getAddress(DICT, &position);
satok28bd03b2010-12-03 16:39:16 +0900197 int matchedProximityCharId = -1;
satok68319262010-12-03 19:38:08 +0900198 const bool needsToTraverseNextNode = childrenPosition != 0;
satok30088252010-12-01 21:22:15 +0900199 // -- after address or flag
200 int freq = 1;
satok715514d2010-12-02 20:19:59 +0900201 // If terminal, increment pos
satok68319262010-12-03 19:38:08 +0900202 if (terminal) freq = Dictionary::getFreq(DICT, IS_LATEST_DICT_VERSION, &position);
satok30088252010-12-01 21:22:15 +0900203 // -- after add or freq
satok28bd03b2010-12-03 16:39:16 +0900204 bool newTraverseAllNodes = traverseAllNodes;
205 int newSnr = snr;
206 int newDiffs = diffs;
207 int newInputIndex = inputIndex;
satok68319262010-12-03 19:38:08 +0900208 const int newDepth = depth + 1;
satok30088252010-12-01 21:22:15 +0900209
satok28bd03b2010-12-03 16:39:16 +0900210 // If we are only doing traverseAllNodes, no need to look at the typed characters.
satok68319262010-12-03 19:38:08 +0900211 if (traverseAllNodes || needsToSkipCurrentNode(c, inputIndex, skipPos, depth)) {
satok30088252010-12-01 21:22:15 +0900212 mWord[depth] = c;
satok28bd03b2010-12-03 16:39:16 +0900213 if (traverseAllNodes && terminal) {
satok715514d2010-12-02 20:19:59 +0900214 onTerminalWhenUserTypedLengthIsGreaterThanInputLength(mWord, mInputLength, depth,
215 snr, nextLetters, nextLettersSize, skipPos, freq);
satok30088252010-12-01 21:22:15 +0900216 }
satok30088252010-12-01 21:22:15 +0900217 } else {
satok68319262010-12-03 19:38:08 +0900218 int *currentChars = mInputCodes + (inputIndex * MAX_ALTERNATIVES);
satok28bd03b2010-12-03 16:39:16 +0900219 matchedProximityCharId = getMatchedProximityId(currentChars, lowerC, c, skipPos);
220 if (matchedProximityCharId < 0) continue;
221 mWord[depth] = c;
222 // If inputIndex is greater than mInputLength, that means there is no
223 // proximity chars. So, we don't need to check proximity.
224 const int addedWeight = matchedProximityCharId == 0 ? TYPED_LETTER_MULTIPLIER : 1;
225 const bool isSameAsUserTypedLength = mInputLength == inputIndex + 1;
226 if (isSameAsUserTypedLength && terminal) {
227 onTerminalWhenUserTypedLengthIsSameAsInputLength(mWord, depth, snr,
228 skipPos, freq, addedWeight);
satok30088252010-12-01 21:22:15 +0900229 }
satok28bd03b2010-12-03 16:39:16 +0900230 if (!needsToTraverseNextNode) continue;
231 // Start traversing all nodes after the index exceeds the user typed length
232 newTraverseAllNodes = isSameAsUserTypedLength;
233 newSnr *= addedWeight;
234 newDiffs += (matchedProximityCharId > 0);
235 ++newInputIndex;
236 }
satok68319262010-12-03 19:38:08 +0900237 // Optimization: Prune out words that are too long compared to how much was typed.
238 if (newDepth > maxDepth || newDiffs > mMaxEditDistance) {
239 continue;
240 }
241 if (mInputLength <= newInputIndex) {
242 newTraverseAllNodes = true;
243 }
satok28bd03b2010-12-03 16:39:16 +0900244 if (needsToTraverseNextNode) {
satok68319262010-12-03 19:38:08 +0900245 // get the count of nodes and increment childAddress.
246 const int count = Dictionary::getCount(DICT, &childrenPosition);
247 getWordsRec(count, childrenPosition, newDepth, maxDepth, newTraverseAllNodes,
satok28bd03b2010-12-03 16:39:16 +0900248 newSnr, newInputIndex, newDiffs, skipPos, nextLetters, nextLettersSize);
satok30088252010-12-01 21:22:15 +0900249 }
250 }
251}
252
satok715514d2010-12-02 20:19:59 +0900253inline void UnigramDictionary::onTerminalWhenUserTypedLengthIsGreaterThanInputLength(
254 unsigned short *word, const int inputLength, const int depth, const int snr,
255 int *nextLetters, const int nextLettersSize, const int skipPos, const int freq) {
256 addWord(word, depth + 1, freq * snr);
257 if (depth >= inputLength && skipPos < 0) {
258 registerNextLetter(mWord[mInputLength], nextLetters, nextLettersSize);
259 }
260}
261
262inline void UnigramDictionary::onTerminalWhenUserTypedLengthIsSameAsInputLength(
263 unsigned short *word, const int depth, const int snr, const int skipPos, const int freq,
264 const int addedWeight) {
265 if (!sameAsTyped(word, depth + 1)) {
266 int finalFreq = freq * snr * addedWeight;
267 // Proximity collection will promote a word of the same length as
268 // what user typed.
269 if (skipPos < 0) finalFreq *= FULL_WORD_MULTIPLIER;
270 addWord(word, depth + 1, finalFreq);
271 }
272}
satok28bd03b2010-12-03 16:39:16 +0900273
274inline bool UnigramDictionary::needsToSkipCurrentNode(const unsigned short c,
satok68319262010-12-03 19:38:08 +0900275 const int inputIndex, const int skipPos, const int depth) {
276 const unsigned short userTypedChar = (mInputCodes + (inputIndex * MAX_ALTERNATIVES))[0];
satok28bd03b2010-12-03 16:39:16 +0900277 // Skip the ' or other letter and continue deeper
278 return (c == QUOTE && userTypedChar != QUOTE) || skipPos == depth;
279}
280
281inline int UnigramDictionary::getMatchedProximityId(const int *currentChars,
282 const unsigned short lowerC, const unsigned short c, const int skipPos) {
satok28bd03b2010-12-03 16:39:16 +0900283 int j = 0;
284 while (currentChars[j] > 0) {
satok68319262010-12-03 19:38:08 +0900285 const bool matched = (currentChars[j] == lowerC || currentChars[j] == c);
satok28bd03b2010-12-03 16:39:16 +0900286 // If skipPos is defined, not to search proximity collections.
287 // First char is what user typed.
288 if (matched) {
289 return j;
290 } else if (skipPos >= 0) {
291 return -1;
292 }
293 ++j;
294 }
295 return -1;
296}
297
satok30088252010-12-01 21:22:15 +0900298} // namespace latinime