File: script_translator.cc

package info (click to toggle)
librime 1.2%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 20,608 kB
  • ctags: 25,041
  • sloc: cpp: 119,202; sh: 21,794; ansic: 7,346; python: 4,372; makefile: 863; perl: 288; ruby: 50
file content (428 lines) | stat: -rw-r--r-- 14,135 bytes parent folder | download
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
425
426
427
428
//
// Copyleft RIME Developers
// License: GPLv3
//
// Script translator
//
// 2011-07-10 GONG Chen <chen.sst@gmail.com>
//
#include <algorithm>
#include <boost/algorithm/string/join.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/foreach.hpp>
#include <rime/composition.h>
#include <rime/candidate.h>
#include <rime/config.h>
#include <rime/context.h>
#include <rime/engine.h>
#include <rime/schema.h>
#include <rime/translation.h>
#include <rime/dict/dictionary.h>
#include <rime/algo/syllabifier.h>
#include <rime/gear/poet.h>
#include <rime/gear/script_translator.h>
#include <rime/gear/translator_commons.h>


//static const char *quote_left = "\xef\xbc\x88";
//static const char *quote_right = "\xef\xbc\x89";

namespace rime {

namespace {

struct DelimitSyllableState {
  const std::string *input;
  const std::string *delimiters;
  const SyllableGraph *graph;
  const Code *code;
  size_t end_pos;
  std::string output;
};

bool DelimitSyllablesDfs(DelimitSyllableState *state,
                         size_t current_pos, size_t depth) {
  if (depth == state->code->size()) {
    return current_pos == state->end_pos;
  }
  SyllableId syllable_id = state->code->at(depth);
  EdgeMap::const_iterator z = state->graph->edges.find(current_pos);
  if (z == state->graph->edges.end())
    return false;
  // favor longer spellings
  BOOST_REVERSE_FOREACH(const EndVertexMap::value_type &y, z->second) {
    size_t end_vertex_pos = y.first;
    if (end_vertex_pos > state->end_pos)
      continue;
    SpellingMap::const_iterator x = y.second.find(syllable_id);
    if (x != y.second.end()) {
      size_t len = state->output.length();
      if (depth > 0 && len > 0 &&
          state->delimiters->find(
              state->output[len - 1]) == std::string::npos) {
        state->output += state->delimiters->at(0);
      }
      state->output += state->input->substr(current_pos,
                                            end_vertex_pos - current_pos);
      if (DelimitSyllablesDfs(state, end_vertex_pos, depth + 1))
        return true;
      state->output.resize(len);
    }
  }
  return false;
}

}  // anonymous namespace

class ScriptTranslation : public Translation,
                          public Syllabification,
                          public boost::enable_shared_from_this<ScriptTranslation>
{
 public:
  ScriptTranslation(ScriptTranslator *translator,
                    const std::string &input, size_t start)
      : translator_(translator),
        input_(input), start_(start),
        user_phrase_index_(0) {
    set_exhausted(true);
  }
  bool Evaluate(Dictionary *dict, UserDictionary *user_dict);
  virtual bool Next();
  virtual shared_ptr<Candidate> Peek();
  virtual size_t PreviousStop(size_t caret_pos) const;
  virtual size_t NextStop(size_t caret_pos) const;

 protected:
  bool CheckEmpty();
  bool IsNormalSpelling() const;
  template <class CandidateT>
  std::string GetPreeditString(const CandidateT &cand) const;
  template <class CandidateT>
  std::string GetOriginalSpelling(const CandidateT &cand) const;
  shared_ptr<Sentence> MakeSentence(Dictionary *dict,
                                    UserDictionary *user_dict);

  ScriptTranslator *translator_;
  std::string input_;
  size_t start_;

  SyllableGraph syllable_graph_;
  shared_ptr<DictEntryCollector> phrase_;
  shared_ptr<UserDictEntryCollector> user_phrase_;
  shared_ptr<Sentence> sentence_;

  DictEntryCollector::reverse_iterator phrase_iter_;
  UserDictEntryCollector::reverse_iterator user_phrase_iter_;
  size_t user_phrase_index_;
};

// ScriptTranslator implementation

ScriptTranslator::ScriptTranslator(const Ticket& ticket)
    : Translator(ticket),
      Memory(ticket),
      TranslatorOptions(ticket),
      spelling_hints_(0) {
  if (!engine_) return;
  Config *config = engine_->schema()->config();
  if (config) {
    config->GetInt(name_space_ + "/spelling_hints", &spelling_hints_);
  }
}

shared_ptr<Translation> ScriptTranslator::Query(const std::string &input,
                                                const Segment &segment,
                                                std::string* prompt) {
  if (!dict_ || !dict_->loaded())
    return shared_ptr<Translation>();
  if (!segment.HasTag(tag_))
    return shared_ptr<Translation>();
  DLOG(INFO) << "input = '" << input
             << "', [" << segment.start << ", " << segment.end << ")";

  bool enable_user_dict = user_dict_ && user_dict_->loaded() &&
      !IsUserDictDisabledFor(input);

  // the translator should survive translations it creates
  shared_ptr<ScriptTranslation> result =
      boost::make_shared<ScriptTranslation>(this, input, segment.start);
  if (!result ||
      !result->Evaluate(dict_.get(),
                        enable_user_dict ? user_dict_.get() : NULL)) {
    return shared_ptr<Translation>();
  }
  return make_shared<UniqueFilter>(result);
}

std::string ScriptTranslator::FormatPreedit(const std::string& preedit) {
  std::string result(preedit);
  preedit_formatter_.Apply(&result);
  return result;
}

std::string ScriptTranslator::Spell(const Code &code) {
  std::string result;
  std::vector<std::string> syllables;
  if (!dict_ || !dict_->Decode(code, &syllables) || syllables.empty())
    return result;
  result =  boost::algorithm::join(syllables,
                                   std::string(1, delimiters_.at(0)));
  comment_formatter_.Apply(&result);
  return result;
}

bool ScriptTranslator::Memorize(const CommitEntry& commit_entry) {
  bool update_elements = false;
  // avoid updating single character entries within a phrase which is
  // composed with single characters only
  if (commit_entry.elements.size() > 1) {
    BOOST_FOREACH(const DictEntry* e, commit_entry.elements) {
      if (e->code.size() > 1) {
        update_elements = true;
        break;
      }
    }
  }
  if (update_elements) {
    BOOST_FOREACH(const DictEntry* e, commit_entry.elements) {
      user_dict_->UpdateEntry(*e, 0);
    }
  }
  user_dict_->UpdateEntry(commit_entry, 1);
  return true;
}

// ScriptTranslation implementation

bool ScriptTranslation::Evaluate(Dictionary *dict, UserDictionary *user_dict) {
  Syllabifier syllabifier(translator_->delimiters(),
                          translator_->enable_completion(),
                          translator_->strict_spelling());
  size_t consumed = syllabifier.BuildSyllableGraph(input_,
                                                   *dict->prism(),
                                                   &syllable_graph_);

  phrase_ = dict->Lookup(syllable_graph_, 0);
  if (user_dict) {
    user_phrase_ = user_dict->Lookup(syllable_graph_, 0);
  }
  if (!phrase_ && !user_phrase_)
    return false;
  // make sentences when there is no exact-matching phrase candidate
  size_t translated_len = 0;
  if (phrase_ && !phrase_->empty())
    translated_len = (std::max)(translated_len, phrase_->rbegin()->first);
  if (user_phrase_ && !user_phrase_->empty())
    translated_len = (std::max)(translated_len, user_phrase_->rbegin()->first);
  if (translated_len < consumed &&
      syllable_graph_.edges.size() > 1) {  // at least 2 syllables required
    sentence_ = MakeSentence(dict, user_dict);
  }

  if (phrase_) phrase_iter_ = phrase_->rbegin();
  if (user_phrase_) user_phrase_iter_ = user_phrase_->rbegin();
  return !CheckEmpty();
}

template <class CandidateT>
std::string ScriptTranslation::GetPreeditString(
    const CandidateT &cand) const {
  DelimitSyllableState state;
  state.input = &input_;
  state.delimiters = &translator_->delimiters();
  state.graph = &syllable_graph_;
  state.code = &cand.code();
  state.end_pos = cand.end() - start_;
  bool success = DelimitSyllablesDfs(&state, cand.start() - start_, 0);
  if (success) {
    return translator_->FormatPreedit(state.output);
  }
  else {
    return std::string();
  }
}

template <class CandidateT>
std::string ScriptTranslation::GetOriginalSpelling(
    const CandidateT& cand) const {
  if (translator_ &&
      static_cast<int>(cand.code().size()) <= translator_->spelling_hints()) {
    return translator_->Spell(cand.code());
  }
  return std::string();
}

bool ScriptTranslation::Next() {
  if (exhausted())
    return false;
  if (sentence_) {
    sentence_.reset();
    return !CheckEmpty();
  }
  int user_phrase_code_length = 0;
  if (user_phrase_ && user_phrase_iter_ != user_phrase_->rend()) {
    user_phrase_code_length = user_phrase_iter_->first;
  }
  int phrase_code_length = 0;
  if (phrase_ && phrase_iter_ != phrase_->rend()) {
    phrase_code_length = phrase_iter_->first;
  }
  if (user_phrase_code_length > 0 &&
      user_phrase_code_length >= phrase_code_length) {
    DictEntryList &entries(user_phrase_iter_->second);
    if (++user_phrase_index_ >= entries.size()) {
      ++user_phrase_iter_;
      user_phrase_index_ = 0;
    }
  }
  else if (phrase_code_length > 0) {
    DictEntryIterator &iter(phrase_iter_->second);
    if (!iter.Next()) {
      ++phrase_iter_;
    }
  }
  return !CheckEmpty();
}

bool ScriptTranslation::IsNormalSpelling() const {
  return !syllable_graph_.vertices.empty() &&
      (syllable_graph_.vertices.rbegin()->second == kNormalSpelling);
}

shared_ptr<Candidate> ScriptTranslation::Peek() {
  if (exhausted())
    return shared_ptr<Candidate>();
  if (sentence_) {
    if (sentence_->preedit().empty()) {
      sentence_->set_preedit(GetPreeditString(*sentence_));
    }
    if (sentence_->comment().empty()) {
      std::string spelling(GetOriginalSpelling(*sentence_));
      if (!spelling.empty() &&
          spelling != sentence_->preedit()) {
        sentence_->set_comment(/*quote_left + */spelling/* + quote_right*/);
      }
    }
    return sentence_;
  }
  size_t user_phrase_code_length = 0;
  if (user_phrase_ && user_phrase_iter_ != user_phrase_->rend()) {
    user_phrase_code_length = user_phrase_iter_->first;
  }
  size_t phrase_code_length = 0;
  if (phrase_ && phrase_iter_ != phrase_->rend()) {
    phrase_code_length = phrase_iter_->first;
  }
  shared_ptr<Phrase> cand;
  if (user_phrase_code_length > 0 &&
      user_phrase_code_length >= phrase_code_length) {
    DictEntryList &entries(user_phrase_iter_->second);
    const shared_ptr<DictEntry> &e(entries[user_phrase_index_]);
    DLOG(INFO) << "user phrase '" << e->text
               << "', code length: " << user_phrase_code_length;
    cand = make_shared<Phrase>(translator_->language(),
                               "phrase",
                               start_,
                               start_ + user_phrase_code_length,
                               e);
    cand->set_quality(e->weight +
                      translator_->initial_quality() +
                      (IsNormalSpelling() ? 0.5 : -0.5));
  }
  else if (phrase_code_length > 0) {
    DictEntryIterator &iter(phrase_iter_->second);
    const shared_ptr<DictEntry> &e(iter.Peek());
    DLOG(INFO) << "phrase '" << e->text
               << "', code length: " << user_phrase_code_length;
    cand = make_shared<Phrase>(translator_->language(),
                               "phrase",
                               start_,
                               start_ + phrase_code_length,
                               e);
    cand->set_quality(e->weight +
                      translator_->initial_quality() +
                      (IsNormalSpelling() ? 0 : -1));
  }
  if (cand->preedit().empty()) {
    cand->set_preedit(GetPreeditString(*cand));
  }
  if (cand->comment().empty()) {
    std::string spelling(GetOriginalSpelling(*cand));
    if (!spelling.empty() &&
        spelling != cand->preedit()) {
      cand->set_comment(/*quote_left + */spelling/* + quote_right*/);
    }
  }
  cand->set_syllabification(shared_from_this());
  return cand;
}

bool ScriptTranslation::CheckEmpty() {
  set_exhausted((!phrase_ || phrase_iter_ == phrase_->rend()) &&
                (!user_phrase_ || user_phrase_iter_ == user_phrase_->rend()));
  return exhausted();
}

shared_ptr<Sentence> ScriptTranslation::MakeSentence(
    Dictionary *dict, UserDictionary *user_dict) {
  const int kMaxSyllablesForUserPhraseQuery = 5;
  const double kPenaltyForAmbiguousSyllable = 1e-10;
  WordGraph graph;
  BOOST_FOREACH(const EdgeMap::value_type &s, syllable_graph_.edges) {
    // discourage starting a word from an ambiguous joint
    // bad cases include pinyin syllabification "niju'ede"
    double credibility = 1.0;
    if (syllable_graph_.vertices[s.first] >= kAmbiguousSpelling)
      credibility = kPenaltyForAmbiguousSyllable;
    shared_ptr<UserDictEntryCollector> user_phrase;
    if (user_dict) {
      user_phrase = user_dict->Lookup(syllable_graph_, s.first,
                                      kMaxSyllablesForUserPhraseQuery,
                                      credibility);
    }
    UserDictEntryCollector &u(graph[s.first]);
    if (user_phrase)
      u.swap(*user_phrase);
    shared_ptr<DictEntryCollector> phrase =
        dict->Lookup(syllable_graph_, s.first, credibility);
    if (phrase) {
      // merge lookup results
      BOOST_FOREACH(DictEntryCollector::value_type &t, *phrase) {
        DictEntryList &entries(u[t.first]);
        if (entries.empty()) {
          shared_ptr<DictEntry> e(t.second.Peek());
          entries.push_back(e);
        }
      }
    }
  }
  Poet poet(translator_->language());
  shared_ptr<Sentence> sentence =
      poet.MakeSentence(graph, syllable_graph_.interpreted_length);
  if (sentence) {
    sentence->Offset(start_);
    sentence->set_syllabification(shared_from_this());
  }
  return sentence;
}

size_t ScriptTranslation::PreviousStop(size_t caret_pos) const {
  size_t offset = caret_pos - start_;
  BOOST_REVERSE_FOREACH(const VertexMap::value_type& x,
                        syllable_graph_.vertices) {
    if (x.first < offset)
      return x.first + start_;
  }
  return caret_pos;
}

size_t ScriptTranslation::NextStop(size_t caret_pos) const {
  size_t offset = caret_pos - start_;
  BOOST_FOREACH(const VertexMap::value_type& x, syllable_graph_.vertices) {
    if (x.first > offset)
      return x.first + start_;
  }
  return caret_pos;
}

}  // namespace rime