|
| 1 | +#include <algorithm> |
| 2 | +#include <iterator> |
| 3 | +#include <rime/gear/contextual_translation.h> |
| 4 | +#include <rime/gear/translator_commons.h> |
| 5 | + |
| 6 | +namespace rime { |
| 7 | + |
| 8 | +const int kContextualSearchLimit = 32; |
| 9 | + |
| 10 | +bool ContextualTranslation::Replenish() { |
| 11 | + vector<of<Phrase>> queue; |
| 12 | + size_t end_pos = 0; |
| 13 | + while (!translation_->exhausted() && |
| 14 | + cache_.size() + queue.size() < kContextualSearchLimit) { |
| 15 | + auto cand = translation_->Peek(); |
| 16 | + DLOG(INFO) << cand->text() << " cache/queue: " |
| 17 | + << cache_.size() << "/" << queue.size(); |
| 18 | + if (cand->type() == "phrase" || cand->type() == "table") { |
| 19 | + if (end_pos != cand->end()) { |
| 20 | + end_pos = cand->end(); |
| 21 | + AppendToCache(queue); |
| 22 | + } |
| 23 | + queue.push_back(Evaluate(As<Phrase>(cand))); |
| 24 | + } else { |
| 25 | + AppendToCache(queue); |
| 26 | + cache_.push_back(cand); |
| 27 | + } |
| 28 | + if (!translation_->Next()) { |
| 29 | + break; |
| 30 | + } |
| 31 | + } |
| 32 | + AppendToCache(queue); |
| 33 | + return !cache_.empty(); |
| 34 | +} |
| 35 | + |
| 36 | +an<Phrase> ContextualTranslation::Evaluate(an<Phrase> phrase) { |
| 37 | + auto sentence = New<Sentence>(phrase->language()); |
| 38 | + sentence->Offset(phrase->start()); |
| 39 | + bool is_rear = phrase->end() == input_.length(); |
| 40 | + sentence->Extend(phrase->entry(), phrase->end(), is_rear, preceding_text_, |
| 41 | + grammar_); |
| 42 | + phrase->set_weight(sentence->weight()); |
| 43 | + DLOG(INFO) << "contextual suggestion: " << phrase->text() |
| 44 | + << " weight: " << phrase->weight(); |
| 45 | + return phrase; |
| 46 | +} |
| 47 | + |
| 48 | +static bool compare_by_weight_desc(const an<Phrase>& a, const an<Phrase>& b) { |
| 49 | + return a->weight() > b->weight(); |
| 50 | +} |
| 51 | + |
| 52 | +void ContextualTranslation::AppendToCache(vector<of<Phrase>>& queue) { |
| 53 | + if (queue.empty()) return; |
| 54 | + DLOG(INFO) << "appending to cache " << queue.size() << " candidates."; |
| 55 | + std::sort(queue.begin(), queue.end(), compare_by_weight_desc); |
| 56 | + std::copy(queue.begin(), queue.end(), std::back_inserter(cache_)); |
| 57 | + queue.clear(); |
| 58 | +} |
| 59 | + |
| 60 | +} // namespace rime |
0 commit comments