tesseract  4.1.0
control.cpp
Go to the documentation of this file.
1 /******************************************************************
2  * File: control.cpp (Formerly control.c)
3  * Description: Module-independent matcher controller.
4  * Author: Ray Smith
5  *
6  * (C) Copyright 1992, Hewlett-Packard Ltd.
7  ** Licensed under the Apache License, Version 2.0 (the "License");
8  ** you may not use this file except in compliance with the License.
9  ** You may obtain a copy of the License at
10  ** http://www.apache.org/licenses/LICENSE-2.0
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 
19 // Include automatically generated configuration file if running autoconf.
20 #ifdef HAVE_CONFIG_H
21 #include "config_auto.h"
22 #endif
23 
24 #include <cmath>
25 #include <cstdint> // for int16_t, int32_t
26 #include <cstdio> // for fclose, fopen, FILE
27 #include <ctime> // for clock
28 #include <cctype>
29 #include "callcpp.h"
30 #include "control.h"
31 #ifndef DISABLED_LEGACY_ENGINE
32 #include "docqual.h"
33 #include "drawfx.h"
34 #include "fixspace.h"
35 #endif
36 #include "lstmrecognizer.h"
37 #include "ocrclass.h"
38 #include "output.h"
39 #include "pageres.h" // for WERD_RES, PAGE_RES_IT, PAGE_RES, BLO...
40 #ifndef DISABLED_LEGACY_ENGINE
41 #include "reject.h"
42 #endif
43 #include "sorthelper.h"
44 #include "tesseractclass.h"
45 #include "tessvars.h"
46 #include "werdit.h"
47 
48 const char* const kBackUpConfigFile = "tempconfigdata.config";
49 // Min believable x-height for any text when refitting as a fraction of
50 // original x-height
51 const double kMinRefitXHeightFraction = 0.5;
52 
53 
60 namespace tesseract {
61 
63  TBOX &selection_box) {
64  PAGE_RES_IT* it = make_pseudo_word(page_res, selection_box);
65  if (it != nullptr) {
67  it->DeleteCurrentWord();
68  delete it;
69  }
70 }
71 
78  int16_t char_qual;
79  int16_t good_char_qual;
80 
81  WordData word_data(*pr_it);
82  SetupWordPassN(2, &word_data);
83  // LSTM doesn't run on pass2, but we want to run pass2 for tesseract.
84  if (lstm_recognizer_ == nullptr) {
85 #ifndef DISABLED_LEGACY_ENGINE
86  classify_word_and_language(2, pr_it, &word_data);
87 #endif // ndef DISABLED_LEGACY_ENGINE
88  } else {
89  classify_word_and_language(1, pr_it, &word_data);
90  }
91 #ifndef DISABLED_LEGACY_ENGINE
93  WERD_RES* word_res = pr_it->word();
94  word_char_quality(word_res, pr_it->row()->row, &char_qual, &good_char_qual);
95  tprintf("\n%d chars; word_blob_quality: %d; outline_errs: %d; "
96  "char_quality: %d; good_char_quality: %d\n",
97  word_res->reject_map.length(),
98  word_blob_quality(word_res, pr_it->row()->row),
99  word_outline_errs(word_res), char_qual, good_char_qual);
100  }
101 #endif // ndef DISABLED_LEGACY_ENGINE
102  return true;
103 }
104 
105 // Helper function to check for a target word and handle it appropriately.
106 // Inspired by Jetsoft's requirement to process only single words on pass2
107 // and beyond.
108 // If word_config is not null:
109 // If the word_box and target_word_box overlap, read the word_config file
110 // else reset to previous config data.
111 // return true.
112 // else
113 // If the word_box and target_word_box overlap or pass <= 1, return true.
114 // Note that this function uses a fixed temporary file for storing the previous
115 // configs, so it is neither thread-safe, nor process-safe, but the assumption
116 // is that it will only be used for one debug window at a time.
117 //
118 // Since this function is used for debugging (and not to change OCR results)
119 // set only debug params from the word config file.
120 bool Tesseract::ProcessTargetWord(const TBOX& word_box,
121  const TBOX& target_word_box,
122  const char* word_config,
123  int pass) {
124  if (word_config != nullptr) {
125  if (word_box.major_overlap(target_word_box)) {
126  if (backup_config_file_ == nullptr) {
127  backup_config_file_ = kBackUpConfigFile;
128  FILE* config_fp = fopen(backup_config_file_, "wb");
129  if (config_fp == nullptr) {
130  tprintf("Error, failed to open file \"%s\"\n", backup_config_file_);
131  } else {
132  ParamUtils::PrintParams(config_fp, params());
133  fclose(config_fp);
134  }
135  ParamUtils::ReadParamsFile(word_config,
137  params());
138  }
139  } else {
140  if (backup_config_file_ != nullptr) {
141  ParamUtils::ReadParamsFile(backup_config_file_,
143  params());
144  backup_config_file_ = nullptr;
145  }
146  }
147  } else if (pass > 1 && !word_box.major_overlap(target_word_box)) {
148  return false;
149  }
150  return true;
151 }
152 
155  const TBOX* target_word_box,
156  const char* word_config,
157  PAGE_RES* page_res,
158  GenericVector<WordData>* words) {
159  // Prepare all the words.
160  PAGE_RES_IT page_res_it(page_res);
161  for (page_res_it.restart_page(); page_res_it.word() != nullptr;
162  page_res_it.forward()) {
163  if (target_word_box == nullptr ||
164  ProcessTargetWord(page_res_it.word()->word->bounding_box(),
165  *target_word_box, word_config, 1)) {
166  words->push_back(WordData(page_res_it));
167  }
168  }
169  // Setup all the words for recognition with polygonal approximation.
170  for (int w = 0; w < words->size(); ++w) {
171  SetupWordPassN(pass_n, &(*words)[w]);
172  if (w > 0) (*words)[w].prev_word = &(*words)[w - 1];
173  }
174 }
175 
176 // Sets up the single word ready for whichever engine is to be run.
177 void Tesseract::SetupWordPassN(int pass_n, WordData* word) {
178  if (pass_n == 1 || !word->word->done) {
179  if (pass_n == 1) {
180  word->word->SetupForRecognition(unicharset, this, BestPix(),
181  tessedit_ocr_engine_mode, nullptr,
185  word->row, word->block);
186  } else if (pass_n == 2) {
187  // TODO(rays) Should we do this on pass1 too?
188  word->word->caps_height = 0.0;
189  if (word->word->x_height == 0.0f)
190  word->word->x_height = word->row->x_height();
191  }
192  word->lang_words.truncate(0);
193  for (int s = 0; s <= sub_langs_.size(); ++s) {
194  // The sub_langs_.size() entry is for the master language.
195  Tesseract* lang_t = s < sub_langs_.size() ? sub_langs_[s] : this;
196  auto* word_res = new WERD_RES;
197  word_res->InitForRetryRecognition(*word->word);
198  word->lang_words.push_back(word_res);
199  // LSTM doesn't get setup for pass2.
200  if (pass_n == 1 || lang_t->tessedit_ocr_engine_mode != OEM_LSTM_ONLY) {
201  word_res->SetupForRecognition(
202  lang_t->unicharset, lang_t, BestPix(),
203  lang_t->tessedit_ocr_engine_mode, nullptr,
205  lang_t->textord_use_cjk_fp_model,
206  lang_t->poly_allow_detailed_fx, word->row, word->block);
207  }
208  }
209  }
210 }
211 
212 // Runs word recognition on all the words.
213 bool Tesseract::RecogAllWordsPassN(int pass_n, ETEXT_DESC* monitor,
214  PAGE_RES_IT* pr_it,
215  GenericVector<WordData>* words) {
216  // TODO(rays) Before this loop can be parallelized (it would yield a massive
217  // speed-up) all remaining member globals need to be converted to local/heap
218  // (eg set_pass1 and set_pass2) and an intermediate adaption pass needs to be
219  // added. The results will be significantly different with adaption on, and
220  // deterioration will need investigation.
221  pr_it->restart_page();
222  for (int w = 0; w < words->size(); ++w) {
223  WordData* word = &(*words)[w];
224  if (w > 0) word->prev_word = &(*words)[w - 1];
225  if (monitor != nullptr) {
226  monitor->ocr_alive = true;
227  if (pass_n == 1) {
228  monitor->progress = 70 * w / words->size();
229  if (monitor->progress_callback2 != nullptr) {
230  TBOX box = pr_it->word()->word->bounding_box();
231  (*monitor->progress_callback2)(monitor, box.left(),
232  box.right(), box.top(), box.bottom());
233  }
234  } else {
235  monitor->progress = 70 + 30 * w / words->size();
236  if (monitor->progress_callback2 != nullptr) {
237  (*monitor->progress_callback2)(monitor, 0, 0, 0, 0);
238  }
239  }
240  if (monitor->deadline_exceeded() ||
241  (monitor->cancel != nullptr && (*monitor->cancel)(monitor->cancel_this,
242  words->size()))) {
243  // Timeout. Fake out the rest of the words.
244  for (; w < words->size(); ++w) {
245  (*words)[w].word->SetupFake(unicharset);
246  }
247  return false;
248  }
249  }
250  if (word->word->tess_failed) {
251  int s;
252  for (s = 0; s < word->lang_words.size() &&
253  word->lang_words[s]->tess_failed; ++s) {}
254  // If all are failed, skip it. Image words are skipped by this test.
255  if (s > word->lang_words.size()) continue;
256  }
257  // Sync pr_it with the wth WordData.
258  while (pr_it->word() != nullptr && pr_it->word() != word->word)
259  pr_it->forward();
260  ASSERT_HOST(pr_it->word() != nullptr);
261  bool make_next_word_fuzzy = false;
262  if (!AnyLSTMLang() &&
263  ReassignDiacritics(pass_n, pr_it, &make_next_word_fuzzy)) {
264  // Needs to be setup again to see the new outlines in the chopped_word.
265  SetupWordPassN(pass_n, word);
266  }
267 
268  classify_word_and_language(pass_n, pr_it, word);
270  tprintf("Pass%d: %s [%s]\n", pass_n,
272  word->word->best_choice->debug_string().string());
273  }
274  pr_it->forward();
275  if (make_next_word_fuzzy && pr_it->word() != nullptr) {
276  pr_it->MakeCurrentWordFuzzy();
277  }
278  }
279  return true;
280 }
281 
304  ETEXT_DESC* monitor,
305  const TBOX* target_word_box,
306  const char* word_config,
307  int dopasses) {
308  PAGE_RES_IT page_res_it(page_res);
309 
311  tessedit_test_adaption.set_value (true);
312  tessedit_minimal_rejection.set_value (true);
313  }
314 
315  if (dopasses==0 || dopasses==1) {
316  page_res_it.restart_page();
317  // ****************** Pass 1 *******************
318 
319  #ifndef DISABLED_LEGACY_ENGINE
320  // If the adaptive classifier is full switch to one we prepared earlier,
321  // ie on the previous page. If the current adaptive classifier is non-empty,
322  // prepare a backup starting at this page, in case it fills up. Do all this
323  // independently for each language.
324  if (AdaptiveClassifierIsFull()) {
326  } else if (!AdaptiveClassifierIsEmpty()) {
328  }
329  // Now check the sub-langs as well.
330  for (int i = 0; i < sub_langs_.size(); ++i) {
331  if (sub_langs_[i]->AdaptiveClassifierIsFull()) {
332  sub_langs_[i]->SwitchAdaptiveClassifier();
333  } else if (!sub_langs_[i]->AdaptiveClassifierIsEmpty()) {
334  sub_langs_[i]->StartBackupAdaptiveClassifier();
335  }
336  }
337 
338  #endif // ndef DISABLED_LEGACY_ENGINE
339 
340  // Set up all words ready for recognition, so that if parallelism is on
341  // all the input and output classes are ready to run the classifier.
343  SetupAllWordsPassN(1, target_word_box, word_config, page_res, &words);
344  #ifndef DISABLED_LEGACY_ENGINE
345  if (tessedit_parallelize) {
346  PrerecAllWordsPar(words);
347  }
348  #endif // ndef DISABLED_LEGACY_ENGINE
349 
350  stats_.word_count = words.size();
351 
352  stats_.dict_words = 0;
353  stats_.doc_blob_quality = 0;
354  stats_.doc_outline_errs = 0;
355  stats_.doc_char_quality = 0;
356  stats_.good_char_count = 0;
357  stats_.doc_good_char_quality = 0;
358 
359  most_recently_used_ = this;
360  // Run pass 1 word recognition.
361  if (!RecogAllWordsPassN(1, monitor, &page_res_it, &words)) return false;
362  // Pass 1 post-processing.
363  for (page_res_it.restart_page(); page_res_it.word() != nullptr;
364  page_res_it.forward()) {
365  if (page_res_it.word()->word->flag(W_REP_CHAR)) {
366  fix_rep_char(&page_res_it);
367  continue;
368  }
369 
370  // Count dict words.
371  if (page_res_it.word()->best_choice->permuter() == USER_DAWG_PERM)
372  ++(stats_.dict_words);
373 
374  // Update misadaption log (we only need to do it on pass 1, since
375  // adaption only happens on this pass).
376  if (page_res_it.word()->blamer_bundle != nullptr &&
377  page_res_it.word()->blamer_bundle->misadaption_debug().length() > 0) {
378  page_res->misadaption_log.push_back(
379  page_res_it.word()->blamer_bundle->misadaption_debug());
380  }
381  }
382  }
383 
384  if (dopasses == 1) return true;
385 
386  #ifndef DISABLED_LEGACY_ENGINE
387 
388  // ****************** Pass 2 *******************
390  AnyTessLang()) {
391  page_res_it.restart_page();
393  SetupAllWordsPassN(2, target_word_box, word_config, page_res, &words);
394  if (tessedit_parallelize) {
395  PrerecAllWordsPar(words);
396  }
397  most_recently_used_ = this;
398  // Run pass 2 word recognition.
399  if (!RecogAllWordsPassN(2, monitor, &page_res_it, &words)) return false;
400  }
401 
402  // The next passes are only required for Tess-only.
403  if (AnyTessLang() && !AnyLSTMLang()) {
404  // ****************** Pass 3 *******************
405  // Fix fuzzy spaces.
407 
410  fix_fuzzy_spaces(monitor, stats_.word_count, page_res);
411 
412  // ****************** Pass 4 *******************
415 
416  // ****************** Pass 5,6 *******************
417  rejection_passes(page_res, monitor, target_word_box, word_config);
418 
419  // ****************** Pass 8 *******************
420  font_recognition_pass(page_res);
421 
422  // ****************** Pass 9 *******************
423  // Check the correctness of the final results.
424  blamer_pass(page_res);
425  script_pos_pass(page_res);
426  }
427 
428  #endif // ndef DISABLED_LEGACY_ENGINE
429 
430  // Write results pass.
432  // This is now redundant, but retained commented so show how to obtain
433  // bounding boxes and style information.
434 
435  #ifndef DISABLED_LEGACY_ENGINE
436  // changed by jetsoft
437  // needed for dll to output memory structure
438  if ((dopasses == 0 || dopasses == 2) && (monitor || tessedit_write_unlv))
439  output_pass(page_res_it, target_word_box);
440  // end jetsoft
441  #endif //ndef DISABLED_LEGACY_ENGINE
442 
443  const auto pageseg_mode = static_cast<PageSegMode>(
444  static_cast<int>(tessedit_pageseg_mode));
445  textord_.CleanupSingleRowResult(pageseg_mode, page_res);
446 
447  // Remove empty words, as these mess up the result iterators.
448  for (page_res_it.restart_page(); page_res_it.word() != nullptr;
449  page_res_it.forward()) {
450  const WERD_RES* word = page_res_it.word();
451  const POLY_BLOCK* pb = page_res_it.block()->block != nullptr
452  ? page_res_it.block()->block->pdblk.poly_block()
453  : nullptr;
454  if (word->best_choice == nullptr || word->best_choice->length() == 0 ||
455  (word->best_choice->IsAllSpaces() && (pb == nullptr || pb->IsText()))) {
456  page_res_it.DeleteCurrentWord();
457  }
458  }
459 
460  if (monitor != nullptr) {
461  monitor->progress = 100;
462  }
463  return true;
464 }
465 
466 #ifndef DISABLED_LEGACY_ENGINE
467 
469  PAGE_RES_IT word_it(page_res);
470 
471  WERD_RES *w_prev = nullptr;
472  WERD_RES *w = word_it.word();
473  while (true) {
474  w_prev = w;
475  while (word_it.forward() != nullptr &&
476  (!word_it.word() || word_it.word()->part_of_combo)) {
477  // advance word_it, skipping over parts of combos
478  }
479  if (!word_it.word()) break;
480  w = word_it.word();
481  if (!w || !w_prev || w->uch_set != w_prev->uch_set) {
482  continue;
483  }
484  if (w_prev->word->flag(W_REP_CHAR) || w->word->flag(W_REP_CHAR)) {
485  if (tessedit_bigram_debug) {
486  tprintf("Skipping because one of the words is W_REP_CHAR\n");
487  }
488  continue;
489  }
490  // Two words sharing the same language model, excellent!
491  GenericVector<WERD_CHOICE *> overrides_word1;
492  GenericVector<WERD_CHOICE *> overrides_word2;
493 
494  const STRING orig_w1_str = w_prev->best_choice->unichar_string();
495  const STRING orig_w2_str = w->best_choice->unichar_string();
496  WERD_CHOICE prev_best(w->uch_set);
497  {
498  int w1start, w1end;
499  w_prev->best_choice->GetNonSuperscriptSpan(&w1start, &w1end);
500  prev_best = w_prev->best_choice->shallow_copy(w1start, w1end);
501  }
502  WERD_CHOICE this_best(w->uch_set);
503  {
504  int w2start, w2end;
505  w->best_choice->GetNonSuperscriptSpan(&w2start, &w2end);
506  this_best = w->best_choice->shallow_copy(w2start, w2end);
507  }
508 
509  if (w->tesseract->getDict().valid_bigram(prev_best, this_best)) {
510  if (tessedit_bigram_debug) {
511  tprintf("Top choice \"%s %s\" verified by bigram model.\n",
512  orig_w1_str.string(), orig_w2_str.string());
513  }
514  continue;
515  }
516  if (tessedit_bigram_debug > 2) {
517  tprintf("Examining alt choices for \"%s %s\".\n",
518  orig_w1_str.string(), orig_w2_str.string());
519  }
520  if (tessedit_bigram_debug > 1) {
521  if (!w_prev->best_choices.singleton()) {
522  w_prev->PrintBestChoices();
523  }
524  if (!w->best_choices.singleton()) {
525  w->PrintBestChoices();
526  }
527  }
528  float best_rating = 0.0;
529  int best_idx = 0;
530  WERD_CHOICE_IT prev_it(&w_prev->best_choices);
531  for (prev_it.mark_cycle_pt(); !prev_it.cycled_list(); prev_it.forward()) {
532  WERD_CHOICE *p1 = prev_it.data();
533  WERD_CHOICE strip1(w->uch_set);
534  {
535  int p1start, p1end;
536  p1->GetNonSuperscriptSpan(&p1start, &p1end);
537  strip1 = p1->shallow_copy(p1start, p1end);
538  }
539  WERD_CHOICE_IT w_it(&w->best_choices);
540  for (w_it.mark_cycle_pt(); !w_it.cycled_list(); w_it.forward()) {
541  WERD_CHOICE *p2 = w_it.data();
542  WERD_CHOICE strip2(w->uch_set);
543  {
544  int p2start, p2end;
545  p2->GetNonSuperscriptSpan(&p2start, &p2end);
546  strip2 = p2->shallow_copy(p2start, p2end);
547  }
548  if (w->tesseract->getDict().valid_bigram(strip1, strip2)) {
549  overrides_word1.push_back(p1);
550  overrides_word2.push_back(p2);
551  if (overrides_word1.size() == 1 ||
552  p1->rating() + p2->rating() < best_rating) {
553  best_rating = p1->rating() + p2->rating();
554  best_idx = overrides_word1.size() - 1;
555  }
556  }
557  }
558  }
559  if (!overrides_word1.empty()) {
560  // Excellent, we have some bigram matches.
562  *overrides_word1[best_idx]) &&
564  *overrides_word2[best_idx])) {
565  if (tessedit_bigram_debug > 1) {
566  tprintf("Top choice \"%s %s\" verified (sans case) by bigram "
567  "model.\n", orig_w1_str.string(), orig_w2_str.string());
568  }
569  continue;
570  }
571  const STRING new_w1_str = overrides_word1[best_idx]->unichar_string();
572  const STRING new_w2_str = overrides_word2[best_idx]->unichar_string();
573  if (new_w1_str != orig_w1_str) {
574  w_prev->ReplaceBestChoice(overrides_word1[best_idx]);
575  }
576  if (new_w2_str != orig_w2_str) {
577  w->ReplaceBestChoice(overrides_word2[best_idx]);
578  }
579  if (tessedit_bigram_debug > 0) {
580  STRING choices_description;
581  int num_bigram_choices
582  = overrides_word1.size() * overrides_word2.size();
583  if (num_bigram_choices == 1) {
584  choices_description = "This was the unique bigram choice.";
585  } else {
586  if (tessedit_bigram_debug > 1) {
587  STRING bigrams_list;
588  const int kMaxChoicesToPrint = 20;
589  for (int i = 0; i < overrides_word1.size() &&
590  i < kMaxChoicesToPrint; i++) {
591  if (i > 0) { bigrams_list += ", "; }
592  WERD_CHOICE *p1 = overrides_word1[i];
593  WERD_CHOICE *p2 = overrides_word2[i];
594  bigrams_list += p1->unichar_string() + " " + p2->unichar_string();
595  }
596  choices_description = "There were many choices: {";
597  choices_description += bigrams_list;
598  choices_description += "}";
599  } else {
600  choices_description.add_str_int("There were ", num_bigram_choices);
601  choices_description += " compatible bigrams.";
602  }
603  }
604  tprintf("Replaced \"%s %s\" with \"%s %s\" with bigram model. %s\n",
605  orig_w1_str.string(), orig_w2_str.string(),
606  new_w1_str.string(), new_w2_str.string(),
607  choices_description.string());
608  }
609  }
610  }
611 }
612 
614  ETEXT_DESC* monitor,
615  const TBOX* target_word_box,
616  const char* word_config) {
617  PAGE_RES_IT page_res_it(page_res);
618  // ****************** Pass 5 *******************
619  // Gather statistics on rejects.
620  int word_index = 0;
621  while (!tessedit_test_adaption && page_res_it.word() != nullptr) {
623  WERD_RES* word = page_res_it.word();
624  word_index++;
625  if (monitor != nullptr) {
626  monitor->ocr_alive = true;
627  monitor->progress = 95 + 5 * word_index / stats_.word_count;
628  }
629  if (word->rebuild_word == nullptr) {
630  // Word was not processed by tesseract.
631  page_res_it.forward();
632  continue;
633  }
634  check_debug_pt(word, 70);
635 
636  // changed by jetsoft
637  // specific to its needs to extract one word when need
638  if (target_word_box &&
640  *target_word_box, word_config, 4)) {
641  page_res_it.forward();
642  continue;
643  }
644  // end jetsoft
645 
646  page_res_it.rej_stat_word();
647  const int chars_in_word = word->reject_map.length();
648  const int rejects_in_word = word->reject_map.reject_count();
649 
650  const int blob_quality = word_blob_quality(word, page_res_it.row()->row);
651  stats_.doc_blob_quality += blob_quality;
652  const int outline_errs = word_outline_errs(word);
653  stats_.doc_outline_errs += outline_errs;
654  int16_t all_char_quality;
655  int16_t accepted_all_char_quality;
656  word_char_quality(word, page_res_it.row()->row,
657  &all_char_quality, &accepted_all_char_quality);
658  stats_.doc_char_quality += all_char_quality;
659  const uint8_t permuter_type = word->best_choice->permuter();
660  if ((permuter_type == SYSTEM_DAWG_PERM) ||
661  (permuter_type == FREQ_DAWG_PERM) ||
662  (permuter_type == USER_DAWG_PERM)) {
663  stats_.good_char_count += chars_in_word - rejects_in_word;
664  stats_.doc_good_char_quality += accepted_all_char_quality;
665  }
666  check_debug_pt(word, 80);
668  (blob_quality == 0) && (outline_errs >= chars_in_word))
670  check_debug_pt(word, 90);
671  page_res_it.forward();
672  }
673 
675  tprintf
676  ("QUALITY: num_chs= %d num_rejs= %d %5.3f blob_qual= %d %5.3f"
677  " outline_errs= %d %5.3f char_qual= %d %5.3f good_ch_qual= %d %5.3f\n",
678  page_res->char_count, page_res->rej_count,
679  page_res->rej_count / static_cast<float>(page_res->char_count),
680  stats_.doc_blob_quality,
681  stats_.doc_blob_quality / static_cast<float>(page_res->char_count),
682  stats_.doc_outline_errs,
683  stats_.doc_outline_errs / static_cast<float>(page_res->char_count),
684  stats_.doc_char_quality,
685  stats_.doc_char_quality / static_cast<float>(page_res->char_count),
686  stats_.doc_good_char_quality,
687  (stats_.good_char_count > 0) ?
688  (stats_.doc_good_char_quality /
689  static_cast<float>(stats_.good_char_count)) : 0.0);
690  }
691  bool good_quality_doc =
692  ((page_res->rej_count / static_cast<float>(page_res->char_count)) <=
693  quality_rej_pc) &&
694  (stats_.doc_blob_quality / static_cast<float>(page_res->char_count) >=
695  quality_blob_pc) &&
696  (stats_.doc_outline_errs / static_cast<float>(page_res->char_count) <=
698  (stats_.doc_char_quality / static_cast<float>(page_res->char_count) >=
700 
701  // ****************** Pass 6 *******************
702  // Do whole document or whole block rejection pass
703  if (!tessedit_test_adaption) {
705  quality_based_rejection(page_res_it, good_quality_doc);
706  }
707 }
708 
709 #endif // ndef DISABLED_LEGACY_ENGINE
710 
712  if (!wordrec_run_blamer) return;
713  PAGE_RES_IT page_res_it(page_res);
714  for (page_res_it.restart_page(); page_res_it.word() != nullptr;
715  page_res_it.forward()) {
716  WERD_RES *word = page_res_it.word();
719  }
720  tprintf("Blame reasons:\n");
721  for (int bl = 0; bl < IRR_NUM_REASONS; ++bl) {
723  static_cast<IncorrectResultReason>(bl)),
724  page_res->blame_reasons[bl]);
725  }
726  if (page_res->misadaption_log.length() > 0) {
727  tprintf("Misadaption log:\n");
728  for (int i = 0; i < page_res->misadaption_log.length(); ++i) {
729  tprintf("%s\n", page_res->misadaption_log[i].string());
730  }
731  }
732 }
733 
734 // Sets script positions and detects smallcaps on all output words.
736  PAGE_RES_IT page_res_it(page_res);
737  for (page_res_it.restart_page(); page_res_it.word() != nullptr;
738  page_res_it.forward()) {
739  WERD_RES* word = page_res_it.word();
740  if (word->word->flag(W_REP_CHAR)) {
741  page_res_it.forward();
742  continue;
743  }
744  const float x_height = page_res_it.block()->block->x_height();
745  float word_x_height = word->x_height;
746  if (word_x_height < word->best_choice->min_x_height() ||
747  word_x_height > word->best_choice->max_x_height()) {
748  word_x_height = (word->best_choice->min_x_height() +
749  word->best_choice->max_x_height()) / 2.0f;
750  }
751  // Test for small caps. Word capheight must be close to block xheight,
752  // and word must contain no lower case letters, and at least one upper case.
753  const double small_cap_xheight = x_height * kXHeightCapRatio;
754  const double small_cap_delta = (x_height - small_cap_xheight) / 2.0;
755  if (word->uch_set->script_has_xheight() &&
756  small_cap_xheight - small_cap_delta <= word_x_height &&
757  word_x_height <= small_cap_xheight + small_cap_delta) {
758  // Scan for upper/lower.
759  int num_upper = 0;
760  int num_lower = 0;
761  for (int i = 0; i < word->best_choice->length(); ++i) {
762  if (word->uch_set->get_isupper(word->best_choice->unichar_id(i)))
763  ++num_upper;
764  else if (word->uch_set->get_islower(word->best_choice->unichar_id(i)))
765  ++num_lower;
766  }
767  if (num_upper > 0 && num_lower == 0)
768  word->small_caps = true;
769  }
770  word->SetScriptPositions();
771  }
772 }
773 
774 // Helper finds the gap between the index word and the next.
775 static void WordGap(const PointerVector<WERD_RES>& words, int index, int* right,
776  int* next_left) {
777  *right = -INT32_MAX;
778  *next_left = INT32_MAX;
779  if (index < words.size()) {
780  *right = words[index]->word->bounding_box().right();
781  if (index + 1 < words.size())
782  *next_left = words[index + 1]->word->bounding_box().left();
783  }
784 }
785 
786 // Factored helper computes the rating, certainty, badness and validity of
787 // the permuter of the words in [first_index, end_index).
788 static void EvaluateWordSpan(const PointerVector<WERD_RES>& words,
789  int first_index, int end_index, float* rating,
790  float* certainty, bool* bad,
791  bool* valid_permuter) {
792  if (end_index <= first_index) {
793  *bad = true;
794  *valid_permuter = false;
795  }
796  for (int index = first_index; index < end_index && index < words.size();
797  ++index) {
798  WERD_CHOICE* choice = words[index]->best_choice;
799  if (choice == nullptr) {
800  *bad = true;
801  } else {
802  *rating += choice->rating();
803  *certainty = std::min(*certainty, choice->certainty());
804  if (!Dict::valid_word_permuter(choice->permuter(), false))
805  *valid_permuter = false;
806  }
807  }
808 }
809 
810 // Helper chooses the best combination of words, transferring good ones from
811 // new_words to best_words. To win, a new word must have (better rating and
812 // certainty) or (better permuter status and rating within rating ratio and
813 // certainty within certainty margin) than current best.
814 // All the new_words are consumed (moved to best_words or deleted.)
815 // The return value is the number of new_words used minus the number of
816 // best_words that remain in the output.
817 static int SelectBestWords(double rating_ratio,
818  double certainty_margin,
819  bool debug,
820  PointerVector<WERD_RES>* new_words,
821  PointerVector<WERD_RES>* best_words) {
822  // Process the smallest groups of words that have an overlapping word
823  // boundary at the end.
824  GenericVector<WERD_RES*> out_words;
825  // Index into each word vector (best, new).
826  int b = 0, n = 0;
827  int num_best = 0, num_new = 0;
828  while (b < best_words->size() || n < new_words->size()) {
829  // Start of the current run in each.
830  int start_b = b, start_n = n;
831  while (b < best_words->size() || n < new_words->size()) {
832  int b_right = -INT32_MAX;
833  int next_b_left = INT32_MAX;
834  WordGap(*best_words, b, &b_right, &next_b_left);
835  int n_right = -INT32_MAX;
836  int next_n_left = INT32_MAX;
837  WordGap(*new_words, n, &n_right, &next_n_left);
838  if (std::max(b_right, n_right) < std::min(next_b_left, next_n_left)) {
839  // The word breaks overlap. [start_b,b] and [start_n, n] match.
840  break;
841  }
842  // Keep searching for the matching word break.
843  if ((b_right < n_right && b < best_words->size()) ||
844  n == new_words->size())
845  ++b;
846  else
847  ++n;
848  }
849  // Rating of the current run in each.
850  float b_rating = 0.0f, n_rating = 0.0f;
851  // Certainty of the current run in each.
852  float b_certainty = 0.0f, n_certainty = 0.0f;
853  // True if any word is missing its best choice.
854  bool b_bad = false, n_bad = false;
855  // True if all words have a valid permuter.
856  bool b_valid_permuter = true, n_valid_permuter = true;
857  const int end_b = b < best_words->size() ? b + 1 : b;
858  const int end_n = n < new_words->size() ? n + 1 : n;
859  EvaluateWordSpan(*best_words, start_b, end_b, &b_rating, &b_certainty,
860  &b_bad, &b_valid_permuter);
861  EvaluateWordSpan(*new_words, start_n, end_n, &n_rating, &n_certainty,
862  &n_bad, &n_valid_permuter);
863  bool new_better = false;
864  if (!n_bad && (b_bad || (n_certainty > b_certainty &&
865  n_rating < b_rating) ||
866  (!b_valid_permuter && n_valid_permuter &&
867  n_rating < b_rating * rating_ratio &&
868  n_certainty > b_certainty - certainty_margin))) {
869  // New is better.
870  for (int i = start_n; i < end_n; ++i) {
871  out_words.push_back((*new_words)[i]);
872  (*new_words)[i] = nullptr;
873  ++num_new;
874  }
875  new_better = true;
876  } else if (!b_bad) {
877  // Current best is better.
878  for (int i = start_b; i < end_b; ++i) {
879  out_words.push_back((*best_words)[i]);
880  (*best_words)[i] = nullptr;
881  ++num_best;
882  }
883  }
884  if (debug) {
885  tprintf("%d new words %s than %d old words: r: %g v %g c: %g v %g"
886  " valid dict: %d v %d\n",
887  end_n - start_n, new_better ? "better" : "worse",
888  end_b - start_b, n_rating, b_rating,
889  n_certainty, b_certainty, n_valid_permuter, b_valid_permuter);
890  }
891  // Move on to the next group.
892  b = end_b;
893  n = end_n;
894  }
895  // Transfer from out_words to best_words.
896  best_words->clear();
897  for (int i = 0; i < out_words.size(); ++i)
898  best_words->push_back(out_words[i]);
899  return num_new - num_best;
900 }
901 
902 // Helper to recognize the word using the given (language-specific) tesseract.
903 // Returns positive if this recognizer found more new best words than the
904 // number kept from best_words.
906  WordRecognizer recognizer, bool debug,
907  WERD_RES** in_word,
908  PointerVector<WERD_RES>* best_words) {
909  if (debug) {
910  tprintf("Trying word using lang %s, oem %d\n",
911  lang.string(), static_cast<int>(tessedit_ocr_engine_mode));
912  }
913  // Run the recognizer on the word.
914  PointerVector<WERD_RES> new_words;
915  (this->*recognizer)(word_data, in_word, &new_words);
916  if (new_words.empty()) {
917  // Transfer input word to new_words, as the classifier must have put
918  // the result back in the input.
919  new_words.push_back(*in_word);
920  *in_word = nullptr;
921  }
922  if (debug) {
923  for (int i = 0; i < new_words.size(); ++i)
924  new_words[i]->DebugTopChoice("Lang result");
925  }
926  // Initial version is a bit of a hack based on better certainty and rating
927  // or a dictionary vs non-dictionary word.
928  return SelectBestWords(classify_max_rating_ratio,
930  debug, &new_words, best_words);
931 }
932 
933 // Helper returns true if all the words are acceptable.
934 static bool WordsAcceptable(const PointerVector<WERD_RES>& words) {
935  for (int w = 0; w < words.size(); ++w) {
936  if (words[w]->tess_failed || !words[w]->tess_accepted) return false;
937  }
938  return true;
939 }
940 
941 // Moves good-looking "noise"/diacritics from the reject list to the main
942 // blob list on the current word. Returns true if anything was done, and
943 // sets make_next_word_fuzzy if blob(s) were added to the end of the word.
945  bool* make_next_word_fuzzy) {
946 #ifdef DISABLED_LEGACY_ENGINE
947  return false;
948 #else
949  *make_next_word_fuzzy = false;
950  WERD* real_word = pr_it->word()->word;
951  if (real_word->rej_cblob_list()->empty() ||
952  real_word->cblob_list()->empty() ||
953  real_word->rej_cblob_list()->length() > noise_maxperword)
954  return false;
955  real_word->rej_cblob_list()->sort(&C_BLOB::SortByXMiddle);
956  // Get the noise outlines into a vector with matching bool map.
957  GenericVector<C_OUTLINE*> outlines;
958  real_word->GetNoiseOutlines(&outlines);
959  GenericVector<bool> word_wanted;
960  GenericVector<bool> overlapped_any_blob;
961  GenericVector<C_BLOB*> target_blobs;
962  AssignDiacriticsToOverlappingBlobs(outlines, pass, real_word, pr_it,
963  &word_wanted, &overlapped_any_blob,
964  &target_blobs);
965  // Filter the outlines that overlapped any blob and put them into the word
966  // now. This simplifies the remaining task and also makes it more accurate
967  // as it has more completed blobs to work on.
968  GenericVector<bool> wanted;
969  GenericVector<C_BLOB*> wanted_blobs;
970  GenericVector<C_OUTLINE*> wanted_outlines;
971  int num_overlapped = 0;
972  int num_overlapped_used = 0;
973  for (int i = 0; i < overlapped_any_blob.size(); ++i) {
974  if (overlapped_any_blob[i]) {
975  ++num_overlapped;
976  if (word_wanted[i]) ++num_overlapped_used;
977  wanted.push_back(word_wanted[i]);
978  wanted_blobs.push_back(target_blobs[i]);
979  wanted_outlines.push_back(outlines[i]);
980  outlines[i] = nullptr;
981  }
982  }
983  real_word->AddSelectedOutlines(wanted, wanted_blobs, wanted_outlines, nullptr);
984  AssignDiacriticsToNewBlobs(outlines, pass, real_word, pr_it, &word_wanted,
985  &target_blobs);
986  int non_overlapped = 0;
987  int non_overlapped_used = 0;
988  for (int i = 0; i < word_wanted.size(); ++i) {
989  if (word_wanted[i]) ++non_overlapped_used;
990  if (outlines[i] != nullptr) ++non_overlapped_used;
991  }
992  if (debug_noise_removal) {
993  tprintf("Used %d/%d overlapped %d/%d non-overlaped diacritics on word:",
994  num_overlapped_used, num_overlapped, non_overlapped_used,
995  non_overlapped);
996  real_word->bounding_box().print();
997  }
998  // Now we have decided which outlines we want, put them into the real_word.
999  if (real_word->AddSelectedOutlines(word_wanted, target_blobs, outlines,
1000  make_next_word_fuzzy)) {
1001  pr_it->MakeCurrentWordFuzzy();
1002  }
1003  // TODO(rays) Parts of combos have a deep copy of the real word, and need
1004  // to have their noise outlines moved/assigned in the same way!!
1005  return num_overlapped_used != 0 || non_overlapped_used != 0;
1006 #endif // ndef DISABLED_LEGACY_ENGINE
1007 }
1008 
1009 // Attempts to put noise/diacritic outlines into the blobs that they overlap.
1010 // Input: a set of noisy outlines that probably belong to the real_word.
1011 // Output: word_wanted indicates which outlines are to be assigned to a blob,
1012 // target_blobs indicates which to assign to, and overlapped_any_blob is
1013 // true for all outlines that overlapped a blob.
1015  const GenericVector<C_OUTLINE*>& outlines, int pass, WERD* real_word,
1016  PAGE_RES_IT* pr_it, GenericVector<bool>* word_wanted,
1017  GenericVector<bool>* overlapped_any_blob,
1018  GenericVector<C_BLOB*>* target_blobs) {
1019 #ifndef DISABLED_LEGACY_ENGINE
1020  GenericVector<bool> blob_wanted;
1021  word_wanted->init_to_size(outlines.size(), false);
1022  overlapped_any_blob->init_to_size(outlines.size(), false);
1023  target_blobs->init_to_size(outlines.size(), nullptr);
1024  // For each real blob, find the outlines that seriously overlap it.
1025  // A single blob could be several merged characters, so there can be quite
1026  // a few outlines overlapping, and the full engine needs to be used to chop
1027  // and join to get a sensible result.
1028  C_BLOB_IT blob_it(real_word->cblob_list());
1029  for (blob_it.mark_cycle_pt(); !blob_it.cycled_list(); blob_it.forward()) {
1030  C_BLOB* blob = blob_it.data();
1031  const TBOX blob_box = blob->bounding_box();
1032  blob_wanted.init_to_size(outlines.size(), false);
1033  int num_blob_outlines = 0;
1034  for (int i = 0; i < outlines.size(); ++i) {
1035  if (blob_box.major_x_overlap(outlines[i]->bounding_box()) &&
1036  !(*word_wanted)[i]) {
1037  blob_wanted[i] = true;
1038  (*overlapped_any_blob)[i] = true;
1039  ++num_blob_outlines;
1040  }
1041  }
1042  if (debug_noise_removal) {
1043  tprintf("%d noise outlines overlap blob at:", num_blob_outlines);
1044  blob_box.print();
1045  }
1046  // If any outlines overlap the blob, and not too many, classify the blob
1047  // (using the full engine, languages and all), and choose the maximal
1048  // combination of outlines that doesn't hurt the end-result classification
1049  // by too much. Mark them as wanted.
1050  if (0 < num_blob_outlines && num_blob_outlines < noise_maxperblob) {
1051  if (SelectGoodDiacriticOutlines(pass, noise_cert_basechar, pr_it, blob,
1052  outlines, num_blob_outlines,
1053  &blob_wanted)) {
1054  for (int i = 0; i < blob_wanted.size(); ++i) {
1055  if (blob_wanted[i]) {
1056  // Claim the outline and record where it is going.
1057  (*word_wanted)[i] = true;
1058  (*target_blobs)[i] = blob;
1059  }
1060  }
1061  }
1062  }
1063  }
1064 #endif // ndef DISABLED_LEGACY_ENGINE
1065 }
1066 
1067 // Attempts to assign non-overlapping outlines to their nearest blobs or
1068 // make new blobs out of them.
1070  const GenericVector<C_OUTLINE*>& outlines, int pass, WERD* real_word,
1071  PAGE_RES_IT* pr_it, GenericVector<bool>* word_wanted,
1072  GenericVector<C_BLOB*>* target_blobs) {
1073 #ifndef DISABLED_LEGACY_ENGINE
1074  GenericVector<bool> blob_wanted;
1075  word_wanted->init_to_size(outlines.size(), false);
1076  target_blobs->init_to_size(outlines.size(), nullptr);
1077  // Check for outlines that need to be turned into stand-alone blobs.
1078  for (int i = 0; i < outlines.size(); ++i) {
1079  if (outlines[i] == nullptr) continue;
1080  // Get a set of adjacent outlines that don't overlap any existing blob.
1081  blob_wanted.init_to_size(outlines.size(), false);
1082  int num_blob_outlines = 0;
1083  TBOX total_ol_box(outlines[i]->bounding_box());
1084  while (i < outlines.size() && outlines[i] != nullptr) {
1085  blob_wanted[i] = true;
1086  total_ol_box += outlines[i]->bounding_box();
1087  ++i;
1088  ++num_blob_outlines;
1089  }
1090  // Find the insertion point.
1091  C_BLOB_IT blob_it(real_word->cblob_list());
1092  while (!blob_it.at_last() &&
1093  blob_it.data_relative(1)->bounding_box().left() <=
1094  total_ol_box.left()) {
1095  blob_it.forward();
1096  }
1097  // Choose which combination of them we actually want and where to put
1098  // them.
1099  if (debug_noise_removal)
1100  tprintf("Num blobless outlines = %d\n", num_blob_outlines);
1101  C_BLOB* left_blob = blob_it.data();
1102  TBOX left_box = left_blob->bounding_box();
1103  C_BLOB* right_blob = blob_it.at_last() ? nullptr : blob_it.data_relative(1);
1104  if ((left_box.x_overlap(total_ol_box) || right_blob == nullptr ||
1105  !right_blob->bounding_box().x_overlap(total_ol_box)) &&
1106  SelectGoodDiacriticOutlines(pass, noise_cert_disjoint, pr_it, left_blob,
1107  outlines, num_blob_outlines,
1108  &blob_wanted)) {
1109  if (debug_noise_removal) tprintf("Added to left blob\n");
1110  for (int j = 0; j < blob_wanted.size(); ++j) {
1111  if (blob_wanted[j]) {
1112  (*word_wanted)[j] = true;
1113  (*target_blobs)[j] = left_blob;
1114  }
1115  }
1116  } else if (right_blob != nullptr &&
1117  (!left_box.x_overlap(total_ol_box) ||
1118  right_blob->bounding_box().x_overlap(total_ol_box)) &&
1120  right_blob, outlines,
1121  num_blob_outlines, &blob_wanted)) {
1122  if (debug_noise_removal) tprintf("Added to right blob\n");
1123  for (int j = 0; j < blob_wanted.size(); ++j) {
1124  if (blob_wanted[j]) {
1125  (*word_wanted)[j] = true;
1126  (*target_blobs)[j] = right_blob;
1127  }
1128  }
1129  } else if (SelectGoodDiacriticOutlines(pass, noise_cert_punc, pr_it, nullptr,
1130  outlines, num_blob_outlines,
1131  &blob_wanted)) {
1132  if (debug_noise_removal) tprintf("Fitted between blobs\n");
1133  for (int j = 0; j < blob_wanted.size(); ++j) {
1134  if (blob_wanted[j]) {
1135  (*word_wanted)[j] = true;
1136  (*target_blobs)[j] = nullptr;
1137  }
1138  }
1139  }
1140  }
1141 #endif // ndef DISABLED_LEGACY_ENGINE
1142 }
1143 
1144 // Starting with ok_outlines set to indicate which outlines overlap the blob,
1145 // chooses the optimal set (approximately) and returns true if any outlines
1146 // are desired, in which case ok_outlines indicates which ones.
1148  int pass, float certainty_threshold, PAGE_RES_IT* pr_it, C_BLOB* blob,
1149  const GenericVector<C_OUTLINE*>& outlines, int num_outlines,
1150  GenericVector<bool>* ok_outlines) {
1151 #ifndef DISABLED_LEGACY_ENGINE
1152  STRING best_str;
1153  float target_cert = certainty_threshold;
1154  if (blob != nullptr) {
1155  float target_c2;
1156  target_cert = ClassifyBlobAsWord(pass, pr_it, blob, &best_str, &target_c2);
1157  if (debug_noise_removal) {
1158  tprintf("No Noise blob classified as %s=%g(%g) at:", best_str.string(),
1159  target_cert, target_c2);
1160  blob->bounding_box().print();
1161  }
1162  target_cert -= (target_cert - certainty_threshold) * noise_cert_factor;
1163  }
1164  GenericVector<bool> test_outlines = *ok_outlines;
1165  // Start with all the outlines in.
1166  STRING all_str;
1167  GenericVector<bool> best_outlines = *ok_outlines;
1168  float best_cert = ClassifyBlobPlusOutlines(test_outlines, outlines, pass,
1169  pr_it, blob, &all_str);
1170  if (debug_noise_removal) {
1171  TBOX ol_box;
1172  for (int i = 0; i < test_outlines.size(); ++i) {
1173  if (test_outlines[i]) ol_box += outlines[i]->bounding_box();
1174  }
1175  tprintf("All Noise blob classified as %s=%g, delta=%g at:",
1176  all_str.string(), best_cert, best_cert - target_cert);
1177  ol_box.print();
1178  }
1179  // Iteratively zero out the bit that improves the certainty the most, until
1180  // we get past the threshold, have zero bits, or fail to improve.
1181  int best_index = 0; // To zero out.
1182  while (num_outlines > 1 && best_index >= 0 &&
1183  (blob == nullptr || best_cert < target_cert || blob != nullptr)) {
1184  // Find the best bit to zero out.
1185  best_index = -1;
1186  for (int i = 0; i < outlines.size(); ++i) {
1187  if (test_outlines[i]) {
1188  test_outlines[i] = false;
1189  STRING str;
1190  float cert = ClassifyBlobPlusOutlines(test_outlines, outlines, pass,
1191  pr_it, blob, &str);
1192  if (debug_noise_removal) {
1193  TBOX ol_box;
1194  for (int j = 0; j < outlines.size(); ++j) {
1195  if (test_outlines[j]) ol_box += outlines[j]->bounding_box();
1196  tprintf("%d", test_outlines[j]);
1197  }
1198  tprintf(" blob classified as %s=%g, delta=%g) at:", str.string(),
1199  cert, cert - target_cert);
1200  ol_box.print();
1201  }
1202  if (cert > best_cert) {
1203  best_cert = cert;
1204  best_index = i;
1205  best_outlines = test_outlines;
1206  }
1207  test_outlines[i] = true;
1208  }
1209  }
1210  if (best_index >= 0) {
1211  test_outlines[best_index] = false;
1212  --num_outlines;
1213  }
1214  }
1215  if (best_cert >= target_cert) {
1216  // Save the best combination.
1217  *ok_outlines = best_outlines;
1218  if (debug_noise_removal) {
1219  tprintf("%s noise combination ", blob ? "Adding" : "New");
1220  for (int i = 0; i < best_outlines.size(); ++i) {
1221  tprintf("%d", best_outlines[i]);
1222  }
1223  tprintf(" yields certainty %g, beating target of %g\n", best_cert,
1224  target_cert);
1225  }
1226  return true;
1227  }
1228 #endif // ndef DISABLED_LEGACY_ENGINE
1229  return false;
1230 }
1231 
1232 // Classifies the given blob plus the outlines flagged by ok_outlines, undoes
1233 // the inclusion of the outlines, and returns the certainty of the raw choice.
1235  const GenericVector<bool>& ok_outlines,
1236  const GenericVector<C_OUTLINE*>& outlines, int pass_n, PAGE_RES_IT* pr_it,
1237  C_BLOB* blob, STRING* best_str) {
1238 #ifndef DISABLED_LEGACY_ENGINE
1239  C_OUTLINE_IT ol_it;
1240  C_OUTLINE* first_to_keep = nullptr;
1241  C_BLOB* local_blob = nullptr;
1242  if (blob != nullptr) {
1243  // Add the required outlines to the blob.
1244  ol_it.set_to_list(blob->out_list());
1245  first_to_keep = ol_it.data();
1246  }
1247  for (int i = 0; i < ok_outlines.size(); ++i) {
1248  if (ok_outlines[i]) {
1249  // This outline is to be added.
1250  if (blob == nullptr) {
1251  local_blob = new C_BLOB(outlines[i]);
1252  blob = local_blob;
1253  ol_it.set_to_list(blob->out_list());
1254  } else {
1255  ol_it.add_before_stay_put(outlines[i]);
1256  }
1257  }
1258  }
1259  float c2;
1260  float cert = ClassifyBlobAsWord(pass_n, pr_it, blob, best_str, &c2);
1261  ol_it.move_to_first();
1262  if (first_to_keep == nullptr) {
1263  // We created blob. Empty its outlines and delete it.
1264  for (; !ol_it.empty(); ol_it.forward()) ol_it.extract();
1265  delete local_blob;
1266  cert = -c2;
1267  } else {
1268  // Remove the outlines that we put in.
1269  for (; ol_it.data() != first_to_keep; ol_it.forward()) {
1270  ol_it.extract();
1271  }
1272  }
1273  return cert;
1274 #else
1275  return 0.1;
1276 #endif // ndef DISABLED_LEGACY_ENGINE
1277 }
1278 
1279 // Classifies the given blob (part of word_data->word->word) as an individual
1280 // word, using languages, chopper etc, returning only the certainty of the
1281 // best raw choice, and undoing all the work done to fake out the word.
1283  C_BLOB* blob, STRING* best_str, float* c2) {
1284 #ifndef DISABLED_LEGACY_ENGINE
1285  WERD* real_word = pr_it->word()->word;
1286  WERD* word = real_word->ConstructFromSingleBlob(
1287  real_word->flag(W_BOL), real_word->flag(W_EOL), C_BLOB::deep_copy(blob));
1288  WERD_RES* word_res = pr_it->InsertSimpleCloneWord(*pr_it->word(), word);
1289  // Get a new iterator that points to the new word.
1290  PAGE_RES_IT it(pr_it->page_res);
1291  while (it.word() != word_res && it.word() != nullptr) it.forward();
1292  ASSERT_HOST(it.word() == word_res);
1293  WordData wd(it);
1294  // Force full initialization.
1295  SetupWordPassN(1, &wd);
1296  classify_word_and_language(pass_n, &it, &wd);
1297  if (debug_noise_removal) {
1298  if (wd.word->raw_choice != nullptr) {
1299  tprintf("word xheight=%g, row=%g, range=[%g,%g]\n", word_res->x_height,
1300  wd.row->x_height(), wd.word->raw_choice->min_x_height(),
1301  wd.word->raw_choice->max_x_height());
1302  } else {
1303  tprintf("Got word with null raw choice xheight=%g, row=%g\n", word_res->x_height,
1304  wd.row->x_height());
1305  }
1306  }
1307  float cert = 0.0f;
1308  if (wd.word->raw_choice != nullptr) { // This probably shouldn't happen, but...
1309  cert = wd.word->raw_choice->certainty();
1310  float rat = wd.word->raw_choice->rating();
1311  *c2 = rat > 0.0f ? cert * cert / rat : 0.0f;
1312  *best_str = wd.word->raw_choice->unichar_string();
1313  } else {
1314  *c2 = 0.0f;
1315  *best_str = "";
1316  }
1317  it.DeleteCurrentWord();
1318  pr_it->ResetWordIterator();
1319  return cert;
1320 #else
1321  return 0.1;
1322 #endif // ndef DISABLED_LEGACY_ENGINE
1323 }
1324 
1325 // Generic function for classifying a word. Can be used either for pass1 or
1326 // pass2 according to the function passed to recognizer.
1327 // word_data holds the word to be recognized, and its block and row, and
1328 // pr_it points to the word as well, in case we are running LSTM and it wants
1329 // to output multiple words.
1330 // Recognizes in the current language, and if successful that is all.
1331 // If recognition was not successful, tries all available languages until
1332 // it gets a successful result or runs out of languages. Keeps the best result.
1334  WordData* word_data) {
1335 #ifdef DISABLED_LEGACY_ENGINE
1337 #else
1338  WordRecognizer recognizer = pass_n == 1 ? &Tesseract::classify_word_pass1
1340 #endif // def DISABLED_LEGACY_ENGINE
1341 
1342  // Best result so far.
1343  PointerVector<WERD_RES> best_words;
1344  // Points to the best result. May be word or in lang_words.
1345  const WERD_RES* word = word_data->word;
1346  clock_t start_t = clock();
1347  const bool debug = classify_debug_level > 0 || multilang_debug_level > 0;
1348  if (debug) {
1349  tprintf("%s word with lang %s at:",
1350  word->done ? "Already done" : "Processing",
1351  most_recently_used_->lang.string());
1352  word->word->bounding_box().print();
1353  }
1354  if (word->done) {
1355  // If done on pass1, leave it as-is.
1356  if (!word->tess_failed)
1357  most_recently_used_ = word->tesseract;
1358  return;
1359  }
1360  int sub = sub_langs_.size();
1361  if (most_recently_used_ != this) {
1362  // Get the index of the most_recently_used_.
1363  for (sub = 0; sub < sub_langs_.size() &&
1364  most_recently_used_ != sub_langs_[sub]; ++sub) {}
1365  }
1366  most_recently_used_->RetryWithLanguage(
1367  *word_data, recognizer, debug, &word_data->lang_words[sub], &best_words);
1368  Tesseract* best_lang_tess = most_recently_used_;
1369  if (!WordsAcceptable(best_words)) {
1370  // Try all the other languages to see if they are any better.
1371  if (most_recently_used_ != this &&
1372  this->RetryWithLanguage(*word_data, recognizer, debug,
1373  &word_data->lang_words[sub_langs_.size()],
1374  &best_words) > 0) {
1375  best_lang_tess = this;
1376  }
1377  for (int i = 0; !WordsAcceptable(best_words) && i < sub_langs_.size();
1378  ++i) {
1379  if (most_recently_used_ != sub_langs_[i] &&
1380  sub_langs_[i]->RetryWithLanguage(*word_data, recognizer, debug,
1381  &word_data->lang_words[i],
1382  &best_words) > 0) {
1383  best_lang_tess = sub_langs_[i];
1384  }
1385  }
1386  }
1387  most_recently_used_ = best_lang_tess;
1388  if (!best_words.empty()) {
1389  if (best_words.size() == 1 && !best_words[0]->combination) {
1390  // Move the best single result to the main word.
1391  word_data->word->ConsumeWordResults(best_words[0]);
1392  } else {
1393  // Words came from LSTM, and must be moved to the PAGE_RES properly.
1394  word_data->word = best_words.back();
1395  pr_it->ReplaceCurrentWord(&best_words);
1396  }
1397  ASSERT_HOST(word_data->word->box_word != nullptr);
1398  } else {
1399  tprintf("no best words!!\n");
1400  }
1401  clock_t ocr_t = clock();
1402  if (tessedit_timing_debug) {
1403  tprintf("%s (ocr took %.2f sec)\n",
1404  word_data->word->best_choice->unichar_string().string(),
1405  static_cast<double>(ocr_t-start_t)/CLOCKS_PER_SEC);
1406  }
1407 }
1408 
1416  WERD_RES** in_word,
1417  PointerVector<WERD_RES>* out_words) {
1418  ROW* row = word_data.row;
1419  BLOCK* block = word_data.block;
1420  prev_word_best_choice_ = word_data.prev_word != nullptr
1421  ? word_data.prev_word->word->best_choice : nullptr;
1422 #ifndef ANDROID_BUILD
1423 #ifdef DISABLED_LEGACY_ENGINE
1425 #else
1428 #endif // def DISABLED_LEGACY_ENGINE
1429  if (!(*in_word)->odd_size || tessedit_ocr_engine_mode == OEM_LSTM_ONLY) {
1430  LSTMRecognizeWord(*block, row, *in_word, out_words);
1431  if (!out_words->empty())
1432  return; // Successful lstm recognition.
1433  }
1435  // No fallback allowed, so use a fake.
1436  (*in_word)->SetupFake(lstm_recognizer_->GetUnicharset());
1437  return;
1438  }
1439 
1440  #ifndef DISABLED_LEGACY_ENGINE
1441  // Fall back to tesseract for failed words or odd words.
1442  (*in_word)->SetupForRecognition(unicharset, this, BestPix(),
1443  OEM_TESSERACT_ONLY, nullptr,
1446  poly_allow_detailed_fx, row, block);
1447 #endif // ndef DISABLED_LEGACY_ENGINE
1448  }
1449 #endif // ndef ANDROID_BUILD
1450 
1451 #ifndef DISABLED_LEGACY_ENGINE
1452  WERD_RES* word = *in_word;
1453  match_word_pass_n(1, word, row, block);
1454  if (!word->tess_failed && !word->word->flag(W_REP_CHAR)) {
1455  word->tess_would_adapt = AdaptableWord(word);
1456  bool adapt_ok = word_adaptable(word, tessedit_tess_adaption_mode);
1457 
1458  if (adapt_ok) {
1459  // Send word to adaptive classifier for training.
1460  word->BestChoiceToCorrectText();
1461  LearnWord(nullptr, word);
1462  // Mark misadaptions if running blamer.
1463  if (word->blamer_bundle != nullptr) {
1466  }
1467  }
1468 
1469  if (tessedit_enable_doc_dict && !word->IsAmbiguous())
1471  }
1472 #endif // ndef DISABLED_LEGACY_ENGINE
1473 }
1474 
1475 // Helper to report the result of the xheight fix.
1476 void Tesseract::ReportXhtFixResult(bool accept_new_word, float new_x_ht,
1477  WERD_RES* word, WERD_RES* new_word) {
1478  tprintf("New XHT Match:%s = %s ",
1479  word->best_choice->unichar_string().string(),
1480  word->best_choice->debug_string().string());
1481  word->reject_map.print(debug_fp);
1482  tprintf(" -> %s = %s ",
1483  new_word->best_choice->unichar_string().string(),
1484  new_word->best_choice->debug_string().string());
1485  new_word->reject_map.print(debug_fp);
1486  tprintf(" %s->%s %s %s\n",
1487  word->guessed_x_ht ? "GUESS" : "CERT",
1488  new_word->guessed_x_ht ? "GUESS" : "CERT",
1489  new_x_ht > 0.1 ? "STILL DOUBT" : "OK",
1490  accept_new_word ? "ACCEPTED" : "");
1491 }
1492 
1493 #ifndef DISABLED_LEGACY_ENGINE
1494 
1495 // Run the x-height fix-up, based on min/max top/bottom information in
1496 // unicharset.
1497 // Returns true if the word was changed.
1498 // See the comment in fixxht.cpp for a description of the overall process.
1499 bool Tesseract::TrainedXheightFix(WERD_RES *word, BLOCK* block, ROW *row) {
1500  int original_misfits = CountMisfitTops(word);
1501  if (original_misfits == 0)
1502  return false;
1503  float baseline_shift = 0.0f;
1504  float new_x_ht = ComputeCompatibleXheight(word, &baseline_shift);
1505  if (baseline_shift != 0.0f) {
1506  // Try the shift on its own first.
1507  if (!TestNewNormalization(original_misfits, baseline_shift, word->x_height,
1508  word, block, row))
1509  return false;
1510  original_misfits = CountMisfitTops(word);
1511  if (original_misfits > 0) {
1512  float new_baseline_shift;
1513  // Now recompute the new x_height.
1514  new_x_ht = ComputeCompatibleXheight(word, &new_baseline_shift);
1515  if (new_x_ht >= kMinRefitXHeightFraction * word->x_height) {
1516  // No test of return value here, as we are definitely making a change
1517  // to the word by shifting the baseline.
1518  TestNewNormalization(original_misfits, baseline_shift, new_x_ht,
1519  word, block, row);
1520  }
1521  }
1522  return true;
1523  } else if (new_x_ht >= kMinRefitXHeightFraction * word->x_height) {
1524  return TestNewNormalization(original_misfits, 0.0f, new_x_ht,
1525  word, block, row);
1526  } else {
1527  return false;
1528  }
1529 }
1530 
1531 // Runs recognition with the test baseline shift and x-height and returns true
1532 // if there was an improvement in recognition result.
1533 bool Tesseract::TestNewNormalization(int original_misfits,
1534  float baseline_shift, float new_x_ht,
1535  WERD_RES *word, BLOCK* block, ROW *row) {
1536  bool accept_new_x_ht = false;
1537  WERD_RES new_x_ht_word(word->word);
1538  if (word->blamer_bundle != nullptr) {
1539  new_x_ht_word.blamer_bundle = new BlamerBundle();
1540  new_x_ht_word.blamer_bundle->CopyTruth(*(word->blamer_bundle));
1541  }
1542  new_x_ht_word.x_height = new_x_ht;
1543  new_x_ht_word.baseline_shift = baseline_shift;
1544  new_x_ht_word.caps_height = 0.0;
1545  new_x_ht_word.SetupForRecognition(
1546  unicharset, this, BestPix(), tessedit_ocr_engine_mode, nullptr,
1548  poly_allow_detailed_fx, row, block);
1549  match_word_pass_n(2, &new_x_ht_word, row, block);
1550  if (!new_x_ht_word.tess_failed) {
1551  int new_misfits = CountMisfitTops(&new_x_ht_word);
1552  if (debug_x_ht_level >= 1) {
1553  tprintf("Old misfits=%d with x-height %f, new=%d with x-height %f\n",
1554  original_misfits, word->x_height,
1555  new_misfits, new_x_ht);
1556  tprintf("Old rating= %f, certainty=%f, new=%f, %f\n",
1557  word->best_choice->rating(), word->best_choice->certainty(),
1558  new_x_ht_word.best_choice->rating(),
1559  new_x_ht_word.best_choice->certainty());
1560  }
1561  // The misfits must improve and either the rating or certainty.
1562  accept_new_x_ht = new_misfits < original_misfits &&
1563  (new_x_ht_word.best_choice->certainty() >
1564  word->best_choice->certainty() ||
1565  new_x_ht_word.best_choice->rating() <
1566  word->best_choice->rating());
1567  if (debug_x_ht_level >= 1) {
1568  ReportXhtFixResult(accept_new_x_ht, new_x_ht, word, &new_x_ht_word);
1569  }
1570  }
1571  if (accept_new_x_ht) {
1572  word->ConsumeWordResults(&new_x_ht_word);
1573  return true;
1574  }
1575  return false;
1576 }
1577 
1578 #endif // ndef DISABLED_LEGACY_ENGINE
1579 
1587  WERD_RES** in_word,
1588  PointerVector<WERD_RES>* out_words) {
1589  // Return if we do not want to run Tesseract.
1591  return;
1592  }
1593 #ifndef DISABLED_LEGACY_ENGINE
1594  ROW* row = word_data.row;
1595  BLOCK* block = word_data.block;
1596  WERD_RES* word = *in_word;
1597  prev_word_best_choice_ = word_data.prev_word != nullptr
1598  ? word_data.prev_word->word->best_choice : nullptr;
1599 
1601  check_debug_pt(word, 30);
1602  if (!word->done) {
1603  word->caps_height = 0.0;
1604  if (word->x_height == 0.0f)
1605  word->x_height = row->x_height();
1606  match_word_pass_n(2, word, row, block);
1607  check_debug_pt(word, 40);
1608  }
1609 
1610  SubAndSuperscriptFix(word);
1611 
1612  if (!word->tess_failed && !word->word->flag(W_REP_CHAR)) {
1614  block->classify_rotation().y() == 0.0f) {
1615  // Use the tops and bottoms since they are available.
1616  TrainedXheightFix(word, block, row);
1617  }
1618 
1620  }
1621 #ifndef GRAPHICS_DISABLED
1623  if (fx_win == nullptr)
1624  create_fx_win();
1625  clear_fx_win();
1626  word->rebuild_word->plot(fx_win);
1627  TBOX wbox = word->rebuild_word->bounding_box();
1628  fx_win->ZoomToRectangle(wbox.left(), wbox.top(),
1629  wbox.right(), wbox.bottom());
1631  }
1632 #endif
1634  check_debug_pt(word, 50);
1635 #endif // ndef DISABLED_LEGACY_ENGINE
1636 }
1637 
1638 #ifndef DISABLED_LEGACY_ENGINE
1639 
1645  ROW *row, BLOCK* block) {
1646  if (word->tess_failed) return;
1647  tess_segment_pass_n(pass_n, word);
1648 
1649  if (!word->tess_failed) {
1650  if (!word->word->flag (W_REP_CHAR)) {
1651  word->fix_quotes();
1653  word->fix_hyphens();
1654  /* Don't trust fix_quotes! - though I think I've fixed the bug */
1655  if (word->best_choice->length() != word->box_word->length()) {
1656  tprintf("POST FIX_QUOTES FAIL String:\"%s\"; Strlen=%d;"
1657  " #Blobs=%d\n",
1658  word->best_choice->debug_string().string(),
1659  word->best_choice->length(),
1660  word->box_word->length());
1661 
1662  }
1663  word->tess_accepted = tess_acceptable_word(word);
1664 
1665  // Also sets word->done flag
1666  make_reject_map(word, row, pass_n);
1667  }
1668  }
1669  set_word_fonts(word);
1670 
1671  ASSERT_HOST(word->raw_choice != nullptr);
1672 }
1673 #endif // ndef DISABLED_LEGACY_ENGINE
1674 
1675 // Helper to return the best rated BLOB_CHOICE in the whole word that matches
1676 // the given char_id, or nullptr if none can be found.
1677 static BLOB_CHOICE* FindBestMatchingChoice(UNICHAR_ID char_id,
1678  WERD_RES* word_res) {
1679  // Find the corresponding best BLOB_CHOICE from any position in the word_res.
1680  BLOB_CHOICE* best_choice = nullptr;
1681  for (int i = 0; i < word_res->best_choice->length(); ++i) {
1682  BLOB_CHOICE* choice = FindMatchingChoice(char_id,
1683  word_res->GetBlobChoices(i));
1684  if (choice != nullptr) {
1685  if (best_choice == nullptr || choice->rating() < best_choice->rating())
1686  best_choice = choice;
1687  }
1688  }
1689  return best_choice;
1690 }
1691 
1692 // Helper to insert blob_choice in each location in the leader word if there is
1693 // no matching BLOB_CHOICE there already, and correct any incorrect results
1694 // in the best_choice.
1695 static void CorrectRepcharChoices(BLOB_CHOICE* blob_choice,
1696  WERD_RES* word_res) {
1697  WERD_CHOICE* word = word_res->best_choice;
1698  for (int i = 0; i < word_res->best_choice->length(); ++i) {
1699  BLOB_CHOICE* choice = FindMatchingChoice(blob_choice->unichar_id(),
1700  word_res->GetBlobChoices(i));
1701  if (choice == nullptr) {
1702  BLOB_CHOICE_IT choice_it(word_res->GetBlobChoices(i));
1703  choice_it.add_before_stay_put(new BLOB_CHOICE(*blob_choice));
1704  }
1705  }
1706  // Correct any incorrect results in word.
1707  for (int i = 0; i < word->length(); ++i) {
1708  if (word->unichar_id(i) != blob_choice->unichar_id())
1709  word->set_unichar_id(blob_choice->unichar_id(), i);
1710  }
1711 }
1712 
1721  WERD_RES *word_res = page_res_it->word();
1722  const WERD_CHOICE &word = *(word_res->best_choice);
1723 
1724  // Find the frequency of each unique character in the word.
1725  SortHelper<UNICHAR_ID> rep_ch(word.length());
1726  for (int i = 0; i < word.length(); ++i) {
1727  rep_ch.Add(word.unichar_id(i), 1);
1728  }
1729 
1730  // Find the most frequent result.
1731  UNICHAR_ID maxch_id = INVALID_UNICHAR_ID; // most common char
1732  int max_count = rep_ch.MaxCount(&maxch_id);
1733  // Find the best exemplar of a classifier result for maxch_id.
1734  BLOB_CHOICE* best_choice = FindBestMatchingChoice(maxch_id, word_res);
1735  if (best_choice == nullptr) {
1736  tprintf("Failed to find a choice for %s, occurring %d times\n",
1737  word_res->uch_set->debug_str(maxch_id).string(), max_count);
1738  return;
1739  }
1740  word_res->done = true;
1741 
1742  // Measure the mean space.
1743  int gap_count = 0;
1744  WERD* werd = word_res->word;
1745  C_BLOB_IT blob_it(werd->cblob_list());
1746  C_BLOB* prev_blob = blob_it.data();
1747  for (blob_it.forward(); !blob_it.at_first(); blob_it.forward()) {
1748  C_BLOB* blob = blob_it.data();
1749  int gap = blob->bounding_box().left();
1750  gap -= prev_blob->bounding_box().right();
1751  ++gap_count;
1752  prev_blob = blob;
1753  }
1754  // Just correct existing classification.
1755  CorrectRepcharChoices(best_choice, word_res);
1756  word_res->reject_map.initialise(word.length());
1757 }
1758 
1760  const UNICHARSET& char_set, const char *s, const char *lengths) {
1761  int i = 0;
1762  int offset = 0;
1763  int leading_punct_count;
1764  int upper_count = 0;
1765  int hyphen_pos = -1;
1767 
1768  if (strlen (lengths) > 20)
1769  return word_type;
1770 
1771  /* Single Leading punctuation char*/
1772 
1773  if (s[offset] != '\0' && STRING(chs_leading_punct).contains(s[offset]))
1774  offset += lengths[i++];
1775  leading_punct_count = i;
1776 
1777  /* Initial cap */
1778  while (s[offset] != '\0' && char_set.get_isupper(s + offset, lengths[i])) {
1779  offset += lengths[i++];
1780  upper_count++;
1781  }
1782  if (upper_count > 1) {
1783  word_type = AC_UPPER_CASE;
1784  } else {
1785  /* Lower case word, possibly with an initial cap */
1786  while (s[offset] != '\0' && char_set.get_islower(s + offset, lengths[i])) {
1787  offset += lengths[i++];
1788  }
1789  if (i - leading_punct_count < quality_min_initial_alphas_reqd)
1790  goto not_a_word;
1791  /*
1792  Allow a single hyphen in a lower case word
1793  - don't trust upper case - I've seen several cases of "H" -> "I-I"
1794  */
1795  if (lengths[i] == 1 && s[offset] == '-') {
1796  hyphen_pos = i;
1797  offset += lengths[i++];
1798  if (s[offset] != '\0') {
1799  while ((s[offset] != '\0') &&
1800  char_set.get_islower(s + offset, lengths[i])) {
1801  offset += lengths[i++];
1802  }
1803  if (i < hyphen_pos + 3)
1804  goto not_a_word;
1805  }
1806  } else {
1807  /* Allow "'s" in NON hyphenated lower case words */
1808  if (lengths[i] == 1 && (s[offset] == '\'') &&
1809  lengths[i + 1] == 1 && (s[offset + lengths[i]] == 's')) {
1810  offset += lengths[i++];
1811  offset += lengths[i++];
1812  }
1813  }
1814  if (upper_count > 0)
1815  word_type = AC_INITIAL_CAP;
1816  else
1817  word_type = AC_LOWER_CASE;
1818  }
1819 
1820  /* Up to two different, constrained trailing punctuation chars */
1821  if (lengths[i] == 1 && s[offset] != '\0' &&
1822  STRING(chs_trailing_punct1).contains(s[offset]))
1823  offset += lengths[i++];
1824  if (lengths[i] == 1 && s[offset] != '\0' && i > 0 &&
1825  s[offset - lengths[i - 1]] != s[offset] &&
1826  STRING(chs_trailing_punct2).contains (s[offset]))
1827  offset += lengths[i++];
1828 
1829  if (s[offset] != '\0')
1830  word_type = AC_UNACCEPTABLE;
1831 
1832  not_a_word:
1833 
1834  if (word_type == AC_UNACCEPTABLE) {
1835  /* Look for abbreviation string */
1836  i = 0;
1837  offset = 0;
1838  if (s[0] != '\0' && char_set.get_isupper(s, lengths[0])) {
1839  word_type = AC_UC_ABBREV;
1840  while (s[offset] != '\0' &&
1841  char_set.get_isupper(s + offset, lengths[i]) &&
1842  lengths[i + 1] == 1 && s[offset + lengths[i]] == '.') {
1843  offset += lengths[i++];
1844  offset += lengths[i++];
1845  }
1846  }
1847  else if (s[0] != '\0' && char_set.get_islower(s, lengths[0])) {
1848  word_type = AC_LC_ABBREV;
1849  while (s[offset] != '\0' &&
1850  char_set.get_islower(s + offset, lengths[i]) &&
1851  lengths[i + 1] == 1 && s[offset + lengths[i]] == '.') {
1852  offset += lengths[i++];
1853  offset += lengths[i++];
1854  }
1855  }
1856  if (s[offset] != '\0')
1857  word_type = AC_UNACCEPTABLE;
1858  }
1859 
1860  return word_type;
1861 }
1862 
1863 bool Tesseract::check_debug_pt(WERD_RES* word, int location) {
1864  bool show_map_detail = false;
1865  int16_t i;
1866 
1867  if (!test_pt)
1868  return false;
1869 
1870  tessedit_rejection_debug.set_value (false);
1871  debug_x_ht_level.set_value(0);
1872 
1873  if (word->word->bounding_box().contains(FCOORD (test_pt_x, test_pt_y))) {
1874  if (location < 0)
1875  return true; // For breakpoint use
1876  tessedit_rejection_debug.set_value(true);
1877  debug_x_ht_level.set_value(2);
1878  tprintf ("\n\nTESTWD::");
1879  switch (location) {
1880  case 0:
1881  tprintf ("classify_word_pass1 start\n");
1882  word->word->print();
1883  break;
1884  case 10:
1885  tprintf ("make_reject_map: initial map");
1886  break;
1887  case 20:
1888  tprintf ("make_reject_map: after NN");
1889  break;
1890  case 30:
1891  tprintf ("classify_word_pass2 - START");
1892  break;
1893  case 40:
1894  tprintf ("classify_word_pass2 - Pre Xht");
1895  break;
1896  case 50:
1897  tprintf ("classify_word_pass2 - END");
1898  show_map_detail = true;
1899  break;
1900  case 60:
1901  tprintf ("fixspace");
1902  break;
1903  case 70:
1904  tprintf ("MM pass START");
1905  break;
1906  case 80:
1907  tprintf ("MM pass END");
1908  break;
1909  case 90:
1910  tprintf ("After Poor quality rejection");
1911  break;
1912  case 100:
1913  tprintf ("unrej_good_quality_words - START");
1914  break;
1915  case 110:
1916  tprintf ("unrej_good_quality_words - END");
1917  break;
1918  case 120:
1919  tprintf ("Write results pass");
1920  show_map_detail = true;
1921  break;
1922  }
1923  if (word->best_choice != nullptr) {
1924  tprintf(" \"%s\" ", word->best_choice->unichar_string().string());
1925  word->reject_map.print(debug_fp);
1926  tprintf("\n");
1927  if (show_map_detail) {
1928  tprintf("\"%s\"\n", word->best_choice->unichar_string().string());
1929  for (i = 0; word->best_choice->unichar_string()[i] != '\0'; i++) {
1930  tprintf("**** \"%c\" ****\n", word->best_choice->unichar_string()[i]);
1931  word->reject_map[i].full_print(debug_fp);
1932  }
1933  }
1934  } else {
1935  tprintf("null best choice\n");
1936  }
1937  tprintf ("Tess Accepted: %s\n", word->tess_accepted ? "TRUE" : "FALSE");
1938  tprintf ("Done flag: %s\n\n", word->done ? "TRUE" : "FALSE");
1939  return true;
1940  } else {
1941  return false;
1942  }
1943 }
1944 
1950 static void find_modal_font( // good chars in word
1951  STATS* fonts, // font stats
1952  int16_t* font_out, // output font
1953  int8_t* font_count // output count
1954 ) {
1955  int16_t font; //font index
1956  int32_t count; //pile count
1957 
1958  if (fonts->get_total () > 0) {
1959  font = static_cast<int16_t>(fonts->mode ());
1960  *font_out = font;
1961  count = fonts->pile_count (font);
1962  *font_count = count < INT8_MAX ? count : INT8_MAX;
1963  fonts->add (font, -*font_count);
1964  }
1965  else {
1966  *font_out = -1;
1967  *font_count = 0;
1968  }
1969 }
1970 
1977  // Don't try to set the word fonts for an lstm word, as the configs
1978  // will be meaningless.
1979  if (word->chopped_word == nullptr) return;
1980  ASSERT_HOST(word->best_choice != nullptr);
1981 
1982 #ifndef DISABLED_LEGACY_ENGINE
1983  const int fontinfo_size = get_fontinfo_table().size();
1984  if (fontinfo_size == 0) return;
1985  GenericVector<int> font_total_score;
1986  font_total_score.init_to_size(fontinfo_size, 0);
1987 
1988  word->italic = 0;
1989  word->bold = 0;
1990  // Compute the font scores for the word
1991  if (tessedit_debug_fonts) {
1992  tprintf("Examining fonts in %s\n",
1993  word->best_choice->debug_string().string());
1994  }
1995  for (int b = 0; b < word->best_choice->length(); ++b) {
1996  const BLOB_CHOICE* choice = word->GetBlobChoice(b);
1997  if (choice == nullptr) continue;
1998  const GenericVector<ScoredFont>& fonts = choice->fonts();
1999  for (int f = 0; f < fonts.size(); ++f) {
2000  const int fontinfo_id = fonts[f].fontinfo_id;
2001  if (0 <= fontinfo_id && fontinfo_id < fontinfo_size) {
2002  font_total_score[fontinfo_id] += fonts[f].score;
2003  }
2004  }
2005  }
2006  // Find the top and 2nd choice for the word.
2007  int score1 = 0, score2 = 0;
2008  int16_t font_id1 = -1, font_id2 = -1;
2009  for (int f = 0; f < fontinfo_size; ++f) {
2010  if (tessedit_debug_fonts && font_total_score[f] > 0) {
2011  tprintf("Font %s, total score = %d\n",
2012  fontinfo_table_.get(f).name, font_total_score[f]);
2013  }
2014  if (font_total_score[f] > score1) {
2015  score2 = score1;
2016  font_id2 = font_id1;
2017  score1 = font_total_score[f];
2018  font_id1 = f;
2019  } else if (font_total_score[f] > score2) {
2020  score2 = font_total_score[f];
2021  font_id2 = f;
2022  }
2023  }
2024  word->fontinfo = font_id1 >= 0 ? &fontinfo_table_.get(font_id1) : nullptr;
2025  word->fontinfo2 = font_id2 >= 0 ? &fontinfo_table_.get(font_id2) : nullptr;
2026  // Each score has a limit of UINT16_MAX, so divide by that to get the number
2027  // of "votes" for that font, ie number of perfect scores.
2028  word->fontinfo_id_count = ClipToRange<int>(score1 / UINT16_MAX, 1, INT8_MAX);
2029  word->fontinfo_id2_count = ClipToRange<int>(score2 / UINT16_MAX, 0, INT8_MAX);
2030  if (score1 > 0) {
2031  const FontInfo fi = fontinfo_table_.get(font_id1);
2032  if (tessedit_debug_fonts) {
2033  if (word->fontinfo_id2_count > 0 && font_id2 >= 0) {
2034  tprintf("Word modal font=%s, score=%d, 2nd choice %s/%d\n",
2035  fi.name, word->fontinfo_id_count,
2036  fontinfo_table_.get(font_id2).name,
2037  word->fontinfo_id2_count);
2038  } else {
2039  tprintf("Word modal font=%s, score=%d. No 2nd choice\n",
2040  fi.name, word->fontinfo_id_count);
2041  }
2042  }
2043  word->italic = (fi.is_italic() ? 1 : -1) * word->fontinfo_id_count;
2044  word->bold = (fi.is_bold() ? 1 : -1) * word->fontinfo_id_count;
2045  }
2046 #endif // ndef DISABLED_LEGACY_ENGINE
2047 }
2048 
2049 
2056  PAGE_RES_IT page_res_it(page_res);
2057  WERD_RES *word; // current word
2058  STATS doc_fonts(0, font_table_size_); // font counters
2059 
2060  // Gather font id statistics.
2061  for (page_res_it.restart_page(); page_res_it.word() != nullptr;
2062  page_res_it.forward()) {
2063  word = page_res_it.word();
2064  if (word->fontinfo != nullptr) {
2065  doc_fonts.add(word->fontinfo->universal_id, word->fontinfo_id_count);
2066  }
2067  if (word->fontinfo2 != nullptr) {
2068  doc_fonts.add(word->fontinfo2->universal_id, word->fontinfo_id2_count);
2069  }
2070  }
2071  int16_t doc_font; // modal font
2072  int8_t doc_font_count; // modal font
2073  find_modal_font(&doc_fonts, &doc_font, &doc_font_count);
2074  if (doc_font_count == 0)
2075  return;
2076  // Get the modal font pointer.
2077  const FontInfo* modal_font = nullptr;
2078  for (page_res_it.restart_page(); page_res_it.word() != nullptr;
2079  page_res_it.forward()) {
2080  word = page_res_it.word();
2081  if (word->fontinfo != nullptr && word->fontinfo->universal_id == doc_font) {
2082  modal_font = word->fontinfo;
2083  break;
2084  }
2085  if (word->fontinfo2 != nullptr && word->fontinfo2->universal_id == doc_font) {
2086  modal_font = word->fontinfo2;
2087  break;
2088  }
2089  }
2090  ASSERT_HOST(modal_font != nullptr);
2091 
2092  // Assign modal font to weak words.
2093  for (page_res_it.restart_page(); page_res_it.word() != nullptr;
2094  page_res_it.forward()) {
2095  word = page_res_it.word();
2096  const int length = word->best_choice->length();
2097 
2098  const int count = word->fontinfo_id_count;
2099  if (!(count == length || (length > 3 && count >= length * 3 / 4))) {
2100  word->fontinfo = modal_font;
2101  // Counts only get 1 as it came from the doc.
2102  word->fontinfo_id_count = 1;
2103  word->italic = modal_font->is_italic() ? 1 : -1;
2104  word->bold = modal_font->is_bold() ? 1 : -1;
2105  }
2106  }
2107 }
2108 
2109 // If a word has multiple alternates check if the best choice is in the
2110 // dictionary. If not, replace it with an alternate that exists in the
2111 // dictionary.
2113  PAGE_RES_IT word_it(page_res);
2114  for (WERD_RES* word = word_it.word(); word != nullptr;
2115  word = word_it.forward()) {
2116  if (word->best_choices.singleton())
2117  continue; // There are no alternates.
2118 
2119  const WERD_CHOICE* best = word->best_choice;
2120  if (word->tesseract->getDict().valid_word(*best) != 0)
2121  continue; // The best choice is in the dictionary.
2122 
2123  WERD_CHOICE_IT choice_it(&word->best_choices);
2124  for (choice_it.mark_cycle_pt(); !choice_it.cycled_list();
2125  choice_it.forward()) {
2126  WERD_CHOICE* alternate = choice_it.data();
2127  if (word->tesseract->getDict().valid_word(*alternate)) {
2128  // The alternate choice is in the dictionary.
2129  if (tessedit_bigram_debug) {
2130  tprintf("Dictionary correction replaces best choice '%s' with '%s'\n",
2131  best->unichar_string().string(),
2132  alternate->unichar_string().string());
2133  }
2134  // Replace the 'best' choice with a better choice.
2135  word->ReplaceBestChoice(alternate);
2136  break;
2137  }
2138  }
2139  }
2140 }
2141 
2142 } // namespace tesseract
void word_char_quality(WERD_RES *word, ROW *row, int16_t *match_count, int16_t *accepted_match_count)
Definition: docqual.cpp:92
UNICHAR_ID unichar_id() const
Definition: ratngs.h:77
int16_t word_outline_errs(WERD_RES *word)
Definition: docqual.cpp:72
ParamsVectors * params()
Definition: ccutil.h:65
float baseline_shift
Definition: pageres.h:312
Definition: werd.h:56
void recog_pseudo_word(PAGE_RES *page_res, TBOX &selection_box)
Definition: control.cpp:62
void GetNoiseOutlines(GenericVector< C_OUTLINE * > *outlines)
Definition: werd.cpp:508
bool AnyTessLang() const
bool tess_failed
Definition: pageres.h:287
static void LastChanceBlame(bool debug, WERD_RES *word)
Definition: blamer.cpp:555
void full_print(FILE *fp)
Definition: rejctmap.cpp:333
bool AdaptableWord(WERD_RES *word)
Definition: adaptmatch.cpp:821
BLOCK * block
Definition: pageres.h:116
int16_t top() const
Definition: rect.h:58
C_OUTLINE_LIST * out_list()
Definition: stepblob.h:70
WERD_RES * restart_page()
Definition: pageres.h:702
float x_height() const
Definition: ocrrow.h:64
bool done
Definition: pageres.h:297
void clear_fx_win()
Definition: drawfx.cpp:62
bool guessed_x_ht
Definition: pageres.h:307
void AssignDiacriticsToOverlappingBlobs(const GenericVector< C_OUTLINE * > &outlines, int pass, WERD *real_word, PAGE_RES_IT *pr_it, GenericVector< bool > *word_wanted, GenericVector< bool > *overlapped_any_blob, GenericVector< C_BLOB * > *target_blobs)
Definition: control.cpp:1014
Definition: rect.h:34
bool major_overlap(const TBOX &box) const
Definition: rect.h:368
void print() const
Definition: rect.h:278
TWERD * rebuild_word
Definition: pageres.h:259
Unacceptable word.
Definition: control.h:30
void ReplaceBestChoice(WERD_CHOICE *choice)
Definition: pageres.cpp:799
UnicityTable< FontInfo > fontinfo_table_
Definition: classify.h:528
int length() const
Definition: genericvector.h:84
WERD_RES * InsertSimpleCloneWord(const WERD_RES &clone_res, WERD *new_word)
Definition: pageres.cpp:1260
int32_t length() const
Definition: rejctmap.h:223
GenericVector< int > blame_reasons
Definition: pageres.h:86
#define LOC_DOC_BLK_REJ
Definition: errcode.h:52
float ComputeCompatibleXheight(WERD_RES *word_res, float *baseline_shift)
Definition: fixxht.cpp:102
bool SetupForRecognition(const UNICHARSET &unicharset_in, tesseract::Tesseract *tesseract, Pix *pix, int norm_mode, const TBOX *norm_box, bool numeric_mode, bool use_body_size, bool allow_detailed_fx, ROW *row, const BLOCK *block)
Definition: pageres.cpp:306
void ResetWordIterator()
Definition: pageres.cpp:1570
float rating() const
Definition: ratngs.h:80
Definition: strngs.h:45
Definition: points.h:188
FCOORD classify_rotation() const
Definition: ocrblock.h:141
bool wordrec_run_blamer
Definition: wordrec.h:237
WERD_CHOICE * prev_word_best_choice_
Definition: wordrec.h:481
FILE * debug_fp
Definition: tessvars.cpp:24
bool word_adaptable(WERD_RES *word, uint16_t mode)
Definition: adaptions.cpp:34
void LSTMRecognizeWord(const BLOCK &block, ROW *row, WERD_RES *word, PointerVector< WERD_RES > *words)
Definition: linerec.cpp:222
BLOB_CHOICE * GetBlobChoice(int index) const
Definition: pageres.cpp:754
POLY_BLOCK * poly_block() const
Definition: pdblock.h:56
void ZoomToRectangle(int x1, int y1, int x2, int y2)
Definition: scrollview.cpp:757
bool recog_all_words(PAGE_RES *page_res, ETEXT_DESC *monitor, const TBOX *target_word_box, const char *word_config, int dopasses)
Definition: control.cpp:303
bool is_italic() const
Definition: fontinfo.h:111
const UNICHARSET & GetUnicharset() const
static void PrintParams(FILE *fp, const ParamsVectors *member_params)
Definition: params.cpp:180
void add_str_int(const char *str, int number)
Definition: strngs.cpp:377
const STRING & unichar_string() const
Definition: ratngs.h:541
C_BLOB_LIST * rej_cblob_list()
Definition: werd.h:90
ROW_RES * row() const
Definition: pageres.h:758
UNICHARSET unicharset
Definition: ccutil.h:71
bool IsAllSpaces() const
Definition: ratngs.h:521
start of line
Definition: werd.h:32
int32_t length() const
Definition: strngs.cpp:189
GenericVector< STRING > misadaption_log
Definition: pageres.h:91
void match_word_pass_n(int pass_n, WERD_RES *word, ROW *row, BLOCK *block)
Definition: control.cpp:1644
ACCEPTABLE_WERD_TYPE
Definition: control.h:28
BLOCK_RES * block() const
Definition: pageres.h:761
float min_x_height() const
Definition: ratngs.h:336
void fix_fuzzy_spaces(ETEXT_DESC *monitor, int32_t word_count, PAGE_RES *page_res)
Definition: fixspace.cpp:75
int length() const
Definition: ratngs.h:303
#define LOC_MM_ADAPT
Definition: errcode.h:51
WERD_CHOICE_LIST best_choices
Definition: pageres.h:242
bool contains(const FCOORD pt) const
Definition: rect.h:333
bool tessedit_enable_bigram_correction
void(Tesseract::*)(const WordData &, WERD_RES **, PointerVector< WERD_RES > *) WordRecognizer
void print(FILE *fp)
Definition: rejctmap.cpp:321
int8_t bold
Definition: pageres.h:301
void script_pos_pass(PAGE_RES *page_res)
Definition: control.cpp:735
bool EqualIgnoringCaseAndTerminalPunct(const WERD_CHOICE &word1, const WERD_CHOICE &word2)
Definition: ratngs.cpp:805
bool AddSelectedOutlines(const GenericVector< bool > &wanted, const GenericVector< C_BLOB * > &target_blobs, const GenericVector< C_OUTLINE * > &outlines, bool *make_next_word_fuzzy)
Definition: werd.cpp:526
TBOX bounding_box() const
Definition: stepblob.cpp:253
void create_fx_win()
Definition: drawfx.cpp:49
void CopyTruth(const BlamerBundle &other)
Definition: blamer.h:199
void add(int32_t value, int32_t count)
Definition: statistc.cpp:99
void init_to_size(int size, const T &t)
bool TestNewNormalization(int original_misfits, float baseline_shift, float new_x_ht, WERD_RES *word, BLOCK *block, ROW *row)
Definition: control.cpp:1533
bool tess_accepted
Definition: pageres.h:295
void plot(ScrollView *window)
Definition: blobs.cpp:901
bool right_to_left() const
tesseract::Tesseract * tesseract
Definition: pageres.h:281
repeated character
Definition: werd.h:38
int length() const
Definition: boxword.h:83
#define LOC_FUZZY_SPACE
Definition: errcode.h:49
PointerVector< WERD_RES > lang_words
ScrollView * fx_win
Definition: drawfx.cpp:40
bool tess_acceptable_word(WERD_RES *word)
Definition: tessbox.cpp:62
int16_t word_blob_quality(WERD_RES *word, ROW *row)
Definition: docqual.cpp:60
bool tess_would_adapt
Definition: pageres.h:296
void StartBackupAdaptiveClassifier()
Definition: adaptmatch.cpp:629
int16_t progress
chars in this buffer(0)
Definition: ocrclass.h:105
bool script_has_xheight() const
Definition: unicharset.h:904
end of line
Definition: werd.h:33
void SetMisAdaptionDebug(const WERD_CHOICE *best_choice, bool debug)
Definition: blamer.cpp:582
REJMAP reject_map
Definition: pageres.h:286
void ReportXhtFixResult(bool accept_new_word, float new_x_ht, WERD_RES *word, WERD_RES *new_word)
Definition: control.cpp:1476
const double kMinRefitXHeightFraction
Definition: control.cpp:51
a.b.c.
Definition: control.h:34
void print()
Definition: werd.cpp:253
const UNICHARSET * uch_set
Definition: pageres.h:205
ALL but initial lc.
Definition: control.h:33
float y() const
Definition: points.h:210
BLOB_CHOICE * FindMatchingChoice(UNICHAR_ID char_id, BLOB_CHOICE_LIST *bc_list)
Definition: ratngs.cpp:180
bool AdaptiveClassifierIsFull() const
Definition: classify.h:325
static void Update()
Definition: scrollview.cpp:709
volatile int8_t ocr_alive
true if not last
Definition: ocrclass.h:110
void tess_add_doc_word(WERD_CHOICE *word_choice)
Definition: tessbox.cpp:72
const FontInfo * fontinfo2
Definition: pageres.h:304
static int SortByXMiddle(const void *v1, const void *v2)
Definition: stepblob.h:125
Pix * BestPix() const
bool ProcessTargetWord(const TBOX &word_box, const TBOX &target_word_box, const char *word_config, int pass)
Definition: control.cpp:120
IncorrectResultReason incorrect_result_reason() const
Definition: blamer.h:118
int8_t fontinfo_id2_count
Definition: pageres.h:306
void * cancel_this
monitor-aware progress callback
Definition: ocrclass.h:116
void output_pass(PAGE_RES_IT &page_res_it, const TBOX *target_word_box)
Definition: output.cpp:36
A.B.C.
Definition: control.h:35
float rating() const
Definition: ratngs.h:327
bool check_debug_pt(WERD_RES *word, int location)
Definition: control.cpp:1863
void fix_quotes()
Definition: pageres.cpp:1022
bool x_overlap(const TBOX &box) const
Definition: rect.h:401
bool RecogAllWordsPassN(int pass_n, ETEXT_DESC *monitor, PAGE_RES_IT *pr_it, GenericVector< WordData > *words)
Definition: control.cpp:213
bool small_caps
Definition: pageres.h:298
void initialise(int16_t length)
Definition: rejctmap.cpp:273
ACCEPTABLE_WERD_TYPE acceptable_word_string(const UNICHARSET &char_set, const char *s, const char *lengths)
Definition: control.cpp:1759
int32_t x_height() const
return xheight
Definition: ocrblock.h:107
const FontInfo * fontinfo
Definition: pageres.h:303
const char * string() const
Definition: strngs.cpp:194
int32_t pile_count(int32_t value) const
Definition: statistc.h:76
void font_recognition_pass(PAGE_RES *page_res)
Definition: control.cpp:2055
void PrerecAllWordsPar(const GenericVector< WordData > &words)
Definition: par_control.cpp:39
DLLSYM void tprintf(const char *format,...)
Definition: tprintf.cpp:36
bool AdaptiveClassifierIsEmpty() const
Definition: classify.h:326
void set_word_fonts(WERD_RES *word)
Definition: control.cpp:1976
bool empty() const
Definition: genericvector.h:89
void Add(T value, int count)
Definition: sorthelper.h:65
void fix_hyphens()
Definition: pageres.cpp:1051
TBOX bounding_box() const
Definition: blobs.cpp:865
PAGE_RES_IT * make_pseudo_word(PAGE_RES *page_res, const TBOX &selection_box)
Definition: werdit.cpp:35
void set_unichar_id(UNICHAR_ID unichar_id, int index)
Definition: ratngs.h:359
tesseract::BoxWord * box_word
Definition: pageres.h:265
int push_back(T object)
float ClassifyBlobAsWord(int pass_n, PAGE_RES_IT *pr_it, C_BLOB *blob, STRING *best_str, float *c2)
Definition: control.cpp:1282
int32_t char_count
Definition: pageres.h:78
WERD_RES * word() const
Definition: pageres.h:755
Dict & getDict() override
bool ReassignDiacritics(int pass, PAGE_RES_IT *pr_it, bool *make_next_word_fuzzy)
Definition: control.cpp:944
PAGE_RES * page_res
Definition: pageres.h:678
bool SubAndSuperscriptFix(WERD_RES *word_res)
bool TrainedXheightFix(WERD_RES *word, BLOCK *block, ROW *row)
Definition: control.cpp:1499
WERD_RES * forward()
Definition: pageres.h:735
bool top_bottom_useful() const
Definition: unicharset.h:537
int32_t universal_id
Definition: fontinfo.h:123
PDBLK pdblk
Page Description Block.
Definition: ocrblock.h:191
float ClassifyBlobPlusOutlines(const GenericVector< bool > &ok_outlines, const GenericVector< C_OUTLINE * > &outlines, int pass_n, PAGE_RES_IT *pr_it, C_BLOB *blob, STRING *best_str)
Definition: control.cpp:1234
double classify_max_certainty_margin
Definition: classify.h:444
STRING lang
Definition: ccutil.h:69
void bigram_correction_pass(PAGE_RES *page_res)
Definition: control.cpp:468
int16_t right() const
Definition: rect.h:79
const GenericVector< tesseract::ScoredFont > & fonts() const
Definition: ratngs.h:92
void SetupWordPassN(int pass_n, WordData *word)
Definition: control.cpp:177
bool contains(char c) const
Definition: strngs.cpp:185
void ConsumeWordResults(WERD_RES *word)
Definition: pageres.cpp:769
int16_t bottom() const
Definition: rect.h:65
STRING debug_str(UNICHAR_ID id) const
Definition: unicharset.cpp:343
TBOX bounding_box() const
Definition: werd.cpp:148
void GetNonSuperscriptSpan(int *start, int *end) const
Definition: ratngs.cpp:397
float certainty() const
Definition: ratngs.h:330
void BestChoiceToCorrectText()
Definition: pageres.cpp:927
UNICHAR_ID unichar_id(int index) const
Definition: ratngs.h:315
int8_t fontinfo_id_count
Definition: pageres.h:305
#define LOC_WRITE_RESULTS
Definition: errcode.h:53
bool AnyLSTMLang() const
int32_t rej_count
Definition: pageres.h:79
void rej_word_bad_quality()
Definition: rejctmap.cpp:415
WERD_CHOICE * best_choice
Definition: pageres.h:234
WERD * ConstructFromSingleBlob(bool bol, bool eol, C_BLOB *blob)
Definition: werd.cpp:125
#define ASSERT_HOST(x)
Definition: errcode.h:88
void set_global_subloc_code(int loc_code)
Definition: globaloc.cpp:30
int32_t get_total() const
Definition: statistc.h:84
void rejection_passes(PAGE_RES *page_res, ETEXT_DESC *monitor, const TBOX *target_word_box, const char *word_config)
Definition: control.cpp:613
int16_t left() const
Definition: rect.h:72
void AssignDiacriticsToNewBlobs(const GenericVector< C_OUTLINE * > &outlines, int pass, WERD *real_word, PAGE_RES_IT *pr_it, GenericVector< bool > *word_wanted, GenericVector< C_BLOB * > *target_blobs)
Definition: control.cpp:1069
UnicityTable< FontInfo > & get_fontinfo_table()
Definition: classify.h:386
bool part_of_combo
Definition: pageres.h:334
void quality_based_rejection(PAGE_RES_IT &page_res_it, bool good_quality_doc)
Definition: docqual.cpp:138
void classify_word_pass1(const WordData &word_data, WERD_RES **in_word, PointerVector< WERD_RES > *out_words)
Definition: control.cpp:1415
bool flag(WERD_FLAGS mask) const
Definition: werd.h:117
TWERD * chopped_word
Definition: pageres.h:214
void MakeCurrentWordFuzzy()
Definition: pageres.cpp:1520
float caps_height
Definition: pageres.h:311
int16_t reject_count()
Definition: rejctmap.h:229
ALL upper case.
Definition: control.h:32
double classify_max_rating_ratio
Definition: classify.h:442
int UNICHAR_ID
Definition: unichar.h:34
void blamer_pass(PAGE_RES *page_res)
Definition: control.cpp:711
void LearnWord(const char *fontname, WERD_RES *word)
Definition: adaptmatch.cpp:250
bool wordrec_debug_blamer
Definition: wordrec.h:236
static const double kXHeightCapRatio
Definition: ccstruct.h:37
void InitForRetryRecognition(const WERD_RES &source)
Definition: pageres.cpp:281
bool valid_bigram(const WERD_CHOICE &word1, const WERD_CHOICE &word2) const
Definition: dict.cpp:822
void CleanupSingleRowResult(PageSegMode pageseg_mode, PAGE_RES *page_res)
Definition: textord.cpp:322
int32_t mode() const
Definition: statistc.cpp:113
static C_BLOB * deep_copy(const C_BLOB *src)
Definition: stepblob.h:119
bool IsText() const
Definition: polyblk.h:49
const STRING & misadaption_debug() const
Definition: blamer.h:131
Definition: ocrrow.h:36
bool get_isupper(UNICHAR_ID unichar_id) const
Definition: unicharset.h:505
float max_x_height() const
Definition: ratngs.h:339
const STRING debug_string() const
Definition: ratngs.h:505
void dictionary_correction_pass(PAGE_RES *page_res)
Definition: control.cpp:2112
int CountMisfitTops(WERD_RES *word_res)
Definition: fixxht.cpp:70
int size() const
Definition: genericvector.h:70
Definition: statistc.h:31
int RetryWithLanguage(const WordData &word_data, WordRecognizer recognizer, bool debug, WERD_RES **in_word, PointerVector< WERD_RES > *best_words)
Definition: control.cpp:905
WERD_CHOICE * raw_choice
Definition: pageres.h:239
const char *const kBackUpConfigFile
Definition: control.cpp:48
bool deadline_exceeded() const
Definition: ocrclass.h:138
ROW * row
Definition: pageres.h:142
void make_reject_map(WERD_RES *word, ROW *row, int16_t pass)
bool major_x_overlap(const TBOX &box) const
Definition: rect.h:412
void PrintBestChoices() const
Definition: pageres.cpp:721
float x_height
Definition: pageres.h:310
void fix_rep_char(PAGE_RES_IT *page_res_it)
Definition: control.cpp:1720
bool is_bold() const
Definition: fontinfo.h:112
WERD_CHOICE shallow_copy(int start, int end) const
Definition: ratngs.cpp:414
void classify_word_and_language(int pass_n, PAGE_RES_IT *pr_it, WordData *word_data)
Definition: control.cpp:1333
void SwitchAdaptiveClassifier()
Definition: adaptmatch.cpp:613
WERD * word
Definition: pageres.h:188
void set_global_loc_code(int loc_code)
Definition: globaloc.cpp:25
static bool ReadParamsFile(const char *file, SetParamConstraint constraint, ParamsVectors *member_params)
Definition: params.cpp:42
void SetScriptPositions()
Definition: pageres.cpp:862
void tess_segment_pass_n(int pass_n, WERD_RES *word)
Definition: tessbox.cpp:32
static const char * IncorrectReasonName(IncorrectResultReason irr)
Definition: blamer.cpp:61
bool recog_interactive(PAGE_RES_IT *pr_it)
Definition: control.cpp:77
bool IsAmbiguous()
Definition: pageres.cpp:456
int count(LIST var_list)
Definition: oldlist.cpp:96
BLOB_CHOICE_LIST * GetBlobChoices(int index) const
Definition: pageres.cpp:763
void DeleteCurrentWord()
Definition: pageres.cpp:1487
uint8_t permuter() const
Definition: ratngs.h:346
void classify_word_pass2(const WordData &word_data, WERD_RES **in_word, PointerVector< WERD_RES > *out_words)
Definition: control.cpp:1586
int8_t italic
Definition: pageres.h:300
Definition: ocrblock.h:29
PROGRESS_FUNC2 progress_callback2
called whenever progress increases
Definition: ocrclass.h:115
bool classify_bln_numeric_mode
Definition: classify.h:540
static bool valid_word_permuter(uint8_t perm, bool numbers_ok)
Check all the DAWGs to see if this word is in any of them.
Definition: dict.h:465
void SetupAllWordsPassN(int pass_n, const TBOX *target_word_box, const char *word_config, PAGE_RES *page_res, GenericVector< WordData > *words)
Definition: control.cpp:154
T & back() const
bool get_islower(UNICHAR_ID unichar_id) const
Definition: unicharset.h:498
void rej_stat_word()
Definition: pageres.cpp:1714
bool SelectGoodDiacriticOutlines(int pass, float certainty_threshold, PAGE_RES_IT *pr_it, C_BLOB *blob, const GenericVector< C_OUTLINE * > &outlines, int num_outlines, GenericVector< bool > *ok_outlines)
Definition: control.cpp:1147
void ReplaceCurrentWord(tesseract::PointerVector< WERD_RES > *words)
Definition: pageres.cpp:1380
ALL lower case.
Definition: control.h:31
#define SUBLOC_NORM
Definition: errcode.h:58
BlamerBundle * blamer_bundle
Definition: pageres.h:245
CANCEL_FUNC cancel
for errcode use
Definition: ocrclass.h:112
C_BLOB_LIST * cblob_list()
Definition: werd.h:95