tesseract  4.1.0
pageres.h
Go to the documentation of this file.
1 /**********************************************************************
2  * File: pageres.h (Formerly page_res.h)
3  * Description: Results classes used by control.c
4  * Author: Phil Cheatle
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 #ifndef PAGERES_H
20 #define PAGERES_H
21 
22 #include <cstdint> // for int32_t, int16_t
23 #include <set> // for std::pair
24 #include <vector> // for std::vector
25 #include <sys/types.h> // for int8_t
26 #include "blamer.h" // for BlamerBundle (ptr only), IRR_NUM_REASONS
27 #include "clst.h" // for CLIST_ITERATOR, CLISTIZEH
28 #include "elst.h" // for ELIST_ITERATOR, ELIST_LINK, ELISTIZEH
29 #include "genericvector.h" // for GenericVector, PointerVector (ptr only)
30 #include "matrix.h" // for MATRIX
31 #include "normalis.h" // for DENORM
32 #include "ratngs.h" // for WERD_CHOICE, BLOB_CHOICE (ptr only)
33 #include "rect.h" // for TBOX
34 #include "rejctmap.h" // for REJMAP
35 #include "strngs.h" // for STRING
36 #include "unichar.h" // for UNICHAR_ID, INVALID_UNICHAR_ID
37 #include "unicharset.h" // for UNICHARSET, UNICHARSET::Direction, UNI...
38 #include "werd.h" // for WERD, W_BOL, W_EOL
39 
40 class BLOCK;
41 class BLOCK_LIST;
42 class BLOCK_RES;
43 class ROW;
44 class ROW_RES;
45 class SEAM;
46 class WERD_RES;
47 
48 struct Pix;
49 struct TWERD;
50 
51 template <class R, class A1, class A2> class TessResultCallback2;
52 
53 namespace tesseract {
54  class BoxWord;
55  class Tesseract;
56  struct FontInfo;
57 }
59 
60 /* Forward declarations */
61 
62 class BLOCK_RES;
63 
65 class
66 ROW_RES;
67 
68 ELISTIZEH (ROW_RES)
69 class WERD_RES;
70 
71 ELISTIZEH (WERD_RES)
72 
73 /*************************************************************************
74  * PAGE_RES - Page results
75  *************************************************************************/
76 class PAGE_RES { // page result
77  public:
78  int32_t char_count;
79  int32_t rej_count;
80  BLOCK_RES_LIST block_res_list;
81  bool rejected;
82  // Updated every time PAGE_RES_IT iterating on this PAGE_RES moves to
83  // the next word. This pointer is not owned by PAGE_RES class.
85  // Sums of blame reasons computed by the blamer.
87  // Debug information about all the misadaptions on this page.
88  // Each BlamerBundle contains an index into this vector, so that words that
89  // caused misadaption could be marked. However, since words could be
90  // deleted/split/merged, the log is stored on the PAGE_RES level.
92 
93  inline void Init() {
94  char_count = 0;
95  rej_count = 0;
96  rejected = false;
97  prev_word_best_choice = nullptr;
98  blame_reasons.init_to_size(IRR_NUM_REASONS, 0);
99  }
100 
101  PAGE_RES() { Init(); } // empty constructor
102 
103  PAGE_RES(bool merge_similar_words,
104  BLOCK_LIST *block_list, // real blocks
105  WERD_CHOICE **prev_word_best_choice_ptr);
106 
107  ~PAGE_RES () = default;
108 };
109 
110 /*************************************************************************
111  * BLOCK_RES - Block results
112  *************************************************************************/
113 
114 class BLOCK_RES:public ELIST_LINK {
115  public:
116  BLOCK * block; // real block
117  int32_t char_count; // chars in block
118  int32_t rej_count; // rejected chars
119  int16_t font_class; //
120  int16_t row_count;
121  float x_height;
122  bool font_assigned; // block already
123  // processed
124  bool bold; // all bold
125  bool italic; // all italic
126 
127  ROW_RES_LIST row_res_list;
128 
129  BLOCK_RES() = default;
130 
131  BLOCK_RES(bool merge_similar_words, BLOCK *the_block); // real block
132 
133  ~BLOCK_RES () = default;
134 };
135 
136 /*************************************************************************
137  * ROW_RES - Row results
138  *************************************************************************/
139 
140 class ROW_RES:public ELIST_LINK {
141  public:
142  ROW * row; // real row
143  int32_t char_count; // chars in block
144  int32_t rej_count; // rejected chars
145  int32_t whole_word_rej_count; // rejs in total rej wds
146  WERD_RES_LIST word_res_list;
147 
148  ROW_RES() = default;
149 
150  ROW_RES(bool merge_similar_words, ROW *the_row); // real row
151 
152  ~ROW_RES() = default;
153 };
154 
155 /*************************************************************************
156  * WERD_RES - Word results
157  *************************************************************************/
159 {
164 };
165 
166 // WERD_RES is a collection of publicly accessible members that gathers
167 // information about a word result.
168 class WERD_RES : public ELIST_LINK {
169  public:
170  // Which word is which?
171  // There are 3 coordinate spaces in use here: a possibly rotated pixel space,
172  // the original image coordinate space, and the BLN space in which the
173  // baseline of a word is at kBlnBaselineOffset, the xheight is kBlnXHeight,
174  // and the x-middle of the word is at 0.
175  // In the rotated pixel space, coordinates correspond to the input image,
176  // but may be rotated about the origin by a multiple of 90 degrees,
177  // and may therefore be negative.
178  // In any case a rotation by denorm.block()->re_rotation() will take them
179  // back to the original image.
180  // The other differences between words all represent different stages of
181  // processing during recognition.
182 
183  // ---------------------------INPUT-------------------------------------
184 
185  // The word is the input C_BLOBs in the rotated pixel space.
186  // word is NOT owned by the WERD_RES unless combination is true.
187  // All the other word pointers ARE owned by the WERD_RES.
188  WERD* word; // Input C_BLOB word.
189 
190  // -------------SETUP BY SetupFor*Recognition---READONLY-INPUT------------
191 
192  // The bln_boxes contains the bounding boxes (only) of the input word, in the
193  // BLN space. The lengths of word and bln_boxes
194  // match as they are both before any chopping.
195  // TODO(rays) determine if docqual does anything useful and delete bln_boxes
196  // if it doesn't.
197  tesseract::BoxWord* bln_boxes; // BLN input bounding boxes.
198  // The ROW that this word sits in. NOT owned by the WERD_RES.
200  // The denorm provides the transformation to get back to the rotated image
201  // coords from the chopped_word/rebuild_word BLN coords, but each blob also
202  // has its own denorm.
203  DENORM denorm; // For use on chopped_word.
204  // Unicharset used by the classifier output in best_choice and raw_choice.
205  const UNICHARSET* uch_set; // For converting back to utf8.
206 
207  // ----Initialized by SetupFor*Recognition---BUT OUTPUT FROM RECOGNITION----
208  // ----Setup to a (different!) state expected by the various classifiers----
209  // TODO(rays) Tidy and make more consistent.
210 
211  // The chopped_word is also in BLN space, and represents the fully chopped
212  // character fragments that make up the word.
213  // The length of chopped_word matches length of seam_array + 1 (if set).
214  TWERD* chopped_word; // BLN chopped fragments output.
215  // Vector of SEAM* holding chopping points matching chopped_word.
217  // Widths of blobs in chopped_word.
219  // Gaps between blobs in chopped_word. blob_gaps[i] is the gap between
220  // blob i and blob i+1.
222  // Stores the lstm choices of every timestep
223  std::vector<std::vector<std::pair<const char*, float>>> timesteps;
224  // Ratings matrix contains classifier choices for each classified combination
225  // of blobs. The dimension is the same as the number of blobs in chopped_word
226  // and the leading diagonal corresponds to classifier results of the blobs
227  // in chopped_word. The state_ members of best_choice, raw_choice and
228  // best_choices all correspond to this ratings matrix and allow extraction
229  // of the blob choices for any given WERD_CHOICE.
230  MATRIX* ratings; // Owned pointer.
231  // Pointer to the first WERD_CHOICE in best_choices. This is the result that
232  // will be output from Tesseract. Note that this is now a borrowed pointer
233  // and should NOT be deleted.
234  WERD_CHOICE* best_choice; // Borrowed pointer.
235  // The best raw_choice found during segmentation search. Differs from the
236  // best_choice by being the best result according to just the character
237  // classifier, not taking any language model information into account.
238  // Unlike best_choice, the pointer IS owned by this WERD_RES.
239  WERD_CHOICE* raw_choice; // Owned pointer.
240  // Alternative results found during chopping/segmentation search stages.
241  // Note that being an ELIST, best_choices owns the WERD_CHOICEs.
242  WERD_CHOICE_LIST best_choices;
243 
244  // Truth bounding boxes, text and incorrect choice reason.
246 
247  // --------------OUTPUT FROM RECOGNITION-------------------------------
248  // --------------Not all fields are necessarily set.-------------------
249  // ---best_choice, raw_choice *must* end up set, with a box_word-------
250  // ---In complete output, the number of blobs in rebuild_word matches---
251  // ---the number of boxes in box_word, the number of unichar_ids in---
252  // ---best_choice, the number of ints in best_state, and the number---
253  // ---of strings in correct_text--------------------------------------
254  // ---SetupFake Sets everything to appropriate values if the word is---
255  // ---known to be bad before recognition.------------------------------
256 
257  // The rebuild_word is also in BLN space, but represents the final best
258  // segmentation of the word. Its length is therefore the same as box_word.
259  TWERD* rebuild_word; // BLN best segmented word.
260  // The box_word is in the original image coordinate space. It is the
261  // bounding boxes of the rebuild_word, after denormalization.
262  // The length of box_word matches rebuild_word, best_state (if set) and
263  // correct_text (if set), as well as best_choice and represents the
264  // number of classified units in the output.
265  tesseract::BoxWord* box_word; // Denormalized output boxes.
266  // The best_state stores the relationship between chopped_word and
267  // rebuild_word. Each blob[i] in rebuild_word is composed of best_state[i]
268  // adjacent blobs in chopped_word. The seams in seam_array are hidden
269  // within a rebuild_word blob and revealed between them.
270  GenericVector<int> best_state; // Number of blobs in each best blob.
271  // The correct_text is used during training and adaption to carry the
272  // text to the training system without the need for a unicharset. There
273  // is one entry in the vector for each blob in rebuild_word and box_word.
275  // The Tesseract that was used to recognize this word. Just a borrowed
276  // pointer. Note: Tesseract's class definition is in a higher-level library.
277  // We avoid introducing a cyclic dependency by not using the Tesseract
278  // within WERD_RES. We are just storing it to provide access to it
279  // for the top-level multi-language controller, and maybe for output of
280  // the recognized language.
282 
283  // Less-well documented members.
284  // TODO(rays) Add more documentation here.
285  WERD_CHOICE *ep_choice; // ep text TODO(rays) delete this.
286  REJMAP reject_map; // best_choice rejects
288  /*
289  If tess_failed is true, one of the following tests failed when Tess
290  returned:
291  - The outword blob list was not the same length as the best_choice string;
292  - The best_choice string contained ALL blanks;
293  - The best_choice string was zero length
294  */
295  bool tess_accepted; // Tess thinks its ok?
296  bool tess_would_adapt; // Tess would adapt?
297  bool done; // ready for output?
298  bool small_caps; // word appears to be small caps
299  bool odd_size; // word is bigger than line or leader dots.
300  int8_t italic;
301  int8_t bold;
302  // The fontinfos are pointers to data owned by the classifier.
305  int8_t fontinfo_id_count; // number of votes
306  int8_t fontinfo_id2_count; // number of votes
310  float x_height; // post match estimate
311  float caps_height; // post match estimate
312  float baseline_shift; // post match estimate.
313  // Certainty score for the spaces either side of this word (LSTM mode).
314  // MIN this value with the actual word certainty.
316 
317  /*
318  To deal with fuzzy spaces we need to be able to combine "words" to form
319  combinations when we suspect that the gap is a non-space. The (new) text
320  ord code generates separate words for EVERY fuzzy gap - flags in the word
321  indicate whether the gap is below the threshold (fuzzy kern) and is thus
322  NOT a real word break by default, or above the threshold (fuzzy space) and
323  this is a real word break by default.
324 
325  The WERD_RES list contains all these words PLUS "combination" words built
326  out of (copies of) the words split by fuzzy kerns. The separate parts have
327  their "part_of_combo" flag set true and should be IGNORED on a default
328  reading of the list.
329 
330  Combination words are FOLLOWED by the sequence of part_of_combo words
331  which they combine.
332  */
333  bool combination; //of two fuzzy gap wds
334  bool part_of_combo; //part of a combo
335  bool reject_spaces; //Reject spacing?
336 
338  InitNonPointers();
339  InitPointers();
340  }
341  WERD_RES(WERD *the_word) {
342  InitNonPointers();
343  InitPointers();
344  word = the_word;
345  }
346  // Deep copies everything except the ratings MATRIX.
347  // To get that use deep_copy below.
348  WERD_RES(const WERD_RES& source) : ELIST_LINK(source) {
349  // combination is used in function Clear which is called from operator=.
350  combination = false;
351  InitPointers();
352  *this = source; // see operator=
353  }
354 
355  ~WERD_RES();
356 
357  // Returns the UTF-8 string for the given blob index in the best_choice word,
358  // given that we know whether we are in a right-to-left reading context.
359  // This matters for mirrorable characters such as parentheses. We recognize
360  // characters purely based on their shape on the page, and by default produce
361  // the corresponding unicode for a left-to-right context.
362  const char* BestUTF8(int blob_index, bool in_rtl_context) const {
363  if (blob_index < 0 || best_choice == nullptr ||
364  blob_index >= best_choice->length())
365  return nullptr;
366  UNICHAR_ID id = best_choice->unichar_id(blob_index);
367  if (id < 0 || id >= uch_set->size())
368  return nullptr;
369  UNICHAR_ID mirrored = uch_set->get_mirror(id);
370  if (in_rtl_context && mirrored > 0)
371  id = mirrored;
372  return uch_set->id_to_unichar_ext(id);
373  }
374  // Returns the UTF-8 string for the given blob index in the raw_choice word.
375  const char* RawUTF8(int blob_index) const {
376  if (blob_index < 0 || blob_index >= raw_choice->length())
377  return nullptr;
378  UNICHAR_ID id = raw_choice->unichar_id(blob_index);
379  if (id < 0 || id >= uch_set->size())
380  return nullptr;
381  return uch_set->id_to_unichar(id);
382  }
383 
384  UNICHARSET::Direction SymbolDirection(int blob_index) const {
385  if (best_choice == nullptr ||
386  blob_index >= best_choice->length() ||
387  blob_index < 0)
389  return uch_set->get_direction(best_choice->unichar_id(blob_index));
390  }
391 
392  bool AnyRtlCharsInWord() const {
393  if (uch_set == nullptr || best_choice == nullptr || best_choice->length() < 1)
394  return false;
395  for (int id = 0; id < best_choice->length(); id++) {
396  int unichar_id = best_choice->unichar_id(id);
397  if (unichar_id < 0 || unichar_id >= uch_set->size())
398  continue; // Ignore illegal chars.
400  uch_set->get_direction(unichar_id);
401  if (dir == UNICHARSET::U_RIGHT_TO_LEFT ||
403  return true;
404  }
405  return false;
406  }
407 
408  bool AnyLtrCharsInWord() const {
409  if (uch_set == nullptr || best_choice == nullptr || best_choice->length() < 1)
410  return false;
411  for (int id = 0; id < best_choice->length(); id++) {
412  int unichar_id = best_choice->unichar_id(id);
413  if (unichar_id < 0 || unichar_id >= uch_set->size())
414  continue; // Ignore illegal chars.
415  UNICHARSET::Direction dir = uch_set->get_direction(unichar_id);
416  if (dir == UNICHARSET::U_LEFT_TO_RIGHT ||
418  return true;
419  }
420  return false;
421  }
422 
423  // Return whether the blobs in this WERD_RES 0, 1,... come from an engine
424  // that gave us the unichars in reading order (as opposed to strict left
425  // to right).
426  bool UnicharsInReadingOrder() const {
427  return best_choice->unichars_in_script_order();
428  }
429 
430  void InitNonPointers();
431  void InitPointers();
432  void Clear();
433  void ClearResults();
434  void ClearWordChoices();
435  void ClearRatings();
436 
437  // Deep copies everything except the ratings MATRIX.
438  // To get that use deep_copy below.
439  WERD_RES& operator=(const WERD_RES& source); //from this
440 
441  void CopySimpleFields(const WERD_RES& source);
442 
443  // Initializes a blank (default constructed) WERD_RES from one that has
444  // already been recognized.
445  // Use SetupFor*Recognition afterwards to complete the setup and make
446  // it ready for a retry recognition.
447  void InitForRetryRecognition(const WERD_RES& source);
448 
449  // Sets up the members used in recognition: bln_boxes, chopped_word,
450  // seam_array, denorm. Returns false if
451  // the word is empty and sets up fake results. If use_body_size is
452  // true and row->body_size is set, then body_size will be used for
453  // blob normalization instead of xheight + ascrise. This flag is for
454  // those languages that are using CJK pitch model and thus it has to
455  // be true if and only if tesseract->textord_use_cjk_fp_model is
456  // true.
457  // If allow_detailed_fx is true, the feature extractor will receive fine
458  // precision outline information, allowing smoother features and better
459  // features on low resolution images.
460  // The norm_mode sets the default mode for normalization in absence
461  // of any of the above flags. It should really be a tesseract::OcrEngineMode
462  // but is declared as int for ease of use with tessedit_ocr_engine_mode.
463  // Returns false if the word is empty and sets up fake results.
464  bool SetupForRecognition(const UNICHARSET& unicharset_in,
465  tesseract::Tesseract* tesseract, Pix* pix,
466  int norm_mode,
467  const TBOX* norm_box, bool numeric_mode,
468  bool use_body_size, bool allow_detailed_fx,
469  ROW *row, const BLOCK* block);
470 
471  // Set up the seam array, bln_boxes, best_choice, and raw_choice to empty
472  // accumulators from a made chopped word. We presume the fields are already
473  // empty.
474  void SetupBasicsFromChoppedWord(const UNICHARSET &unicharset_in);
475 
476  // Sets up the members used in recognition for an empty recognition result:
477  // bln_boxes, chopped_word, seam_array, denorm, best_choice, raw_choice.
478  void SetupFake(const UNICHARSET& uch);
479 
480  // Set the word as having the script of the input unicharset.
481  void SetupWordScript(const UNICHARSET& unicharset_in);
482 
483  // Sets up the blamer_bundle if it is not null, using the initialized denorm.
484  void SetupBlamerBundle();
485 
486  // Computes the blob_widths and blob_gaps from the chopped_word.
487  void SetupBlobWidthsAndGaps();
488 
489  // Updates internal data to account for a new SEAM (chop) at the given
490  // blob_number. Fixes the ratings matrix and states in the choices, as well
491  // as the blob widths and gaps.
492  void InsertSeam(int blob_number, SEAM* seam);
493 
494  // Returns true if all the word choices except the first have adjust_factors
495  // worse than the given threshold.
496  bool AlternativeChoiceAdjustmentsWorseThan(float threshold) const;
497 
498  // Returns true if the current word is ambiguous (by number of answers or
499  // by dangerous ambigs.)
500  bool IsAmbiguous();
501 
502  // Returns true if the ratings matrix size matches the sum of each of the
503  // segmentation states.
504  bool StatesAllValid();
505 
506  // Prints a list of words found if debug is true or the word result matches
507  // the word_to_debug.
508  void DebugWordChoices(bool debug, const char* word_to_debug);
509 
510  // Prints the top choice along with the accepted/done flags.
511  void DebugTopChoice(const char* msg) const;
512 
513  // Removes from best_choices all choices which are not within a reasonable
514  // range of the best choice.
515  void FilterWordChoices(int debug_level);
516 
517  // Computes a set of distance thresholds used to control adaption.
518  // Compares the best choice for the current word to the best raw choice
519  // to determine which characters were classified incorrectly by the
520  // classifier. Then places a separate threshold into thresholds for each
521  // character in the word. If the classifier was correct, max_rating is placed
522  // into thresholds. If the classifier was incorrect, the mean match rating
523  // (error percentage) of the classifier's incorrect choice minus some margin
524  // is placed into thresholds. This can then be used by the caller to try to
525  // create a new template for the desired class that will classify the
526  // character with a rating better than the threshold value. The match rating
527  // placed into thresholds is never allowed to be below min_rating in order to
528  // prevent trying to make overly tight templates.
529  // min_rating limits how tight to make a template.
530  // max_rating limits how loose to make a template.
531  // rating_margin denotes the amount of margin to put in template.
532  void ComputeAdaptionThresholds(float certainty_scale,
533  float min_rating,
534  float max_rating,
535  float rating_margin,
536  float* thresholds);
537 
538  // Saves a copy of the word_choice if it has the best unadjusted rating.
539  // Returns true if the word_choice was the new best.
540  bool LogNewRawChoice(WERD_CHOICE* word_choice);
541  // Consumes word_choice by adding it to best_choices, (taking ownership) if
542  // the certainty for word_choice is some distance of the best choice in
543  // best_choices, or by deleting the word_choice and returning false.
544  // The best_choices list is kept in sorted order by rating. Duplicates are
545  // removed, and the list is kept no longer than max_num_choices in length.
546  // Returns true if the word_choice is still a valid pointer.
547  bool LogNewCookedChoice(int max_num_choices, bool debug,
548  WERD_CHOICE* word_choice);
549 
550  // Prints a brief list of all the best choices.
551  void PrintBestChoices() const;
552 
553  // Returns the sum of the widths of the blob between start_blob and last_blob
554  // inclusive.
555  int GetBlobsWidth(int start_blob, int last_blob);
556  // Returns the width of a gap between the specified blob and the next one.
557  int GetBlobsGap(int blob_index);
558 
559  // Returns the BLOB_CHOICE corresponding to the given index in the
560  // best choice word taken from the appropriate cell in the ratings MATRIX.
561  // Borrowed pointer, so do not delete. May return nullptr if there is no
562  // BLOB_CHOICE matching the unichar_id at the given index.
563  BLOB_CHOICE* GetBlobChoice(int index) const;
564 
565  // Returns the BLOB_CHOICE_LIST corresponding to the given index in the
566  // best choice word taken from the appropriate cell in the ratings MATRIX.
567  // Borrowed pointer, so do not delete.
568  BLOB_CHOICE_LIST* GetBlobChoices(int index) const;
569 
570  // Moves the results fields from word to this. This takes ownership of all
571  // the data, so src can be destructed.
572  // word1.ConsumeWordResult(word);
573  // delete word;
574  // is simpler and faster than:
575  // word1 = *word;
576  // delete word;
577  // as it doesn't need to copy and reallocate anything.
578  void ConsumeWordResults(WERD_RES* word);
579 
580  // Replace the best choice and rebuild box word.
581  // choice must be from the current best_choices list.
582  void ReplaceBestChoice(WERD_CHOICE* choice);
583 
584  // Builds the rebuild_word and sets the best_state from the chopped_word and
585  // the best_choice->state.
586  void RebuildBestState();
587 
588  // Copies the chopped_word to the rebuild_word, faking a best_state as well.
589  // Also sets up the output box_word.
590  void CloneChoppedToRebuild();
591 
592  // Sets/replaces the box_word with one made from the rebuild_word.
593  void SetupBoxWord();
594 
595  // Sets up the script positions in the best_choice using the best_choice
596  // to get the unichars, and the unicharset to get the target positions.
597  void SetScriptPositions();
598  // Sets all the blobs in all the words (best choice and alternates) to be
599  // the given position. (When a sub/superscript is recognized as a separate
600  // word, it falls victim to the rule that a whole word cannot be sub or
601  // superscript, so this function overrides that problem.)
602  void SetAllScriptPositions(tesseract::ScriptPos position);
603 
604  // Classifies the word with some already-calculated BLOB_CHOICEs.
605  // The choices are an array of blob_count pointers to BLOB_CHOICE,
606  // providing a single classifier result for each blob.
607  // The BLOB_CHOICEs are consumed and the word takes ownership.
608  // The number of blobs in the box_word must match blob_count.
609  void FakeClassifyWord(int blob_count, BLOB_CHOICE** choices);
610 
611  // Creates a WERD_CHOICE for the word using the top choices from the leading
612  // diagonal of the ratings matrix.
613  void FakeWordFromRatings(PermuterType permuter);
614 
615  // Copies the best_choice strings to the correct_text for adaption/training.
616  void BestChoiceToCorrectText();
617 
618  // Merges 2 adjacent blobs in the result if the permanent callback
619  // class_cb returns other than INVALID_UNICHAR_ID, AND the permanent
620  // callback box_cb is nullptr or returns true, setting the merged blob
621  // result to the class returned from class_cb.
622  // Returns true if anything was merged.
623  bool ConditionalBlobMerge(
626 
627  // Merges 2 adjacent blobs in the result (index and index+1) and corrects
628  // all the data to account for the change.
629  void MergeAdjacentBlobs(int index);
630 
631  // Callback helper for fix_quotes returns a double quote if both
632  // arguments are quote, otherwise INVALID_UNICHAR_ID.
633  UNICHAR_ID BothQuotes(UNICHAR_ID id1, UNICHAR_ID id2);
634  void fix_quotes();
635 
636  // Callback helper for fix_hyphens returns UNICHAR_ID of - if both
637  // arguments are hyphen, otherwise INVALID_UNICHAR_ID.
638  UNICHAR_ID BothHyphens(UNICHAR_ID id1, UNICHAR_ID id2);
639  // Callback helper for fix_hyphens returns true if box1 and box2 overlap
640  // (assuming both on the same textline, are in order and a chopped em dash.)
641  bool HyphenBoxesOverlap(const TBOX& box1, const TBOX& box2);
642  void fix_hyphens();
643 
644  // Callback helper for merge_tess_fails returns a space if both
645  // arguments are space, otherwise INVALID_UNICHAR_ID.
646  UNICHAR_ID BothSpaces(UNICHAR_ID id1, UNICHAR_ID id2);
647  void merge_tess_fails();
648 
649  // Returns a really deep copy of *src, including the ratings MATRIX.
650  static WERD_RES* deep_copy(const WERD_RES* src) {
651  auto* result = new WERD_RES(*src);
652  // That didn't copy the ratings, but we want a copy if there is one to
653  // begin with.
654  if (src->ratings != nullptr)
655  result->ratings = src->ratings->DeepCopy();
656  return result;
657  }
658 
659  // Copy blobs from word_res onto this word (eliminating spaces between).
660  // Since this may be called bidirectionally OR both the BOL and EOL flags.
661  void copy_on(WERD_RES *word_res) { //from this word
662  word->set_flag(W_BOL, word->flag(W_BOL) || word_res->word->flag(W_BOL));
663  word->set_flag(W_EOL, word->flag(W_EOL) || word_res->word->flag(W_EOL));
664  word->copy_on(word_res->word);
665  }
666 
667  // Returns true if the collection of count pieces, starting at start, are all
668  // natural connected components, ie there are no real chops involved.
669  bool PiecesAllNatural(int start, int count) const;
670 };
671 
672 /*************************************************************************
673  * PAGE_RES_IT - Page results iterator
674  *************************************************************************/
675 
676 class PAGE_RES_IT {
677  public:
678  PAGE_RES * page_res; // page being iterated
679 
680  PAGE_RES_IT() = default;
681 
682  PAGE_RES_IT(PAGE_RES *the_page_res) { // page result
683  page_res = the_page_res;
684  restart_page(); // ready to scan
685  }
686 
687  // Do two PAGE_RES_ITs point at the same word?
688  // This is much cheaper than cmp().
689  bool operator ==(const PAGE_RES_IT &other) const {
690  return word_res == other.word_res && row_res == other.row_res &&
691  block_res == other.block_res;
692  }
693 
694  bool operator !=(const PAGE_RES_IT &other) const {return !(*this == other); }
695 
696  // Given another PAGE_RES_IT to the same page,
697  // this before other: -1
698  // this equal to other: 0
699  // this later than other: 1
700  int cmp(const PAGE_RES_IT &other) const;
701 
703  return start_page(false); // Skip empty blocks.
704  }
706  return start_page(true); // Allow empty blocks.
707  }
708  WERD_RES *start_page(bool empty_ok);
709 
710  WERD_RES *restart_row();
711 
712  // ============ Methods that mutate the underling structures ===========
713  // Note that these methods will potentially invalidate other PAGE_RES_ITs
714  // and are intended to be used only while a single PAGE_RES_IT is active.
715  // This problem needs to be taken into account if these mutation operators
716  // are ever provided to PageIterator or its subclasses.
717 
718  // Inserts the new_word and a corresponding WERD_RES before the current
719  // position. The simple fields of the WERD_RES are copied from clone_res and
720  // the resulting WERD_RES is returned for further setup with best_choice etc.
721  WERD_RES* InsertSimpleCloneWord(const WERD_RES& clone_res, WERD* new_word);
722 
723  // Replaces the current WERD/WERD_RES with the given words. The given words
724  // contain fake blobs that indicate the position of the characters. These are
725  // replaced with real blobs from the current word as much as possible.
726  void ReplaceCurrentWord(tesseract::PointerVector<WERD_RES>* words);
727 
728  // Deletes the current WERD_RES and its underlying WERD.
729  void DeleteCurrentWord();
730 
731  // Makes the current word a fuzzy space if not already fuzzy. Updates
732  // corresponding part of combo if required.
733  void MakeCurrentWordFuzzy();
734 
735  WERD_RES *forward() { // Get next word.
736  return internal_forward(false, false);
737  }
738  // Move forward, but allow empty blocks to show as single nullptr words.
740  return internal_forward(false, true);
741  }
742 
743  WERD_RES *forward_paragraph(); // get first word in next non-empty paragraph
744  WERD_RES *forward_block(); // get first word in next non-empty block
745 
746  WERD_RES *prev_word() const { // previous word
747  return prev_word_res;
748  }
749  ROW_RES *prev_row() const { // row of prev word
750  return prev_row_res;
751  }
752  BLOCK_RES *prev_block() const { // block of prev word
753  return prev_block_res;
754  }
755  WERD_RES *word() const { // current word
756  return word_res;
757  }
758  ROW_RES *row() const { // row of current word
759  return row_res;
760  }
761  BLOCK_RES *block() const { // block of cur. word
762  return block_res;
763  }
764  WERD_RES *next_word() const { // next word
765  return next_word_res;
766  }
767  ROW_RES *next_row() const { // row of next word
768  return next_row_res;
769  }
770  BLOCK_RES *next_block() const { // block of next word
771  return next_block_res;
772  }
773  void rej_stat_word(); // for page/block/row
774  void ResetWordIterator();
775 
776  private:
777  WERD_RES *internal_forward(bool new_block, bool empty_ok);
778 
779  WERD_RES * prev_word_res; // previous word
780  ROW_RES *prev_row_res; // row of prev word
781  BLOCK_RES *prev_block_res; // block of prev word
782 
783  WERD_RES *word_res; // current word
784  ROW_RES *row_res; // row of current word
785  BLOCK_RES *block_res; // block of cur. word
786 
787  WERD_RES *next_word_res; // next word
788  ROW_RES *next_row_res; // row of next word
789  BLOCK_RES *next_block_res; // block of next word
790 
791  BLOCK_RES_IT block_res_it; // iterators
792  ROW_RES_IT row_res_it;
793  WERD_RES_IT word_res_it;
794  // Iterators used to get the state of word_res_it for the current word.
795  // Since word_res_it is 2 words further on, this is otherwise hard to do.
796  WERD_RES_IT wr_it_of_current_word;
797  WERD_RES_IT wr_it_of_next_word;
798 };
799 #endif
ROW_RES * next_row() const
Definition: pageres.h:767
float baseline_shift
Definition: pageres.h:312
Definition: werd.h:56
bool tess_failed
Definition: pageres.h:287
bool UnicharsInReadingOrder() const
Definition: pageres.h:426
BLOCK * block
Definition: pageres.h:116
WERD_RES * restart_page()
Definition: pageres.h:702
PermuterType
Definition: ratngs.h:242
bool done
Definition: pageres.h:297
bool guessed_x_ht
Definition: pageres.h:307
Definition: rect.h:34
std::vector< std::vector< std::pair< const char *, float > > > timesteps
Definition: pageres.h:223
TWERD * rebuild_word
Definition: pageres.h:259
WERD_RES_LIST word_res_list
Definition: pageres.h:146
Definition: blobs.h:397
GenericVector< int > blame_reasons
Definition: pageres.h:86
GenericVector< int > blob_widths
Definition: pageres.h:218
UNICHAR_ID get_mirror(UNICHAR_ID unichar_id) const
Definition: unicharset.h:697
UNICHARSET::Direction SymbolDirection(int blob_index) const
Definition: pageres.h:384
int32_t char_count
Definition: pageres.h:143
GenericVector< STRING > correct_text
Definition: pageres.h:274
WERD_RES(WERD *the_word)
Definition: pageres.h:341
ROW_RES * prev_row() const
Definition: pageres.h:749
ROW_RES * row() const
Definition: pageres.h:758
int32_t whole_word_rej_count
Definition: pageres.h:145
PAGE_RES()
Definition: pageres.h:101
start of line
Definition: werd.h:32
float space_certainty
Definition: pageres.h:315
GenericVector< STRING > misadaption_log
Definition: pageres.h:91
GenericVector< SEAM * > seam_array
Definition: pageres.h:216
ROW_RES_LIST row_res_list
Definition: pageres.h:127
BLOCK_RES * block() const
Definition: pageres.h:761
int length() const
Definition: ratngs.h:303
int size() const
Definition: unicharset.h:341
WERD_CHOICE_LIST best_choices
Definition: pageres.h:242
WERD_CHOICE * ep_choice
Definition: pageres.h:285
Direction get_direction(UNICHAR_ID unichar_id) const
Definition: unicharset.h:690
bool combination
Definition: pageres.h:333
int8_t bold
Definition: pageres.h:301
const char * id_to_unichar(UNICHAR_ID id) const
Definition: unicharset.cpp:291
WERD_RES * restart_page_with_empties()
Definition: pageres.h:705
void init_to_size(int size, const T &t)
tesseract::BoxWord * bln_boxes
Definition: pageres.h:197
bool tess_accepted
Definition: pageres.h:295
const char * id_to_unichar_ext(UNICHAR_ID id) const
Definition: unicharset.cpp:299
tesseract::Tesseract * tesseract
Definition: pageres.h:281
BLOCK_RES * next_block() const
Definition: pageres.h:770
bool bold
Definition: pageres.h:124
bool odd_size
Definition: pageres.h:299
PAGE_RES_IT(PAGE_RES *the_page_res)
Definition: pageres.h:682
bool AnyLtrCharsInWord() const
Definition: pageres.h:408
bool tess_would_adapt
Definition: pageres.h:296
end of line
Definition: werd.h:33
REJMAP reject_map
Definition: pageres.h:286
const UNICHARSET * uch_set
Definition: pageres.h:205
int32_t rej_count
Definition: pageres.h:118
ELISTIZEH(BLOCK_RES) CLISTIZEH(BLOCK_RES) class ROW_RES
const FontInfo * fontinfo2
Definition: pageres.h:304
bool guessed_caps_ht
Definition: pageres.h:308
CRUNCH_MODE unlv_crunch_mode
Definition: pageres.h:309
int8_t fontinfo_id2_count
Definition: pageres.h:306
int16_t font_class
Definition: pageres.h:119
WERD_RES * next_word() const
Definition: pageres.h:764
bool unichars_in_script_order() const
Definition: ratngs.h:535
BLOCK_RES * prev_block() const
Definition: pageres.h:752
bool small_caps
Definition: pageres.h:298
Definition: seam.h:38
static WERD_RES * deep_copy(const WERD_RES *src)
Definition: pageres.h:650
const FontInfo * fontinfo
Definition: pageres.h:303
tesseract::BoxWord * box_word
Definition: pageres.h:265
WERD_RES()
Definition: pageres.h:337
int32_t char_count
Definition: pageres.h:78
WERD_RES * word() const
Definition: pageres.h:755
void copy_on(WERD_RES *word_res)
Definition: pageres.h:661
PAGE_RES * page_res
Definition: pageres.h:678
const char * BestUTF8(int blob_index, bool in_rtl_context) const
Definition: pageres.h:362
WERD_RES * forward()
Definition: pageres.h:735
ROW * blob_row
Definition: pageres.h:199
Definition: matrix.h:578
bool AnyRtlCharsInWord() const
Definition: pageres.h:392
UNICHAR_ID unichar_id(int index) const
Definition: ratngs.h:315
WERD_RES(const WERD_RES &source)
Definition: pageres.h:348
int8_t fontinfo_id_count
Definition: pageres.h:305
int32_t rej_count
Definition: pageres.h:79
WERD_CHOICE * best_choice
Definition: pageres.h:234
MATRIX * ratings
Definition: pageres.h:230
CRUNCH_MODE
Definition: pageres.h:158
bool italic
Definition: pageres.h:125
bool part_of_combo
Definition: pageres.h:334
WERD_RES * prev_word() const
Definition: pageres.h:746
bool flag(WERD_FLAGS mask) const
Definition: werd.h:117
TWERD * chopped_word
Definition: pageres.h:214
bool rejected
Definition: pageres.h:81
float caps_height
Definition: pageres.h:311
int16_t row_count
Definition: pageres.h:120
int UNICHAR_ID
Definition: unichar.h:34
int32_t char_count
Definition: pageres.h:117
void Init()
Definition: pageres.h:93
int32_t rej_count
Definition: pageres.h:144
GenericVector< int > best_state
Definition: pageres.h:270
Definition: ocrrow.h:36
GenericVector< int > blob_gaps
Definition: pageres.h:221
WERD_CHOICE * raw_choice
Definition: pageres.h:239
bool font_assigned
Definition: pageres.h:122
ROW * row
Definition: pageres.h:142
WERD_CHOICE ** prev_word_best_choice
Definition: pageres.h:84
float x_height
Definition: pageres.h:310
WERD_RES * forward_with_empties()
Definition: pageres.h:739
BLOCK_RES_LIST block_res_list
Definition: pageres.h:80
WERD * word
Definition: pageres.h:188
CLISTIZEH(STRING) CLISTIZE(STRING) namespace tesseract
Definition: reject.cpp:51
DENORM denorm
Definition: pageres.h:203
int count(LIST var_list)
Definition: oldlist.cpp:96
const char * RawUTF8(int blob_index) const
Definition: pageres.h:375
bool reject_spaces
Definition: pageres.h:335
int8_t italic
Definition: pageres.h:300
Definition: ocrblock.h:29
MATRIX * DeepCopy() const
Definition: matrix.cpp:94
BlamerBundle * blamer_bundle
Definition: pageres.h:245
float x_height
Definition: pageres.h:121