forked from rime/librime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dictionary.cc
424 lines (388 loc) · 12.9 KB
/
dictionary.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//
// Copyright RIME Developers
// Distributed under the BSD License
//
// 2011-07-05 GONG Chen <chen.sst@gmail.com>
//
#include <boost/filesystem.hpp>
#include <rime/algo/syllabifier.h>
#include <rime/common.h>
#include <rime/dict/dictionary.h>
#include <rime/resource.h>
#include <rime/schema.h>
#include <rime/service.h>
#include <rime/ticket.h>
#include <utility>
namespace rime {
namespace dictionary {
struct Chunk {
Table* table = nullptr;
Code code;
const table::Entry* entries = nullptr;
size_t size = 0;
size_t cursor = 0;
string remaining_code; // for predictive queries
double credibility = 0.0;
Chunk() = default;
Chunk(Table* t, const Code& c, const table::Entry* e, double cr = 0.0)
: table(t), code(c), entries(e), size(1), cursor(0), credibility(cr) {}
Chunk(Table* t, const TableAccessor& a, double cr = 0.0)
: Chunk(t, a, string(), cr) {}
Chunk(Table* t, const TableAccessor& a, const string& r, double cr = 0.0)
: table(t),
code(a.index_code()),
entries(a.entry()),
size(a.remaining()),
cursor(0),
remaining_code(r),
credibility(cr) {}
};
struct QueryResult {
vector<Chunk> chunks;
};
bool compare_chunk_by_head_element(const Chunk& a, const Chunk& b) {
if (!a.entries || a.cursor >= a.size)
return false;
if (!b.entries || b.cursor >= b.size)
return true;
if (a.remaining_code.length() != b.remaining_code.length())
return a.remaining_code.length() < b.remaining_code.length();
return a.credibility + a.entries[a.cursor].weight >
b.credibility + b.entries[b.cursor].weight; // by weight desc
}
size_t match_extra_code(const table::Code* extra_code,
size_t depth,
const SyllableGraph& syll_graph,
size_t current_pos) {
if (!extra_code || depth >= extra_code->size)
return current_pos; // success
if (current_pos >= syll_graph.interpreted_length)
return 0; // failure (possibly success for completion in the future)
auto index = syll_graph.indices.find(current_pos);
if (index == syll_graph.indices.end())
return 0;
SyllableId current_syll_id = extra_code->at[depth];
auto spellings = index->second.find(current_syll_id);
if (spellings == index->second.end())
return 0;
size_t best_match = 0;
for (const SpellingProperties* props : spellings->second) {
size_t match_end_pos =
match_extra_code(extra_code, depth + 1, syll_graph, props->end_pos);
if (!match_end_pos)
continue;
if (match_end_pos > best_match)
best_match = match_end_pos;
}
return best_match;
}
} // namespace dictionary
DictEntryIterator::DictEntryIterator()
: query_result_(New<dictionary::QueryResult>()) {}
void DictEntryIterator::AddChunk(dictionary::Chunk&& chunk) {
query_result_->chunks.push_back(std::move(chunk));
entry_count_ += chunk.size;
}
void DictEntryIterator::Sort() {
auto& chunks = query_result_->chunks;
// partial-sort remaining chunks, move best match to chunk_index_
std::partial_sort(chunks.begin() + chunk_index_,
chunks.begin() + chunk_index_ + 1, chunks.end(),
dictionary::compare_chunk_by_head_element);
}
void DictEntryIterator::AddFilter(DictEntryFilter filter) {
DictEntryFilterBinder::AddFilter(filter);
// the introduced filter could invalidate the current or even all the
// remaining entries
while (!exhausted() && !filter_(Peek())) {
FindNextEntry();
}
}
an<DictEntry> DictEntryIterator::Peek() {
if (!entry_ && !exhausted()) {
// get next entry from current chunk
const auto& chunk = query_result_->chunks[chunk_index_];
const auto& e = chunk.entries[chunk.cursor];
DLOG(INFO) << "creating temporary dict entry '"
<< chunk.table->GetEntryText(e) << "'.";
entry_ = New<DictEntry>();
entry_->code = chunk.code;
entry_->text = chunk.table->GetEntryText(e);
const double kS = 18.420680743952367; // log(1e8)
entry_->weight = e.weight - kS + chunk.credibility;
if (!chunk.remaining_code.empty()) {
entry_->comment = "~" + chunk.remaining_code;
entry_->remaining_code_length = chunk.remaining_code.length();
}
}
return entry_;
}
bool DictEntryIterator::FindNextEntry() {
if (exhausted()) {
return false;
}
auto& chunk = query_result_->chunks[chunk_index_];
if (++chunk.cursor >= chunk.size) {
++chunk_index_;
}
if (exhausted()) {
return false;
}
// reorder chunks to move the one with the best entry to head
Sort();
return true;
}
bool DictEntryIterator::Next() {
entry_.reset();
if (!FindNextEntry()) {
return false;
}
while (filter_ && !filter_(Peek())) {
if (!FindNextEntry()) {
return false;
}
}
return true;
}
// Note: does not apply filters
bool DictEntryIterator::Skip(size_t num_entries) {
while (num_entries > 0) {
if (exhausted())
return false;
auto& chunk = query_result_->chunks[chunk_index_];
if (chunk.cursor + num_entries < chunk.size) {
chunk.cursor += num_entries;
return true;
}
num_entries -= (chunk.size - chunk.cursor);
++chunk_index_;
}
return true;
}
bool DictEntryIterator::exhausted() const {
return chunk_index_ >= query_result_->chunks.size();
}
// Dictionary members
Dictionary::Dictionary(string name,
vector<string> packs,
vector<of<Table>> tables,
an<Prism> prism)
: name_(name),
packs_(std::move(packs)),
tables_(std::move(tables)),
prism_(std::move(prism)) {}
Dictionary::~Dictionary() {
// should not close shared table and prism objects
}
static void lookup_table(Table* table,
DictEntryCollector* collector,
const SyllableGraph& syllable_graph,
size_t start_pos,
double initial_credibility) {
TableQueryResult result;
if (!table->Query(syllable_graph, start_pos, &result)) {
return;
}
// copy result
for (auto& v : result) {
size_t end_pos = v.first;
for (TableAccessor& a : v.second) {
double cr = initial_credibility + a.credibility();
if (a.extra_code()) {
do {
size_t actual_end_pos = dictionary::match_extra_code(
a.extra_code(), 0, syllable_graph, end_pos);
if (actual_end_pos == 0)
continue;
(*collector)[actual_end_pos].AddChunk(
{table, a.code(), a.entry(), cr});
} while (a.Next());
} else {
(*collector)[end_pos].AddChunk({table, a, cr});
}
}
}
}
an<DictEntryCollector> Dictionary::Lookup(const SyllableGraph& syllable_graph,
size_t start_pos,
double initial_credibility) {
if (!loaded())
return nullptr;
auto collector = New<DictEntryCollector>();
for (const auto& table : tables_) {
if (!table->IsOpen())
continue;
lookup_table(table.get(), collector.get(), syllable_graph, start_pos,
initial_credibility);
}
if (collector->empty())
return nullptr;
// sort each group of equal code length
for (auto& v : *collector) {
v.second.Sort();
}
return collector;
}
size_t Dictionary::LookupWords(DictEntryIterator* result,
const string& str_code,
bool predictive,
size_t expand_search_limit) {
DLOG(INFO) << "lookup: " << str_code;
if (!loaded())
return 0;
vector<Prism::Match> keys;
if (predictive) {
prism_->ExpandSearch(str_code, &keys, expand_search_limit);
} else {
Prism::Match match{0, 0};
if (prism_->GetValue(str_code, &match.value)) {
keys.push_back(match);
}
}
DLOG(INFO) << "found " << keys.size() << " matching keys thru the prism.";
size_t code_length(str_code.length());
for (auto& match : keys) {
SpellingAccessor accessor(prism_->QuerySpelling(match.value));
while (!accessor.exhausted()) {
SyllableId syllable_id = accessor.syllable_id();
SpellingType type = accessor.properties().type;
accessor.Next();
if (type > kNormalSpelling)
continue;
string remaining_code;
if (match.length > code_length) {
string syllable = primary_table()->GetSyllableById(syllable_id);
if (syllable.length() > code_length)
remaining_code = syllable.substr(code_length);
}
for (const auto& table : tables_) {
if (!table->IsOpen())
continue;
TableAccessor a = table->QueryWords(syllable_id);
if (!a.exhausted()) {
DLOG(INFO) << "remaining code: " << remaining_code;
result->AddChunk({table.get(), a, remaining_code});
}
}
}
}
return keys.size();
}
bool Dictionary::Decode(const Code& code, vector<string>* result) {
if (!result || tables_.empty())
return false;
result->clear();
for (SyllableId c : code) {
string s = primary_table()->GetSyllableById(c);
if (s.empty())
return false;
result->push_back(s);
}
return true;
}
bool Dictionary::Exists() const {
return boost::filesystem::exists(prism_->file_name()) && !tables_.empty() &&
boost::filesystem::exists(tables_[0]->file_name());
}
bool Dictionary::Remove() {
if (loaded())
return false;
prism_->Remove();
for (const auto& table : tables_) {
table->Remove();
}
return true;
}
bool Dictionary::Load() {
LOG(INFO) << "loading dictionary '" << name_ << "'.";
if (tables_.empty()) {
LOG(ERROR) << "Cannot load dictionary '" << name_
<< "'; it contains no tables.";
return false;
}
auto& primary_table = tables_[0];
if (!primary_table || (!primary_table->IsOpen() && !primary_table->Load())) {
LOG(ERROR) << "Error loading table for dictionary '" << name_ << "'.";
return false;
}
if (!prism_ || (!prism_->IsOpen() && !prism_->Load())) {
LOG(ERROR) << "Error loading prism for dictionary '" << name_ << "'.";
return false;
}
// packs are optional
for (int i = 1; i < tables_.size(); ++i) {
const auto& table = tables_[i];
if (!table->IsOpen() && table->Exists() && table->Load()) {
LOG(INFO) << "loaded pack: " << packs_[i - 1];
}
}
return true;
}
bool Dictionary::loaded() const {
return !tables_.empty() && tables_[0]->IsOpen() && prism_ && prism_->IsOpen();
}
// DictionaryComponent members
static const ResourceType kPrismResourceType = {"prism", "", ".prism.bin"};
static const ResourceType kTableResourceType = {"table", "", ".table.bin"};
DictionaryComponent::DictionaryComponent()
: prism_resource_resolver_(
Service::instance().CreateDeployedResourceResolver(
kPrismResourceType)),
table_resource_resolver_(
Service::instance().CreateDeployedResourceResolver(
kTableResourceType)) {}
DictionaryComponent::~DictionaryComponent() {}
Dictionary* DictionaryComponent::Create(const Ticket& ticket) {
if (!ticket.schema)
return nullptr;
Config* config = ticket.schema->config();
string dict_name;
if (!config->GetString(ticket.name_space + "/dictionary", &dict_name)) {
LOG(ERROR) << ticket.name_space << "/dictionary not specified in schema '"
<< ticket.schema->schema_id() << "'.";
return nullptr;
}
if (dict_name.empty()) {
return nullptr; // not requiring static dictionary
}
string prism_name;
if (!config->GetString(ticket.name_space + "/prism", &prism_name)) {
prism_name = dict_name;
}
vector<string> packs;
if (auto pack_list = config->GetList(ticket.name_space + "/packs")) {
for (const auto& item : *pack_list) {
if (auto value = As<ConfigValue>(item)) {
packs.push_back(value->str());
}
}
}
return Create(std::move(dict_name), std::move(prism_name), std::move(packs));
}
Dictionary* DictionaryComponent::Create(string dict_name,
string prism_name,
vector<string> packs) {
// obtain prism and primary table objects
auto primary_table = table_map_[dict_name].lock();
if (!primary_table) {
auto file_path = table_resource_resolver_->ResolvePath(dict_name).string();
table_map_[dict_name] = primary_table = New<Table>(file_path);
}
auto prism = prism_map_[prism_name].lock();
if (!prism) {
auto file_path = prism_resource_resolver_->ResolvePath(prism_name).string();
prism_map_[prism_name] = prism = New<Prism>(file_path);
}
vector<of<Table>> tables = {std::move(primary_table)};
for (const auto& pack : packs) {
auto table = table_map_[pack].lock();
if (!table) {
auto file_path = table_resource_resolver_->ResolvePath(pack).string();
table_map_[pack] = table = New<Table>(file_path);
}
tables.push_back(std::move(table));
}
return new Dictionary(std::move(dict_name), std::move(packs),
std::move(tables), std::move(prism));
}
} // namespace rime