blob: b3479738ed92d67620bf102f0f09bbed216c2eb1 [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) {
satoke808e432010-12-02 14:53:24 +090090 if (IS_LATEST_DICT_VERSION) {
satok30088252010-12-01 21:22:15 +090091 getWordsRec(DICTIONARY_HEADER_SIZE, 0, inputLength * 3, false, 1, 0, 0, skipPos,
92 nextLetters, nextLettersSize);
93 } else {
94 getWordsRec(0, 0, inputLength * 3, false, 1, 0, 0, skipPos, nextLetters, nextLettersSize);
95 }
96
97 // Get the word count
98 int suggestedWordsCount = 0;
99 while (suggestedWordsCount < MAX_WORDS && mFrequencies[suggestedWordsCount] > 0) {
100 suggestedWordsCount++;
101 }
102 return suggestedWordsCount;
103}
104
satok715514d2010-12-02 20:19:59 +0900105void UnigramDictionary::registerNextLetter(
106 unsigned short c, int *nextLetters, int nextLettersSize) {
satok30088252010-12-01 21:22:15 +0900107 if (c < nextLettersSize) {
108 nextLetters[c]++;
109 }
110}
111
satok28bd03b2010-12-03 16:39:16 +0900112bool UnigramDictionary::addWord(unsigned short *word, int length, int frequency) {
satok30088252010-12-01 21:22:15 +0900113 word[length] = 0;
114 if (DEBUG_DICT) {
115 char s[length + 1];
116 for (int i = 0; i <= length; i++) s[i] = word[i];
117 LOGI("Found word = %s, freq = %d : \n", s, frequency);
118 }
119
120 // Find the right insertion point
121 int insertAt = 0;
122 while (insertAt < MAX_WORDS) {
satok715514d2010-12-02 20:19:59 +0900123 if (frequency > mFrequencies[insertAt] || (mFrequencies[insertAt] == frequency
124 && length < Dictionary::wideStrLen(mOutputChars + insertAt * MAX_WORD_LENGTH))) {
satok30088252010-12-01 21:22:15 +0900125 break;
126 }
127 insertAt++;
128 }
129 if (insertAt < MAX_WORDS) {
130 memmove((char*) mFrequencies + (insertAt + 1) * sizeof(mFrequencies[0]),
131 (char*) mFrequencies + insertAt * sizeof(mFrequencies[0]),
132 (MAX_WORDS - insertAt - 1) * sizeof(mFrequencies[0]));
133 mFrequencies[insertAt] = frequency;
134 memmove((char*) mOutputChars + (insertAt + 1) * MAX_WORD_LENGTH * sizeof(short),
satok715514d2010-12-02 20:19:59 +0900135 (char*) mOutputChars + insertAt * MAX_WORD_LENGTH * sizeof(short),
satok30088252010-12-01 21:22:15 +0900136 (MAX_WORDS - insertAt - 1) * sizeof(short) * MAX_WORD_LENGTH);
satok715514d2010-12-02 20:19:59 +0900137 unsigned short *dest = mOutputChars + insertAt * MAX_WORD_LENGTH;
satok30088252010-12-01 21:22:15 +0900138 while (length--) {
139 *dest++ = *word++;
140 }
141 *dest = 0; // NULL terminate
142 if (DEBUG_DICT) LOGI("Added word at %d\n", insertAt);
143 return true;
144 }
145 return false;
146}
147
satok28bd03b2010-12-03 16:39:16 +0900148unsigned short UnigramDictionary::toLowerCase(unsigned short c) {
satok30088252010-12-01 21:22:15 +0900149 if (c < sizeof(BASE_CHARS) / sizeof(BASE_CHARS[0])) {
150 c = BASE_CHARS[c];
151 }
152 if (c >='A' && c <= 'Z') {
153 c |= 32;
154 } else if (c > 127) {
155 c = latin_tolower(c);
156 }
157 return c;
158}
159
satok28bd03b2010-12-03 16:39:16 +0900160bool UnigramDictionary::sameAsTyped(unsigned short *word, int length) {
satok30088252010-12-01 21:22:15 +0900161 if (length != mInputLength) {
162 return false;
163 }
164 int *inputCodes = mInputCodes;
165 while (length--) {
166 if ((unsigned int) *inputCodes != (unsigned int) *word) {
167 return false;
168 }
169 inputCodes += MAX_ALTERNATIVES;
170 word++;
171 }
172 return true;
173}
174
satok715514d2010-12-02 20:19:59 +0900175static const char QUOTE = '\'';
satok30088252010-12-01 21:22:15 +0900176
satok715514d2010-12-02 20:19:59 +0900177// snr : frequency?
satok28bd03b2010-12-03 16:39:16 +0900178void UnigramDictionary::getWordsRec(int pos, int depth, int maxDepth, bool traverseAllNodes,
179 int snr, int inputIndex, int diffs, int skipPos, int *nextLetters, int nextLettersSize) {
satok30088252010-12-01 21:22:15 +0900180 // Optimization: Prune out words that are too long compared to how much was typed.
satok28bd03b2010-12-03 16:39:16 +0900181 if (depth > maxDepth || diffs > mMaxEditDistance) {
satok30088252010-12-01 21:22:15 +0900182 return;
183 }
satok715514d2010-12-02 20:19:59 +0900184 // get the count of nodes and increment pos.
satoke808e432010-12-02 14:53:24 +0900185 int count = Dictionary::getCount(DICT, &pos);
satok30088252010-12-01 21:22:15 +0900186 int *currentChars = NULL;
satok715514d2010-12-02 20:19:59 +0900187 // If inputIndex is greater than mInputLength, that means there are no proximity chars.
satok30088252010-12-01 21:22:15 +0900188 if (mInputLength <= inputIndex) {
satok28bd03b2010-12-03 16:39:16 +0900189 traverseAllNodes = true;
satok30088252010-12-01 21:22:15 +0900190 } else {
191 currentChars = mInputCodes + (inputIndex * MAX_ALTERNATIVES);
192 }
193
satok28bd03b2010-12-03 16:39:16 +0900194 for (int i = 0; i < count; ++i) {
satok30088252010-12-01 21:22:15 +0900195 // -- at char
satok28bd03b2010-12-03 16:39:16 +0900196 const unsigned short c = Dictionary::getChar(DICT, &pos);
satok30088252010-12-01 21:22:15 +0900197 // -- at flag/add
satok28bd03b2010-12-03 16:39:16 +0900198 const unsigned short lowerC = toLowerCase(c);
199 const bool terminal = Dictionary::getTerminal(DICT, &pos);
200 const int childrenAddress = Dictionary::getAddress(DICT, &pos);
201 int matchedProximityCharId = -1;
202 const bool needsToTraverseNextNode = childrenAddress != 0;
satok30088252010-12-01 21:22:15 +0900203 // -- after address or flag
204 int freq = 1;
satok715514d2010-12-02 20:19:59 +0900205 // If terminal, increment pos
satoke808e432010-12-02 14:53:24 +0900206 if (terminal) freq = Dictionary::getFreq(DICT, IS_LATEST_DICT_VERSION, &pos);
satok30088252010-12-01 21:22:15 +0900207 // -- after add or freq
satok28bd03b2010-12-03 16:39:16 +0900208 bool newTraverseAllNodes = traverseAllNodes;
209 int newSnr = snr;
210 int newDiffs = diffs;
211 int newInputIndex = inputIndex;
satok30088252010-12-01 21:22:15 +0900212
satok28bd03b2010-12-03 16:39:16 +0900213 // If we are only doing traverseAllNodes, no need to look at the typed characters.
214 if (traverseAllNodes || needsToSkipCurrentNode(c, currentChars[0], skipPos, depth)) {
satok30088252010-12-01 21:22:15 +0900215 mWord[depth] = c;
satok28bd03b2010-12-03 16:39:16 +0900216 if (traverseAllNodes && terminal) {
satok715514d2010-12-02 20:19:59 +0900217 onTerminalWhenUserTypedLengthIsGreaterThanInputLength(mWord, mInputLength, depth,
218 snr, nextLetters, nextLettersSize, skipPos, freq);
satok30088252010-12-01 21:22:15 +0900219 }
satok30088252010-12-01 21:22:15 +0900220 } else {
satok28bd03b2010-12-03 16:39:16 +0900221 matchedProximityCharId = getMatchedProximityId(currentChars, lowerC, c, skipPos);
222 if (matchedProximityCharId < 0) continue;
223 mWord[depth] = c;
224 // If inputIndex is greater than mInputLength, that means there is no
225 // proximity chars. So, we don't need to check proximity.
226 const int addedWeight = matchedProximityCharId == 0 ? TYPED_LETTER_MULTIPLIER : 1;
227 const bool isSameAsUserTypedLength = mInputLength == inputIndex + 1;
228 if (isSameAsUserTypedLength && terminal) {
229 onTerminalWhenUserTypedLengthIsSameAsInputLength(mWord, depth, snr,
230 skipPos, freq, addedWeight);
satok30088252010-12-01 21:22:15 +0900231 }
satok28bd03b2010-12-03 16:39:16 +0900232 if (!needsToTraverseNextNode) continue;
233 // Start traversing all nodes after the index exceeds the user typed length
234 newTraverseAllNodes = isSameAsUserTypedLength;
235 newSnr *= addedWeight;
236 newDiffs += (matchedProximityCharId > 0);
237 ++newInputIndex;
238 }
239 if (needsToTraverseNextNode) {
240 getWordsRec(childrenAddress, depth + 1, maxDepth, newTraverseAllNodes,
241 newSnr, newInputIndex, newDiffs, skipPos, nextLetters, nextLettersSize);
satok30088252010-12-01 21:22:15 +0900242 }
243 }
244}
245
satok715514d2010-12-02 20:19:59 +0900246inline void UnigramDictionary::onTerminalWhenUserTypedLengthIsGreaterThanInputLength(
247 unsigned short *word, const int inputLength, const int depth, const int snr,
248 int *nextLetters, const int nextLettersSize, const int skipPos, const int freq) {
249 addWord(word, depth + 1, freq * snr);
250 if (depth >= inputLength && skipPos < 0) {
251 registerNextLetter(mWord[mInputLength], nextLetters, nextLettersSize);
252 }
253}
254
255inline void UnigramDictionary::onTerminalWhenUserTypedLengthIsSameAsInputLength(
256 unsigned short *word, const int depth, const int snr, const int skipPos, const int freq,
257 const int addedWeight) {
258 if (!sameAsTyped(word, depth + 1)) {
259 int finalFreq = freq * snr * addedWeight;
260 // Proximity collection will promote a word of the same length as
261 // what user typed.
262 if (skipPos < 0) finalFreq *= FULL_WORD_MULTIPLIER;
263 addWord(word, depth + 1, finalFreq);
264 }
265}
satok28bd03b2010-12-03 16:39:16 +0900266
267inline bool UnigramDictionary::needsToSkipCurrentNode(const unsigned short c,
268 const unsigned short userTypedChar, const int skipPos, const int depth) {
269 // Skip the ' or other letter and continue deeper
270 return (c == QUOTE && userTypedChar != QUOTE) || skipPos == depth;
271}
272
273inline int UnigramDictionary::getMatchedProximityId(const int *currentChars,
274 const unsigned short lowerC, const unsigned short c, const int skipPos) {
275 bool matched = false;
276 int j = 0;
277 while (currentChars[j] > 0) {
278 matched = (currentChars[j] == lowerC || currentChars[j] == c);
279 // If skipPos is defined, not to search proximity collections.
280 // First char is what user typed.
281 if (matched) {
282 return j;
283 } else if (skipPos >= 0) {
284 return -1;
285 }
286 ++j;
287 }
288 return -1;
289}
290
satok30088252010-12-01 21:22:15 +0900291} // namespace latinime