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