All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
paragraphs.cpp
Go to the documentation of this file.
1 /**********************************************************************
2  * File: paragraphs.cpp
3  * Description: Paragraph detection for tesseract.
4  * Author: David Eger
5  * Created: 25 February 2011
6  *
7  * (C) Copyright 2011, Google Inc.
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 #ifdef _MSC_VER
20 #define __func__ __FUNCTION__
21 #endif
22 
23 #include <ctype.h>
24 
25 #include "genericvector.h"
26 #include "helpers.h"
27 #include "mutableiterator.h"
28 #include "ocrpara.h"
29 #include "pageres.h"
30 #include "paragraphs.h"
31 #include "paragraphs_internal.h"
32 #include "publictypes.h"
33 #include "ratngs.h"
34 #include "rect.h"
35 #include "statistc.h"
36 #include "strngs.h"
37 #include "tprintf.h"
38 #include "unicharset.h"
39 #include "unicodes.h"
40 
41 namespace tesseract {
42 
43 // Special "weak" ParagraphModels.
45  = reinterpret_cast<ParagraphModel *>(0xDEAD111F);
47  = reinterpret_cast<ParagraphModel *>(0xDEAD888F);
48 
49 // Given the width of a typical space between words, what is the threshold
50 // by which by which we think left and right alignments for paragraphs
51 // can vary and still be aligned.
52 static int Epsilon(int space_pix) {
53  return space_pix * 4 / 5;
54 }
55 
56 static bool AcceptableRowArgs(
57  int debug_level, int min_num_rows, const char *function_name,
59  int row_start, int row_end) {
60  if (row_start < 0 || row_end > rows->size() || row_start > row_end) {
61  tprintf("Invalid arguments rows[%d, %d) while rows is of size %d.\n",
62  row_start, row_end, rows->size());
63  return false;
64  }
65  if (row_end - row_start < min_num_rows) {
66  if (debug_level > 1) {
67  tprintf("# Too few rows[%d, %d) for %s.\n",
68  row_start, row_end, function_name);
69  }
70  return false;
71  }
72  return true;
73 }
74 
75 // =============================== Debug Code ================================
76 
77 // Convert an integer to a decimal string.
78 static STRING StrOf(int num) {
79  char buffer[30];
80  snprintf(buffer, sizeof(buffer), "%d", num);
81  return STRING(buffer);
82 }
83 
84 // Given a row-major matrix of unicode text and a column separator, print
85 // a formatted table. For ASCII, we get good column alignment.
86 static void PrintTable(const GenericVector<GenericVector<STRING> > &rows,
87  const STRING &colsep) {
88  GenericVector<int> max_col_widths;
89  for (int r = 0; r < rows.size(); r++) {
90  int num_columns = rows[r].size();
91  for (int c = 0; c < num_columns; c++) {
92  int num_unicodes = 0;
93  for (int i = 0; i < rows[r][c].size(); i++) {
94  if ((rows[r][c][i] & 0xC0) != 0x80) num_unicodes++;
95  }
96  if (c >= max_col_widths.size()) {
97  max_col_widths.push_back(num_unicodes);
98  } else {
99  if (num_unicodes > max_col_widths[c])
100  max_col_widths[c] = num_unicodes;
101  }
102  }
103  }
104 
105  GenericVector<STRING> col_width_patterns;
106  for (int c = 0; c < max_col_widths.size(); c++) {
107  col_width_patterns.push_back(
108  STRING("%-") + StrOf(max_col_widths[c]) + "s");
109  }
110 
111  for (int r = 0; r < rows.size(); r++) {
112  for (int c = 0; c < rows[r].size(); c++) {
113  if (c > 0)
114  tprintf("%s", colsep.string());
115  tprintf(col_width_patterns[c].string(), rows[r][c].string());
116  }
117  tprintf("\n");
118  }
119 }
120 
121 STRING RtlEmbed(const STRING &word, bool rtlify) {
122  if (rtlify)
123  return STRING(kRLE) + word + STRING(kPDF);
124  return word;
125 }
126 
127 // Print the current thoughts of the paragraph detector.
128 static void PrintDetectorState(const ParagraphTheory &theory,
132  output.back().push_back("#row");
133  output.back().push_back("space");
134  output.back().push_back("..");
135  output.back().push_back("lword[widthSEL]");
136  output.back().push_back("rword[widthSEL]");
138  output.back().push_back("text");
139 
140  for (int i = 0; i < rows.size(); i++) {
142  GenericVector<STRING> &row = output.back();
143  const RowInfo& ri = *rows[i].ri_;
144  row.push_back(StrOf(i));
145  row.push_back(StrOf(ri.average_interword_space));
146  row.push_back(ri.has_leaders ? ".." : " ");
147  row.push_back(RtlEmbed(ri.lword_text, !ri.ltr) +
148  "[" + StrOf(ri.lword_box.width()) +
149  (ri.lword_likely_starts_idea ? "S" : "s") +
150  (ri.lword_likely_ends_idea ? "E" : "e") +
151  (ri.lword_indicates_list_item ? "L" : "l") +
152  "]");
153  row.push_back(RtlEmbed(ri.rword_text, !ri.ltr) +
154  "[" + StrOf(ri.rword_box.width()) +
155  (ri.rword_likely_starts_idea ? "S" : "s") +
156  (ri.rword_likely_ends_idea ? "E" : "e") +
157  (ri.rword_indicates_list_item ? "L" : "l") +
158  "]");
159  rows[i].AppendDebugInfo(theory, &row);
160  row.push_back(RtlEmbed(ri.text, !ri.ltr));
161  }
162  PrintTable(output, " ");
163 
164  tprintf("Active Paragraph Models:\n");
165  for (int m = 0; m < theory.models().size(); m++) {
166  tprintf(" %d: %s\n", m + 1, theory.models()[m]->ToString().string());
167  }
168 }
169 
170 static void DebugDump(
171  bool should_print,
172  const STRING &phase,
173  const ParagraphTheory &theory,
175  if (!should_print)
176  return;
177  tprintf("# %s\n", phase.string());
178  PrintDetectorState(theory, rows);
179 }
180 
181 // Print out the text for rows[row_start, row_end)
182 static void PrintRowRange(const GenericVector<RowScratchRegisters> &rows,
183  int row_start, int row_end) {
184  tprintf("======================================\n");
185  for (int row = row_start; row < row_end; row++) {
186  tprintf("%s\n", rows[row].ri_->text.string());
187  }
188  tprintf("======================================\n");
189 }
190 
191 // ============= Brain Dead Language Model (ASCII Version) ===================
192 
193 bool IsLatinLetter(int ch) {
194  return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
195 }
196 
197 bool IsDigitLike(int ch) {
198  return ch == 'o' || ch == 'O' || ch == 'l' || ch == 'I';
199 }
200 
201 bool IsOpeningPunct(int ch) {
202  return strchr("'\"({[", ch) != NULL;
203 }
204 
205 bool IsTerminalPunct(int ch) {
206  return strchr(":'\".?!]})", ch) != NULL;
207 }
208 
209 // Return a pointer after consuming as much text as qualifies as roman numeral.
210 const char *SkipChars(const char *str, const char *toskip) {
211  while (*str != '\0' && strchr(toskip, *str)) { str++; }
212  return str;
213 }
214 
215 const char *SkipChars(const char *str, bool (*skip)(int)) {
216  while (*str != '\0' && skip(*str)) { str++; }
217  return str;
218 }
219 
220 const char *SkipOne(const char *str, const char *toskip) {
221  if (*str != '\0' && strchr(toskip, *str)) return str + 1;
222  return str;
223 }
224 
225 // Return whether it is very likely that this is a numeral marker that could
226 // start a list item. Some examples include:
227 // A I iii. VI (2) 3.5. [C-4]
228 bool LikelyListNumeral(const STRING &word) {
229  const char *kRomans = "ivxlmdIVXLMD";
230  const char *kDigits = "012345789";
231  const char *kOpen = "[{(";
232  const char *kSep = ":;-.,";
233  const char *kClose = "]})";
234 
235  int num_segments = 0;
236  const char *pos = word.string();
237  while (*pos != '\0' && num_segments < 3) {
238  // skip up to two open parens.
239  const char *numeral_start = SkipOne(SkipOne(pos, kOpen), kOpen);
240  const char *numeral_end = SkipChars(numeral_start, kRomans);
241  if (numeral_end != numeral_start) {
242  // Got Roman Numeral. Great.
243  } else {
244  numeral_end = SkipChars(numeral_start, kDigits);
245  if (numeral_end == numeral_start) {
246  // If there's a single latin letter, we can use that.
247  numeral_end = SkipChars(numeral_start, IsLatinLetter);
248  if (numeral_end - numeral_start != 1)
249  break;
250  }
251  }
252  // We got some sort of numeral.
253  num_segments++;
254  // Skip any trailing parens or punctuation.
255  pos = SkipChars(SkipChars(numeral_end, kClose), kSep);
256  if (pos == numeral_end)
257  break;
258  }
259  return *pos == '\0';
260 }
261 
262 bool LikelyListMark(const STRING &word) {
263  const char *kListMarks = "0Oo*.,+.";
264  return word.size() == 1 && strchr(kListMarks, word[0]) != NULL;
265 }
266 
267 bool AsciiLikelyListItem(const STRING &word) {
268  return LikelyListMark(word) || LikelyListNumeral(word);
269 }
270 
271 // ========== Brain Dead Language Model (Tesseract Version) ================
272 
273 // Return the first Unicode Codepoint from werd[pos].
274 int UnicodeFor(const UNICHARSET *u, const WERD_CHOICE *werd, int pos) {
275  if (!u || !werd || pos > werd->length())
276  return 0;
277  return UNICHAR(u->id_to_unichar(werd->unichar_id(pos)), -1).first_uni();
278 }
279 
280 // A useful helper class for finding the first j >= i so that word[j]
281 // does not have given character type.
283  public:
284  UnicodeSpanSkipper(const UNICHARSET *unicharset, const WERD_CHOICE *word)
285  : u_(unicharset), word_(word) { wordlen_ = word->length(); }
286 
287  // Given an input position, return the first position >= pos not punc.
288  int SkipPunc(int pos);
289  // Given an input position, return the first position >= pos not digit.
290  int SkipDigits(int pos);
291  // Given an input position, return the first position >= pos not roman.
292  int SkipRomans(int pos);
293  // Given an input position, return the first position >= pos not alpha.
294  int SkipAlpha(int pos);
295 
296  private:
297  const UNICHARSET *u_;
298  const WERD_CHOICE *word_;
299  int wordlen_;
300 };
301 
303  while (pos < wordlen_ && u_->get_ispunctuation(word_->unichar_id(pos))) pos++;
304  return pos;
305 }
306 
308  while (pos < wordlen_ && (u_->get_isdigit(word_->unichar_id(pos)) ||
309  IsDigitLike(UnicodeFor(u_, word_, pos)))) pos++;
310  return pos;
311 }
312 
314  const char *kRomans = "ivxlmdIVXLMD";
315  while (pos < wordlen_) {
316  int ch = UnicodeFor(u_, word_, pos);
317  if (ch >= 0xF0 || strchr(kRomans, ch) == 0) break;
318  pos++;
319  }
320  return pos;
321 }
322 
324  while (pos < wordlen_ && u_->get_isalpha(word_->unichar_id(pos))) pos++;
325  return pos;
326 }
327 
328 bool LikelyListMarkUnicode(int ch) {
329  if (ch < 0x80) {
330  STRING single_ch;
331  single_ch += ch;
332  return LikelyListMark(single_ch);
333  }
334  switch (ch) {
335  // TODO(eger) expand this list of unicodes as needed.
336  case 0x00B0: // degree sign
337  case 0x2022: // bullet
338  case 0x25E6: // white bullet
339  case 0x00B7: // middle dot
340  case 0x25A1: // white square
341  case 0x25A0: // black square
342  case 0x25AA: // black small square
343  case 0x2B1D: // black very small square
344  case 0x25BA: // black right-pointing pointer
345  case 0x25CF: // black circle
346  case 0x25CB: // white circle
347  return true;
348  default:
349  break; // fall through
350  }
351  return false;
352 }
353 
354 // Return whether it is very likely that this is a numeral marker that could
355 // start a list item. Some examples include:
356 // A I iii. VI (2) 3.5. [C-4]
357 bool UniLikelyListItem(const UNICHARSET *u, const WERD_CHOICE *werd) {
358  if (werd->length() == 1 && LikelyListMarkUnicode(UnicodeFor(u, werd, 0)))
359  return true;
360 
361  UnicodeSpanSkipper m(u, werd);
362  int num_segments = 0;
363  int pos = 0;
364  while (pos < werd->length() && num_segments < 3) {
365  int numeral_start = m.SkipPunc(pos);
366  if (numeral_start > pos + 1) break;
367  int numeral_end = m.SkipRomans(numeral_start);
368  if (numeral_end == numeral_start) {
369  numeral_end = m.SkipDigits(numeral_start);
370  if (numeral_end == numeral_start) {
371  // If there's a single latin letter, we can use that.
372  numeral_end = m.SkipAlpha(numeral_start);
373  if (numeral_end - numeral_start != 1)
374  break;
375  }
376  }
377  // We got some sort of numeral.
378  num_segments++;
379  // Skip any trailing punctuation.
380  pos = m.SkipPunc(numeral_end);
381  if (pos == numeral_end)
382  break;
383  }
384  return pos == werd->length();
385 }
386 
387 // ========= Brain Dead Language Model (combined entry points) ================
388 
389 // Given the leftmost word of a line either as a Tesseract unicharset + werd
390 // or a utf8 string, set the following attributes for it:
391 // is_list - this word might be a list number or bullet.
392 // starts_idea - this word is likely to start a sentence.
393 // ends_idea - this word is likely to end a sentence.
394 void LeftWordAttributes(const UNICHARSET *unicharset, const WERD_CHOICE *werd,
395  const STRING &utf8,
396  bool *is_list, bool *starts_idea, bool *ends_idea) {
397  *is_list = false;
398  *starts_idea = false;
399  *ends_idea = false;
400  if (utf8.size() == 0 || (werd != NULL && werd->length() == 0)) { // Empty
401  *ends_idea = true;
402  return;
403  }
404 
405  if (unicharset && werd) { // We have a proper werd and unicharset so use it.
406  if (UniLikelyListItem(unicharset, werd)) {
407  *is_list = true;
408  *starts_idea = true;
409  *ends_idea = true;
410  }
411  if (unicharset->get_isupper(werd->unichar_id(0))) {
412  *starts_idea = true;
413  }
414  if (unicharset->get_ispunctuation(werd->unichar_id(0))) {
415  *starts_idea = true;
416  *ends_idea = true;
417  }
418  } else { // Assume utf8 is mostly ASCII
419  if (AsciiLikelyListItem(utf8)) {
420  *is_list = true;
421  *starts_idea = true;
422  }
423  int start_letter = utf8[0];
424  if (IsOpeningPunct(start_letter)) {
425  *starts_idea = true;
426  }
427  if (IsTerminalPunct(start_letter)) {
428  *ends_idea = true;
429  }
430  if (start_letter >= 'A' && start_letter <= 'Z') {
431  *starts_idea = true;
432  }
433  }
434 }
435 
436 // Given the rightmost word of a line either as a Tesseract unicharset + werd
437 // or a utf8 string, set the following attributes for it:
438 // is_list - this word might be a list number or bullet.
439 // starts_idea - this word is likely to start a sentence.
440 // ends_idea - this word is likely to end a sentence.
441 void RightWordAttributes(const UNICHARSET *unicharset, const WERD_CHOICE *werd,
442  const STRING &utf8,
443  bool *is_list, bool *starts_idea, bool *ends_idea) {
444  *is_list = false;
445  *starts_idea = false;
446  *ends_idea = false;
447  if (utf8.size() == 0 || (werd != NULL && werd->length() == 0)) { // Empty
448  *ends_idea = true;
449  return;
450  }
451 
452  if (unicharset && werd) { // We have a proper werd and unicharset so use it.
453  if (UniLikelyListItem(unicharset, werd)) {
454  *is_list = true;
455  *starts_idea = true;
456  }
457  UNICHAR_ID last_letter = werd->unichar_id(werd->length() - 1);
458  if (unicharset->get_ispunctuation(last_letter)) {
459  *ends_idea = true;
460  }
461  } else { // Assume utf8 is mostly ASCII
462  if (AsciiLikelyListItem(utf8)) {
463  *is_list = true;
464  *starts_idea = true;
465  }
466  int last_letter = utf8[utf8.size() - 1];
467  if (IsOpeningPunct(last_letter) || IsTerminalPunct(last_letter)) {
468  *ends_idea = true;
469  }
470  }
471 }
472 
473 // =============== Implementation of RowScratchRegisters =====================
474 /* static */
476  GenericVector<STRING> *header) {
477  header->push_back("[lmarg,lind;rind,rmarg]");
478  header->push_back("model");
479 }
480 
482  GenericVector<STRING> *dbg) const {
483  char s[30];
484  snprintf(s, sizeof(s), "[%3d,%3d;%3d,%3d]",
486  dbg->push_back(s);
487  STRING model_string;
488  model_string += static_cast<char>(GetLineType());
489  model_string += ":";
490 
491  int model_numbers = 0;
492  for (int h = 0; h < hypotheses_.size(); h++) {
493  if (hypotheses_[h].model == NULL)
494  continue;
495  if (model_numbers > 0)
496  model_string += ",";
497  if (StrongModel(hypotheses_[h].model)) {
498  model_string += StrOf(1 + theory.IndexOf(hypotheses_[h].model));
499  } else if (hypotheses_[h].model == kCrownLeft) {
500  model_string += "CrL";
501  } else if (hypotheses_[h].model == kCrownRight) {
502  model_string += "CrR";
503  }
504  model_numbers++;
505  }
506  if (model_numbers == 0)
507  model_string += "0";
508 
509  dbg->push_back(model_string);
510 }
511 
513  ri_ = &row;
514  lmargin_ = 0;
515  lindent_ = row.pix_ldistance;
516  rmargin_ = 0;
517  rindent_ = row.pix_rdistance;
518 }
519 
521  if (hypotheses_.empty())
522  return LT_UNKNOWN;
523  bool has_start = false;
524  bool has_body = false;
525  for (int i = 0; i < hypotheses_.size(); i++) {
526  switch (hypotheses_[i].ty) {
527  case LT_START: has_start = true; break;
528  case LT_BODY: has_body = true; break;
529  default:
530  tprintf("Encountered bad value in hypothesis list: %c\n",
531  hypotheses_[i].ty);
532  break;
533  }
534  }
535  if (has_start && has_body)
536  return LT_MULTIPLE;
537  return has_start ? LT_START : LT_BODY;
538 }
539 
541  if (hypotheses_.empty())
542  return LT_UNKNOWN;
543  bool has_start = false;
544  bool has_body = false;
545  for (int i = 0; i < hypotheses_.size(); i++) {
546  if (hypotheses_[i].model != model)
547  continue;
548  switch (hypotheses_[i].ty) {
549  case LT_START: has_start = true; break;
550  case LT_BODY: has_body = true; break;
551  default:
552  tprintf("Encountered bad value in hypothesis list: %c\n",
553  hypotheses_[i].ty);
554  break;
555  }
556  }
557  if (has_start && has_body)
558  return LT_MULTIPLE;
559  return has_start ? LT_START : LT_BODY;
560 }
561 
563  LineType current_lt = GetLineType();
564  if (current_lt != LT_UNKNOWN && current_lt != LT_START) {
565  tprintf("Trying to set a line to be START when it's already BODY.\n");
566  }
567  if (current_lt == LT_UNKNOWN || current_lt == LT_BODY) {
568  hypotheses_.push_back_new(LineHypothesis(LT_START, NULL));
569  }
570 }
571 
573  LineType current_lt = GetLineType();
574  if (current_lt != LT_UNKNOWN && current_lt != LT_BODY) {
575  tprintf("Trying to set a line to be BODY when it's already START.\n");
576  }
577  if (current_lt == LT_UNKNOWN || current_lt == LT_START) {
578  hypotheses_.push_back_new(LineHypothesis(LT_BODY, NULL));
579  }
580 }
581 
583  hypotheses_.push_back_new(LineHypothesis(LT_START, model));
584  int old_idx = hypotheses_.get_index(LineHypothesis(LT_START, NULL));
585  if (old_idx >= 0)
586  hypotheses_.remove(old_idx);
587 }
588 
590  hypotheses_.push_back_new(LineHypothesis(LT_BODY, model));
591  int old_idx = hypotheses_.get_index(LineHypothesis(LT_BODY, NULL));
592  if (old_idx >= 0)
593  hypotheses_.remove(old_idx);
594 }
595 
597  for (int h = 0; h < hypotheses_.size(); h++) {
598  if (hypotheses_[h].ty == LT_START && StrongModel(hypotheses_[h].model))
599  models->push_back_new(hypotheses_[h].model);
600  }
601 }
602 
604  for (int h = 0; h < hypotheses_.size(); h++) {
605  if (StrongModel(hypotheses_[h].model))
606  models->push_back_new(hypotheses_[h].model);
607  }
608 }
609 
611  for (int h = 0; h < hypotheses_.size(); h++) {
612  if (hypotheses_[h].model != NULL)
613  models->push_back_new(hypotheses_[h].model);
614  }
615 }
616 
618  if (hypotheses_.size() != 1 || hypotheses_[0].ty != LT_START)
619  return NULL;
620  return hypotheses_[0].model;
621 }
622 
624  if (hypotheses_.size() != 1 || hypotheses_[0].ty != LT_BODY)
625  return NULL;
626  return hypotheses_[0].model;
627 }
628 
629 // Discard any hypotheses whose model is not in the given list.
631  const SetOfModels &models) {
632  if (models.empty())
633  return;
634  for (int h = hypotheses_.size() - 1; h >= 0; h--) {
635  if (!models.contains(hypotheses_[h].model)) {
636  hypotheses_.remove(h);
637  }
638  }
639 }
640 
641 // ============ Geometry based Paragraph Detection Algorithm =================
642 
643 struct Cluster {
644  Cluster() : center(0), count(0) {}
645  Cluster(int cen, int num) : center(cen), count(num) {}
646 
647  int center; // The center of the cluster.
648  int count; // The number of entries within the cluster.
649 };
650 
652  public:
653  explicit SimpleClusterer(int max_cluster_width)
654  : max_cluster_width_(max_cluster_width) {}
655  void Add(int value) { values_.push_back(value); }
656  int size() const { return values_.size(); }
657  void GetClusters(GenericVector<Cluster> *clusters);
658 
659  private:
660  int max_cluster_width_;
661  GenericVectorEqEq<int> values_;
662 };
663 
664 // Return the index of the cluster closest to value.
665 int ClosestCluster(const GenericVector<Cluster> &clusters, int value) {
666  int best_index = 0;
667  for (int i = 0; i < clusters.size(); i++) {
668  if (abs(value - clusters[i].center) <
669  abs(value - clusters[best_index].center))
670  best_index = i;
671  }
672  return best_index;
673 }
674 
676  clusters->clear();
677  values_.sort();
678  for (int i = 0; i < values_.size();) {
679  int orig_i = i;
680  int lo = values_[i];
681  int hi = lo;
682  while (++i < values_.size() && values_[i] <= lo + max_cluster_width_) {
683  hi = values_[i];
684  }
685  clusters->push_back(Cluster((hi + lo) / 2, i - orig_i));
686  }
687 }
688 
689 // Calculate left- and right-indent tab stop values seen in
690 // rows[row_start, row_end) given a tolerance of tolerance.
692  int row_start, int row_end,
693  int tolerance,
694  GenericVector<Cluster> *left_tabs,
695  GenericVector<Cluster> *right_tabs) {
696  if (!AcceptableRowArgs(0, 1, __func__, rows, row_start, row_end))
697  return;
698  // First pass: toss all left and right indents into clusterers.
699  SimpleClusterer initial_lefts(tolerance);
700  SimpleClusterer initial_rights(tolerance);
701  GenericVector<Cluster> initial_left_tabs;
702  GenericVector<Cluster> initial_right_tabs;
703  for (int i = row_start; i < row_end; i++) {
704  initial_lefts.Add((*rows)[i].lindent_);
705  initial_rights.Add((*rows)[i].rindent_);
706  }
707  initial_lefts.GetClusters(&initial_left_tabs);
708  initial_rights.GetClusters(&initial_right_tabs);
709 
710  // Second pass: cluster only lines that are not "stray"
711  // An example of a stray line is a page number -- a line whose start
712  // and end tab-stops are far outside the typical start and end tab-stops
713  // for the block.
714  // Put another way, we only cluster data from lines whose start or end
715  // tab stop is frequent.
716  SimpleClusterer lefts(tolerance);
717  SimpleClusterer rights(tolerance);
718 
719  // Outlier elimination. We might want to switch this to test outlier-ness
720  // based on how strange a position an outlier is in instead of or in addition
721  // to how rare it is. These outliers get re-added if we end up having too
722  // few tab stops, to work with, however.
723  int infrequent_enough_to_ignore = 0;
724  if (row_end - row_start >= 8) infrequent_enough_to_ignore = 1;
725  if (row_end - row_start >= 20) infrequent_enough_to_ignore = 2;
726 
727  for (int i = row_start; i < row_end; i++) {
728  int lidx = ClosestCluster(initial_left_tabs, (*rows)[i].lindent_);
729  int ridx = ClosestCluster(initial_right_tabs, (*rows)[i].rindent_);
730  if (initial_left_tabs[lidx].count > infrequent_enough_to_ignore ||
731  initial_right_tabs[ridx].count > infrequent_enough_to_ignore) {
732  lefts.Add((*rows)[i].lindent_);
733  rights.Add((*rows)[i].rindent_);
734  }
735  }
736  lefts.GetClusters(left_tabs);
737  rights.GetClusters(right_tabs);
738 
739  if ((left_tabs->size() == 1 && right_tabs->size() >= 4) ||
740  (right_tabs->size() == 1 && left_tabs->size() >= 4)) {
741  // One side is really ragged, and the other only has one tab stop,
742  // so those "insignificant outliers" are probably important, actually.
743  // This often happens on a page of an index. Add back in the ones
744  // we omitted in the first pass.
745  for (int i = row_start; i < row_end; i++) {
746  int lidx = ClosestCluster(initial_left_tabs, (*rows)[i].lindent_);
747  int ridx = ClosestCluster(initial_right_tabs, (*rows)[i].rindent_);
748  if (!(initial_left_tabs[lidx].count > infrequent_enough_to_ignore ||
749  initial_right_tabs[ridx].count > infrequent_enough_to_ignore)) {
750  lefts.Add((*rows)[i].lindent_);
751  rights.Add((*rows)[i].rindent_);
752  }
753  }
754  }
755  lefts.GetClusters(left_tabs);
756  rights.GetClusters(right_tabs);
757 
758  // If one side is almost a two-indent aligned side, and the other clearly
759  // isn't, try to prune out the least frequent tab stop from that side.
760  if (left_tabs->size() == 3 && right_tabs->size() >= 4) {
761  int to_prune = -1;
762  for (int i = left_tabs->size() - 1; i >= 0; i--) {
763  if (to_prune < 0 ||
764  (*left_tabs)[i].count < (*left_tabs)[to_prune].count) {
765  to_prune = i;
766  }
767  }
768  if (to_prune >= 0 &&
769  (*left_tabs)[to_prune].count <= infrequent_enough_to_ignore) {
770  left_tabs->remove(to_prune);
771  }
772  }
773  if (right_tabs->size() == 3 && left_tabs->size() >= 4) {
774  int to_prune = -1;
775  for (int i = right_tabs->size() - 1; i >= 0; i--) {
776  if (to_prune < 0 ||
777  (*right_tabs)[i].count < (*right_tabs)[to_prune].count) {
778  to_prune = i;
779  }
780  }
781  if (to_prune >= 0 &&
782  (*right_tabs)[to_prune].count <= infrequent_enough_to_ignore) {
783  right_tabs->remove(to_prune);
784  }
785  }
786 }
787 
788 // Given a paragraph model mark rows[row_start, row_end) as said model
789 // start or body lines.
790 //
791 // Case 1: model->first_indent_ != model->body_indent_
792 // Differentiating the paragraph start lines from the paragraph body lines in
793 // this case is easy, we just see how far each line is indented.
794 //
795 // Case 2: model->first_indent_ == model->body_indent_
796 // Here, we find end-of-paragraph lines by looking for "short lines."
797 // What constitutes a "short line" changes depending on whether the text
798 // ragged-right[left] or fully justified (aligned left and right).
799 //
800 // Case 2a: Ragged Right (or Left) text. (eop_threshold == 0)
801 // We have a new paragraph it the first word would have at the end
802 // of the previous line.
803 //
804 // Case 2b: Fully Justified. (eop_threshold > 0)
805 // We mark a line as short (end of paragraph) if the offside indent
806 // is greater than eop_threshold.
808  int row_start, int row_end,
809  const ParagraphModel *model,
810  bool ltr,
811  int eop_threshold) {
812  if (!AcceptableRowArgs(0, 0, __func__, rows, row_start, row_end))
813  return;
814  for (int row = row_start; row < row_end; row++) {
815  bool valid_first = ValidFirstLine(rows, row, model);
816  bool valid_body = ValidBodyLine(rows, row, model);
817  if (valid_first && !valid_body) {
818  (*rows)[row].AddStartLine(model);
819  } else if (valid_body && !valid_first) {
820  (*rows)[row].AddBodyLine(model);
821  } else if (valid_body && valid_first) {
822  bool after_eop = (row == row_start);
823  if (row > row_start) {
824  if (eop_threshold > 0) {
825  if (model->justification() == JUSTIFICATION_LEFT) {
826  after_eop = (*rows)[row - 1].rindent_ > eop_threshold;
827  } else {
828  after_eop = (*rows)[row - 1].lindent_ > eop_threshold;
829  }
830  } else {
831  after_eop = FirstWordWouldHaveFit((*rows)[row - 1], (*rows)[row],
832  model->justification());
833  }
834  }
835  if (after_eop) {
836  (*rows)[row].AddStartLine(model);
837  } else {
838  (*rows)[row].AddBodyLine(model);
839  }
840  } else {
841  // Do nothing. Stray row.
842  }
843  }
844 }
845 
846 // GeometricClassifierState holds all of the information we'll use while
847 // trying to determine a paragraph model for the text lines in a block of
848 // text:
849 // + the rows under consideration [row_start, row_end)
850 // + the common left- and right-indent tab stops
851 // + does the block start out left-to-right or right-to-left
852 // Further, this struct holds the data we amass for the (single) ParagraphModel
853 // we'll assign to the text lines (assuming we get that far).
857  int r_start, int r_end)
858  : debug_level(dbg_level), rows(r), row_start(r_start), row_end(r_end),
859  margin(0) {
860  tolerance = InterwordSpace(*r, r_start, r_end);
861  CalculateTabStops(r, r_start, r_end, tolerance,
862  &left_tabs, &right_tabs);
863  if (debug_level >= 3) {
864  tprintf("Geometry: TabStop cluster tolerance = %d; "
865  "%d left tabs; %d right tabs\n",
866  tolerance, left_tabs.size(), right_tabs.size());
867  }
868  ltr = (*r)[r_start].ri_->ltr;
869  }
870 
873  margin = (*rows)[row_start].lmargin_;
874  }
875 
878  margin = (*rows)[row_start].rmargin_;
879  }
880 
881  // Align tabs are the tab stops the text is aligned to.
884  return left_tabs;
885  }
886 
887  // Offside tabs are the tab stops opposite the tabs used to align the text.
888  //
889  // Note that for a left-to-right text which is aligned to the right such as
890  // this function comment, the offside tabs are the horizontal tab stops
891  // marking the beginning of ("Note", "this" and "marking").
894  return right_tabs;
895  }
896 
897  // Return whether the i'th row extends from the leftmost left tab stop
898  // to the right most right tab stop.
899  bool IsFullRow(int i) const {
900  return ClosestCluster(left_tabs, (*rows)[i].lindent_) == 0 &&
901  ClosestCluster(right_tabs, (*rows)[i].rindent_) == 0;
902  }
903 
904  int AlignsideTabIndex(int row_idx) const {
905  return ClosestCluster(AlignTabs(), (*rows)[row_idx].AlignsideIndent(just));
906  }
907 
908  // Given what we know about the paragraph justification (just), would the
909  // first word of row_b have fit at the end of row_a?
910  bool FirstWordWouldHaveFit(int row_a, int row_b) {
912  (*rows)[row_a], (*rows)[row_b], just);
913  }
914 
915  void PrintRows() const { PrintRowRange(*rows, row_start, row_end); }
916 
917  void Fail(int min_debug_level, const char *why) const {
918  if (debug_level < min_debug_level) return;
919  tprintf("# %s\n", why);
920  PrintRows();
921  }
922 
925  }
926 
927  // We print out messages with a debug level at least as great as debug_level.
929 
930  // The Geometric Classifier was asked to find a single paragraph model
931  // to fit the text rows (*rows)[row_start, row_end)
934  int row_end;
935 
936  // The amount by which we expect the text edge can vary and still be aligned.
938 
939  // Is the script in this text block left-to-right?
940  // HORRIBLE ROUGH APPROXIMATION. TODO(eger): Improve
941  bool ltr;
942 
943  // These left and right tab stops were determined to be the common tab
944  // stops for the given text.
947 
948  // These are parameters we must determine to create a ParagraphModel.
950  int margin;
953 
954  // eop_threshold > 0 if the text is fully justified. See MarkRowsWithModel()
956 };
957 
958 // Given a section of text where strong textual clues did not help identifying
959 // paragraph breaks, and for which the left and right indents have exactly
960 // three tab stops between them, attempt to find the paragraph breaks based
961 // solely on the outline of the text and whether the script is left-to-right.
962 //
963 // Algorithm Detail:
964 // The selected rows are in the form of a rectangle except
965 // for some number of "short lines" of the same length:
966 //
967 // (A1) xxxxxxxxxxxxx (B1) xxxxxxxxxxxx
968 // xxxxxxxxxxx xxxxxxxxxx # A "short" line.
969 // xxxxxxxxxxxxx xxxxxxxxxxxx
970 // xxxxxxxxxxxxx xxxxxxxxxxxx
971 //
972 // We have a slightly different situation if the only short
973 // line is at the end of the excerpt.
974 //
975 // (A2) xxxxxxxxxxxxx (B2) xxxxxxxxxxxx
976 // xxxxxxxxxxxxx xxxxxxxxxxxx
977 // xxxxxxxxxxxxx xxxxxxxxxxxx
978 // xxxxxxxxxxx xxxxxxxxxx # A "short" line.
979 //
980 // We'll interpret these as follows based on the reasoning in the comment for
981 // GeometricClassify():
982 // [script direction: first indent, body indent]
983 // (A1) LtR: 2,0 RtL: 0,0 (B1) LtR: 0,0 RtL: 2,0
984 // (A2) LtR: 2,0 RtL: CrR (B2) LtR: CrL RtL: 2,0
986  int debug_level,
988  ParagraphTheory *theory) {
989  int num_rows = s.row_end - s.row_start;
990  int num_full_rows = 0;
991  int last_row_full = 0;
992  for (int i = s.row_start; i < s.row_end; i++) {
993  if (s.IsFullRow(i)) {
994  num_full_rows++;
995  if (i == s.row_end - 1) last_row_full++;
996  }
997  }
998 
999  if (num_full_rows < 0.7 * num_rows) {
1000  s.Fail(1, "Not enough full lines to know which lines start paras.");
1001  return;
1002  }
1003 
1004  // eop_threshold gets set if we're fully justified; see MarkRowsWithModel()
1005  s.eop_threshold = 0;
1006 
1007  if (s.ltr) {
1009  } else {
1011  }
1012 
1013  if (debug_level > 0) {
1014  tprintf("# Not enough variety for clear outline classification. "
1015  "Guessing these are %s aligned based on script.\n",
1016  s.ltr ? "left" : "right");
1017  s.PrintRows();
1018  }
1019 
1020  if (s.AlignTabs().size() == 2) { // case A1 or A2
1021  s.first_indent = s.AlignTabs()[1].center;
1022  s.body_indent = s.AlignTabs()[0].center;
1023  } else { // case B1 or B2
1024  if (num_rows - 1 == num_full_rows - last_row_full) {
1025  // case B2
1026  const ParagraphModel *model = s.ltr ? kCrownLeft : kCrownRight;
1027  (*s.rows)[s.row_start].AddStartLine(model);
1028  for (int i = s.row_start + 1; i < s.row_end; i++) {
1029  (*s.rows)[i].AddBodyLine(model);
1030  }
1031  return;
1032  } else {
1033  // case B1
1034  s.first_indent = s.body_indent = s.AlignTabs()[0].center;
1035  s.eop_threshold = (s.OffsideTabs()[0].center +
1036  s.OffsideTabs()[1].center) / 2;
1037  }
1038  }
1039  const ParagraphModel *model = theory->AddModel(s.Model());
1040  MarkRowsWithModel(s.rows, s.row_start, s.row_end, model,
1041  s.ltr, s.eop_threshold);
1042  return;
1043 }
1044 
1045 // This function is called if strong textual clues were not available, but
1046 // the caller hopes that the paragraph breaks will be super obvious just
1047 // by the outline of the text.
1048 //
1049 // The particularly difficult case is figuring out what's going on if you
1050 // don't have enough short paragraph end lines to tell us what's going on.
1051 //
1052 // For instance, let's say you have the following outline:
1053 //
1054 // (A1) xxxxxxxxxxxxxxxxxxxxxx
1055 // xxxxxxxxxxxxxxxxxxxx
1056 // xxxxxxxxxxxxxxxxxxxxxx
1057 // xxxxxxxxxxxxxxxxxxxxxx
1058 //
1059 // Even if we know that the text is left-to-right and so will probably be
1060 // left-aligned, both of the following are possible texts:
1061 //
1062 // (A1a) 1. Here our list item
1063 // with two full lines.
1064 // 2. Here a second item.
1065 // 3. Here our third one.
1066 //
1067 // (A1b) so ends paragraph one.
1068 // Here starts another
1069 // paragraph we want to
1070 // read. This continues
1071 //
1072 // These examples are obvious from the text and should have been caught
1073 // by the StrongEvidenceClassify pass. However, for languages where we don't
1074 // have capital letters to go on (e.g. Hebrew, Arabic, Hindi, Chinese),
1075 // it's worth guessing that (A1b) is the correct interpretation if there are
1076 // far more "full" lines than "short" lines.
1077 void GeometricClassify(int debug_level,
1079  int row_start, int row_end,
1080  ParagraphTheory *theory) {
1081  if (!AcceptableRowArgs(debug_level, 4, __func__, rows, row_start, row_end))
1082  return;
1083  if (debug_level > 1) {
1084  tprintf("###############################################\n");
1085  tprintf("##### GeometricClassify( rows[%d:%d) ) ####\n",
1086  row_start, row_end);
1087  tprintf("###############################################\n");
1088  }
1089  RecomputeMarginsAndClearHypotheses(rows, row_start, row_end, 10);
1090 
1091  GeometricClassifierState s(debug_level, rows, row_start, row_end);
1092  if (s.left_tabs.size() > 2 && s.right_tabs.size() > 2) {
1093  s.Fail(2, "Too much variety for simple outline classification.");
1094  return;
1095  }
1096  if (s.left_tabs.size() <= 1 && s.right_tabs.size() <= 1) {
1097  s.Fail(1, "Not enough variety for simple outline classification.");
1098  return;
1099  }
1100  if (s.left_tabs.size() + s.right_tabs.size() == 3) {
1101  GeometricClassifyThreeTabStopTextBlock(debug_level, s, theory);
1102  return;
1103  }
1104 
1105  // At this point, we know that one side has at least two tab stops, and the
1106  // other side has one or two tab stops.
1107  // Left to determine:
1108  // (1) Which is the body indent and which is the first line indent?
1109  // (2) Is the text fully justified?
1110 
1111  // If one side happens to have three or more tab stops, assume that side
1112  // is opposite of the aligned side.
1113  if (s.right_tabs.size() > 2) {
1115  } else if (s.left_tabs.size() > 2) {
1117  } else if (s.ltr) { // guess based on script direction
1119  } else {
1121  }
1122 
1123  if (s.AlignTabs().size() == 2) {
1124  // For each tab stop on the aligned side, how many of them appear
1125  // to be paragraph start lines? [first lines]
1126  int firsts[2] = {0, 0};
1127  // Count the first line as a likely paragraph start line.
1128  firsts[s.AlignsideTabIndex(s.row_start)]++;
1129  // For each line, if the first word would have fit on the previous
1130  // line count it as a likely paragraph start line.
1131  bool jam_packed = true;
1132  for (int i = s.row_start + 1; i < s.row_end; i++) {
1133  if (s.FirstWordWouldHaveFit(i - 1, i)) {
1134  firsts[s.AlignsideTabIndex(i)]++;
1135  jam_packed = false;
1136  }
1137  }
1138  // Make an extra accounting for the last line of the paragraph just
1139  // in case it's the only short line in the block. That is, take its
1140  // first word as typical and see if this looks like the *last* line
1141  // of a paragraph. If so, mark the *other* indent as probably a first.
1142  if (jam_packed && s.FirstWordWouldHaveFit(s.row_end - 1, s.row_end - 1)) {
1143  firsts[1 - s.AlignsideTabIndex(s.row_end - 1)]++;
1144  }
1145 
1146  int percent0firsts, percent1firsts;
1147  percent0firsts = (100 * firsts[0]) / s.AlignTabs()[0].count;
1148  percent1firsts = (100 * firsts[1]) / s.AlignTabs()[1].count;
1149 
1150  // TODO(eger): Tune these constants if necessary.
1151  if ((percent0firsts < 20 && 30 < percent1firsts) ||
1152  percent0firsts + 30 < percent1firsts) {
1153  s.first_indent = s.AlignTabs()[1].center;
1154  s.body_indent = s.AlignTabs()[0].center;
1155  } else if ((percent1firsts < 20 && 30 < percent0firsts) ||
1156  percent1firsts + 30 < percent0firsts) {
1157  s.first_indent = s.AlignTabs()[0].center;
1158  s.body_indent = s.AlignTabs()[1].center;
1159  } else {
1160  // Ambiguous! Probably lineated (poetry)
1161  if (debug_level > 1) {
1162  tprintf("# Cannot determine %s indent likely to start paragraphs.\n",
1163  s.just == tesseract::JUSTIFICATION_LEFT ? "left" : "right");
1164  tprintf("# Indent of %d looks like a first line %d%% of the time.\n",
1165  s.AlignTabs()[0].center, percent0firsts);
1166  tprintf("# Indent of %d looks like a first line %d%% of the time.\n",
1167  s.AlignTabs()[1].center, percent1firsts);
1168  s.PrintRows();
1169  }
1170  return;
1171  }
1172  } else {
1173  // There's only one tab stop for the "aligned to" side.
1174  s.first_indent = s.body_indent = s.AlignTabs()[0].center;
1175  }
1176 
1177  // At this point, we have our model.
1178  const ParagraphModel *model = theory->AddModel(s.Model());
1179 
1180  // Now all we have to do is figure out if the text is fully justified or not.
1181  // eop_threshold: default to fully justified unless we see evidence below.
1182  // See description on MarkRowsWithModel()
1183  s.eop_threshold =
1184  (s.OffsideTabs()[0].center + s.OffsideTabs()[1].center) / 2;
1185  // If the text is not fully justified, re-set the eop_threshold to 0.
1186  if (s.AlignTabs().size() == 2) {
1187  // Paragraphs with a paragraph-start indent.
1188  for (int i = s.row_start; i < s.row_end - 1; i++) {
1189  if (ValidFirstLine(s.rows, i + 1, model) &&
1190  !NearlyEqual(s.OffsideTabs()[0].center,
1191  (*s.rows)[i].OffsideIndent(s.just), s.tolerance)) {
1192  // We found a non-end-of-paragraph short line: not fully justified.
1193  s.eop_threshold = 0;
1194  break;
1195  }
1196  }
1197  } else {
1198  // Paragraphs with no paragraph-start indent.
1199  for (int i = s.row_start; i < s.row_end - 1; i++) {
1200  if (!s.FirstWordWouldHaveFit(i, i + 1) &&
1201  !NearlyEqual(s.OffsideTabs()[0].center,
1202  (*s.rows)[i].OffsideIndent(s.just), s.tolerance)) {
1203  // We found a non-end-of-paragraph short line: not fully justified.
1204  s.eop_threshold = 0;
1205  break;
1206  }
1207  }
1208  }
1209  MarkRowsWithModel(rows, row_start, row_end, model, s.ltr, s.eop_threshold);
1210 }
1211 
1212 // =============== Implementation of ParagraphTheory =====================
1213 
1215  for (int i = 0; i < models_->size(); i++) {
1216  if ((*models_)[i]->Comparable(model))
1217  return (*models_)[i];
1218  }
1219  ParagraphModel *m = new ParagraphModel(model);
1220  models_->push_back(m);
1221  models_we_added_.push_back_new(m);
1222  return m;
1223 }
1224 
1226  for (int i = models_->size() - 1; i >= 0; i--) {
1227  ParagraphModel *m = (*models_)[i];
1228  if (!used_models.contains(m) && models_we_added_.contains(m)) {
1229  models_->remove(i);
1230  models_we_added_.remove(models_we_added_.get_index(m));
1231  delete m;
1232  }
1233  }
1234 }
1235 
1236 // Examine rows[start, end) and try to determine if an existing non-centered
1237 // paragraph model would fit them perfectly. If so, return a pointer to it.
1238 // If not, return NULL.
1240  const GenericVector<RowScratchRegisters> *rows, int start, int end) const {
1241  for (int m = 0; m < models_->size(); m++) {
1242  const ParagraphModel *model = (*models_)[m];
1243  if (model->justification() != JUSTIFICATION_CENTER &&
1244  RowsFitModel(rows, start, end, model))
1245  return model;
1246  }
1247  return NULL;
1248 }
1249 
1251  for (int m = 0; m < models_->size(); m++) {
1252  const ParagraphModel *model = (*models_)[m];
1253  if (model->justification() != JUSTIFICATION_CENTER)
1254  models->push_back_new(model);
1255  }
1256 }
1257 
1258 int ParagraphTheory::IndexOf(const ParagraphModel *model) const {
1259  for (int i = 0; i < models_->size(); i++) {
1260  if ((*models_)[i] == model)
1261  return i;
1262  }
1263  return -1;
1264 }
1265 
1267  int row, const ParagraphModel *model) {
1268  if (!StrongModel(model)) {
1269  tprintf("ValidFirstLine() should only be called with strong models!\n");
1270  }
1271  return StrongModel(model) &&
1272  model->ValidFirstLine(
1273  (*rows)[row].lmargin_, (*rows)[row].lindent_,
1274  (*rows)[row].rindent_, (*rows)[row].rmargin_);
1275 }
1276 
1278  int row, const ParagraphModel *model) {
1279  if (!StrongModel(model)) {
1280  tprintf("ValidBodyLine() should only be called with strong models!\n");
1281  }
1282  return StrongModel(model) &&
1283  model->ValidBodyLine(
1284  (*rows)[row].lmargin_, (*rows)[row].lindent_,
1285  (*rows)[row].rindent_, (*rows)[row].rmargin_);
1286 }
1287 
1289  int a, int b, const ParagraphModel *model) {
1290  if (model != kCrownRight && model != kCrownLeft) {
1291  tprintf("CrownCompatible() should only be called with crown models!\n");
1292  return false;
1293  }
1294  RowScratchRegisters &row_a = (*rows)[a];
1295  RowScratchRegisters &row_b = (*rows)[b];
1296  if (model == kCrownRight) {
1297  return NearlyEqual(row_a.rindent_ + row_a.rmargin_,
1298  row_b.rindent_ + row_b.rmargin_,
1299  Epsilon(row_a.ri_->average_interword_space));
1300  }
1301  return NearlyEqual(row_a.lindent_ + row_a.lmargin_,
1302  row_b.lindent_ + row_b.lmargin_,
1303  Epsilon(row_a.ri_->average_interword_space));
1304 }
1305 
1306 
1307 // =============== Implementation of ParagraphModelSmearer ====================
1308 
1311  int row_start, int row_end, ParagraphTheory *theory)
1312  : theory_(theory), rows_(rows), row_start_(row_start),
1313  row_end_(row_end) {
1314  if (!AcceptableRowArgs(0, 0, __func__, rows, row_start, row_end)) {
1315  row_start_ = 0;
1316  row_end_ = 0;
1317  return;
1318  }
1319  SetOfModels no_models;
1320  for (int row = row_start - 1; row <= row_end; row++) {
1321  open_models_.push_back(no_models);
1322  }
1323 }
1324 
1325 // see paragraphs_internal.h
1326 void ParagraphModelSmearer::CalculateOpenModels(int row_start, int row_end) {
1327  SetOfModels no_models;
1328  if (row_start < row_start_) row_start = row_start_;
1329  if (row_end > row_end_) row_end = row_end_;
1330 
1331  for (int row = (row_start > 0) ? row_start - 1 : row_start; row < row_end;
1332  row++) {
1333  if ((*rows_)[row].ri_->num_words == 0) {
1334  OpenModels(row + 1) = no_models;
1335  } else {
1336  SetOfModels &opened = OpenModels(row);
1337  (*rows_)[row].StartHypotheses(&opened);
1338 
1339  // Which models survive the transition from row to row + 1?
1340  SetOfModels still_open;
1341  for (int m = 0; m < opened.size(); m++) {
1342  if (ValidFirstLine(rows_, row, opened[m]) ||
1343  ValidBodyLine(rows_, row, opened[m])) {
1344  // This is basic filtering; we check likely paragraph starty-ness down
1345  // below in Smear() -- you know, whether the first word would have fit
1346  // and such.
1347  still_open.push_back_new(opened[m]);
1348  }
1349  }
1350  OpenModels(row + 1) = still_open;
1351  }
1352  }
1353 }
1354 
1355 // see paragraphs_internal.h
1357  CalculateOpenModels(row_start_, row_end_);
1358 
1359  // For each row which we're unsure about (that is, it is LT_UNKNOWN or
1360  // we have multiple LT_START hypotheses), see if there's a model that
1361  // was recently used (an "open" model) which might model it well.
1362  for (int i = row_start_; i < row_end_; i++) {
1363  RowScratchRegisters &row = (*rows_)[i];
1364  if (row.ri_->num_words == 0)
1365  continue;
1366 
1367  // Step One:
1368  // Figure out if there are "open" models which are left-alined or
1369  // right-aligned. This is important for determining whether the
1370  // "first" word in a row would fit at the "end" of the previous row.
1371  bool left_align_open = false;
1372  bool right_align_open = false;
1373  for (int m = 0; m < OpenModels(i).size(); m++) {
1374  switch (OpenModels(i)[m]->justification()) {
1375  case JUSTIFICATION_LEFT: left_align_open = true; break;
1376  case JUSTIFICATION_RIGHT: right_align_open = true; break;
1377  default: left_align_open = right_align_open = true;
1378  }
1379  }
1380  // Step Two:
1381  // Use that knowledge to figure out if this row is likely to
1382  // start a paragraph.
1383  bool likely_start;
1384  if (i == 0) {
1385  likely_start = true;
1386  } else {
1387  if ((left_align_open && right_align_open) ||
1388  (!left_align_open && !right_align_open)) {
1389  likely_start = LikelyParagraphStart((*rows_)[i - 1], row,
1390  JUSTIFICATION_LEFT) ||
1391  LikelyParagraphStart((*rows_)[i - 1], row,
1393  } else if (left_align_open) {
1394  likely_start = LikelyParagraphStart((*rows_)[i - 1], row,
1396  } else {
1397  likely_start = LikelyParagraphStart((*rows_)[i - 1], row,
1399  }
1400  }
1401 
1402  // Step Three:
1403  // If this text line seems like an obvious first line of an
1404  // open model, or an obvious continuation of an existing
1405  // modelled paragraph, mark it up.
1406  if (likely_start) {
1407  // Add Start Hypotheses for all Open models that fit.
1408  for (int m = 0; m < OpenModels(i).size(); m++) {
1409  if (ValidFirstLine(rows_, i, OpenModels(i)[m])) {
1410  row.AddStartLine(OpenModels(i)[m]);
1411  }
1412  }
1413  } else {
1414  // Add relevant body line hypotheses.
1415  SetOfModels last_line_models;
1416  if (i > 0) {
1417  (*rows_)[i - 1].StrongHypotheses(&last_line_models);
1418  } else {
1419  theory_->NonCenteredModels(&last_line_models);
1420  }
1421  for (int m = 0; m < last_line_models.size(); m++) {
1422  const ParagraphModel *model = last_line_models[m];
1423  if (ValidBodyLine(rows_, i, model))
1424  row.AddBodyLine(model);
1425  }
1426  }
1427 
1428  // Step Four:
1429  // If we're still quite unsure about this line, go through all
1430  // models in our theory and see if this row could be the start
1431  // of any of our models.
1432  if (row.GetLineType() == LT_UNKNOWN ||
1433  (row.GetLineType() == LT_START && !row.UniqueStartHypothesis())) {
1434  SetOfModels all_models;
1435  theory_->NonCenteredModels(&all_models);
1436  for (int m = 0; m < all_models.size(); m++) {
1437  if (ValidFirstLine(rows_, i, all_models[m])) {
1438  row.AddStartLine(all_models[m]);
1439  }
1440  }
1441  }
1442  // Step Five:
1443  // Since we may have updated the hypotheses about this row, we need
1444  // to recalculate the Open models for the rest of rows[i + 1, row_end)
1445  if (row.GetLineType() != LT_UNKNOWN) {
1446  CalculateOpenModels(i + 1, row_end_);
1447  }
1448  }
1449 }
1450 
1451 // ================ Main Paragraph Detection Algorithm =======================
1452 
1453 // Find out what ParagraphModels are actually used, and discard any
1454 // that are not.
1456  ParagraphTheory *theory) {
1457  SetOfModels used_models;
1458  for (int i = 0; i < rows.size(); i++) {
1459  rows[i].StrongHypotheses(&used_models);
1460  }
1461  theory->DiscardUnusedModels(used_models);
1462 }
1463 
1464 // DowngradeWeakestToCrowns:
1465 // Forget any flush-{left, right} models unless we see two or more
1466 // of them in sequence.
1467 //
1468 // In pass 3, we start to classify even flush-left paragraphs (paragraphs
1469 // where the first line and body indent are the same) as having proper Models.
1470 // This is generally dangerous, since if you start imagining that flush-left
1471 // is a typical paragraph model when it is not, it will lead you to chop normal
1472 // indented paragraphs in the middle whenever a sentence happens to start on a
1473 // new line (see "This" above). What to do?
1474 // What we do is to take any paragraph which is flush left and is not
1475 // preceded by another paragraph of the same model and convert it to a "Crown"
1476 // paragraph. This is a weak pseudo-ParagraphModel which is a placeholder
1477 // for later. It means that the paragraph is flush, but it would be desirable
1478 // to mark it as the same model as following text if it fits. This downgrade
1479 // FlushLeft -> CrownLeft -> Model of following paragraph. Means that we
1480 // avoid making flush left Paragraph Models whenever we see a top-of-the-page
1481 // half-of-a-paragraph. and instead we mark it the same as normal body text.
1482 //
1483 // Implementation:
1484 //
1485 // Comb backwards through the row scratch registers, and turn any
1486 // sequences of body lines of equivalent type abutted against the beginning
1487 // or a body or start line of a different type into a crown paragraph.
1488 void DowngradeWeakestToCrowns(int debug_level,
1489  ParagraphTheory *theory,
1491  int start;
1492  for (int end = rows->size(); end > 0; end = start) {
1493  // Search back for a body line of a unique type.
1494  const ParagraphModel *model = NULL;
1495  while (end > 0 &&
1496  (model = (*rows)[end - 1].UniqueBodyHypothesis()) == NULL) {
1497  end--;
1498  }
1499  if (end == 0) break;
1500  start = end - 1;
1501  while (start >= 0 && (*rows)[start].UniqueBodyHypothesis() == model) {
1502  start--; // walk back to the first line that is not the same body type.
1503  }
1504  if (start >= 0 && (*rows)[start].UniqueStartHypothesis() == model &&
1505  StrongModel(model) &&
1506  NearlyEqual(model->first_indent(), model->body_indent(),
1507  model->tolerance())) {
1508  start--;
1509  }
1510  start++;
1511  // Now rows[start, end) is a sequence of unique body hypotheses of model.
1512  if (StrongModel(model) && model->justification() == JUSTIFICATION_CENTER)
1513  continue;
1514  if (!StrongModel(model)) {
1515  while (start > 0 &&
1516  CrownCompatible(rows, start - 1, start, model))
1517  start--;
1518  }
1519  if (start == 0 ||
1520  (!StrongModel(model)) ||
1521  (StrongModel(model) && !ValidFirstLine(rows, start - 1, model))) {
1522  // crownify rows[start, end)
1523  const ParagraphModel *crown_model = model;
1524  if (StrongModel(model)) {
1525  if (model->justification() == JUSTIFICATION_LEFT)
1526  crown_model = kCrownLeft;
1527  else
1528  crown_model = kCrownRight;
1529  }
1530  (*rows)[start].SetUnknown();
1531  (*rows)[start].AddStartLine(crown_model);
1532  for (int row = start + 1; row < end; row++) {
1533  (*rows)[row].SetUnknown();
1534  (*rows)[row].AddBodyLine(crown_model);
1535  }
1536  }
1537  }
1538  DiscardUnusedModels(*rows, theory);
1539 }
1540 
1541 
1542 // Clear all hypotheses about lines [start, end) and reset margins.
1543 //
1544 // The empty space between the left of a row and the block boundary (and
1545 // similarly for the right) is split into two pieces: margin and indent.
1546 // In initial processing, we assume the block is tight and the margin for
1547 // all lines is set to zero. However, if our first pass does not yield
1548 // models for everything, it may be due to an inset paragraph like a
1549 // block-quote. In that case, we make a second pass over that unmarked
1550 // section of the page and reset the "margin" portion of the empty space
1551 // to the common amount of space at the ends of the lines under consid-
1552 // eration. This would be equivalent to percentile set to 0. However,
1553 // sometimes we have a single character sticking out in the right margin
1554 // of a text block (like the 'r' in 'for' on line 3 above), and we can
1555 // really just ignore it as an outlier. To express this, we allow the
1556 // user to specify the percentile (0..100) of indent values to use as
1557 // the common margin for each row in the run of rows[start, end).
1559  GenericVector<RowScratchRegisters> *rows, int start, int end,
1560  int percentile) {
1561  if (!AcceptableRowArgs(0, 0, __func__, rows, start, end))
1562  return;
1563 
1564  int lmin, lmax, rmin, rmax;
1565  lmin = lmax = (*rows)[start].lmargin_ + (*rows)[start].lindent_;
1566  rmin = rmax = (*rows)[start].rmargin_ + (*rows)[start].rindent_;
1567  for (int i = start; i < end; i++) {
1568  RowScratchRegisters &sr = (*rows)[i];
1569  sr.SetUnknown();
1570  if (sr.ri_->num_words == 0)
1571  continue;
1572  UpdateRange(sr.lmargin_ + sr.lindent_, &lmin, &lmax);
1573  UpdateRange(sr.rmargin_ + sr.rindent_, &rmin, &rmax);
1574  }
1575  STATS lefts(lmin, lmax + 1);
1576  STATS rights(rmin, rmax + 1);
1577  for (int i = start; i < end; i++) {
1578  RowScratchRegisters &sr = (*rows)[i];
1579  if (sr.ri_->num_words == 0)
1580  continue;
1581  lefts.add(sr.lmargin_ + sr.lindent_, 1);
1582  rights.add(sr.rmargin_ + sr.rindent_, 1);
1583  }
1584  int ignorable_left = lefts.ile(ClipToRange(percentile, 0, 100) / 100.0);
1585  int ignorable_right = rights.ile(ClipToRange(percentile, 0, 100) / 100.0);
1586  for (int i = start; i < end; i++) {
1587  RowScratchRegisters &sr = (*rows)[i];
1588  int ldelta = ignorable_left - sr.lmargin_;
1589  sr.lmargin_ += ldelta;
1590  sr.lindent_ -= ldelta;
1591  int rdelta = ignorable_right - sr.rmargin_;
1592  sr.rmargin_ += rdelta;
1593  sr.rindent_ -= rdelta;
1594  }
1595 }
1596 
1597 // Return the median inter-word space in rows[row_start, row_end).
1599  int row_start, int row_end) {
1600  if (row_end < row_start + 1) return 1;
1601  int word_height = (rows[row_start].ri_->lword_box.height() +
1602  rows[row_end - 1].ri_->lword_box.height()) / 2;
1603  int word_width = (rows[row_start].ri_->lword_box.width() +
1604  rows[row_end - 1].ri_->lword_box.width()) / 2;
1605  STATS spacing_widths(0, 5 + word_width);
1606  for (int i = row_start; i < row_end; i++) {
1607  if (rows[i].ri_->num_words > 1) {
1608  spacing_widths.add(rows[i].ri_->average_interword_space, 1);
1609  }
1610  }
1611  int minimum_reasonable_space = word_height / 3;
1612  if (minimum_reasonable_space < 2)
1613  minimum_reasonable_space = 2;
1614  int median = spacing_widths.median();
1615  return (median > minimum_reasonable_space)
1616  ? median : minimum_reasonable_space;
1617 }
1618 
1619 // Return whether the first word on the after line can fit in the space at
1620 // the end of the before line (knowing which way the text is aligned and read).
1622  const RowScratchRegisters &after,
1623  tesseract::ParagraphJustification justification) {
1624  if (before.ri_->num_words == 0 || after.ri_->num_words == 0)
1625  return true;
1626 
1627  if (justification == JUSTIFICATION_UNKNOWN) {
1628  tprintf("Don't call FirstWordWouldHaveFit(r, s, JUSTIFICATION_UNKNOWN).\n");
1629  }
1630  int available_space;
1631  if (justification == JUSTIFICATION_CENTER) {
1632  available_space = before.lindent_ + before.rindent_;
1633  } else {
1634  available_space = before.OffsideIndent(justification);
1635  }
1636  available_space -= before.ri_->average_interword_space;
1637 
1638  if (before.ri_->ltr)
1639  return after.ri_->lword_box.width() < available_space;
1640  return after.ri_->rword_box.width() < available_space;
1641 }
1642 
1643 // Return whether the first word on the after line can fit in the space at
1644 // the end of the before line (not knowing which way the text goes) in a left
1645 // or right alignemnt.
1647  const RowScratchRegisters &after) {
1648  if (before.ri_->num_words == 0 || after.ri_->num_words == 0)
1649  return true;
1650 
1651  int available_space = before.lindent_;
1652  if (before.rindent_ > available_space)
1653  available_space = before.rindent_;
1654  available_space -= before.ri_->average_interword_space;
1655 
1656  if (before.ri_->ltr)
1657  return after.ri_->lword_box.width() < available_space;
1658  return after.ri_->rword_box.width() < available_space;
1659 }
1660 
1662  const RowScratchRegisters &after) {
1663  if (before.ri_->ltr) {
1664  return before.ri_->rword_likely_ends_idea &&
1666  } else {
1667  return before.ri_->lword_likely_ends_idea &&
1669  }
1670 }
1671 
1673  const RowScratchRegisters &after) {
1674  return before.ri_->num_words == 0 ||
1675  (FirstWordWouldHaveFit(before, after) &&
1676  TextSupportsBreak(before, after));
1677 }
1678 
1680  const RowScratchRegisters &after,
1682  return before.ri_->num_words == 0 ||
1683  (FirstWordWouldHaveFit(before, after, j) &&
1684  TextSupportsBreak(before, after));
1685 }
1686 
1687 // Examine rows[start, end) and try to determine what sort of ParagraphModel
1688 // would fit them as a single paragraph.
1689 // If we can't produce a unique model justification_ = JUSTIFICATION_UNKNOWN.
1690 // If the rows given could be a consistent start to a paragraph, set *consistent
1691 // true.
1694  int start, int end, int tolerance, bool *consistent) {
1695  int ltr_line_count = 0;
1696  for (int i = start; i < end; i++) {
1697  ltr_line_count += static_cast<int>((*rows)[i].ri_->ltr);
1698  }
1699  bool ltr = (ltr_line_count >= (end - start) / 2);
1700 
1701  *consistent = true;
1702  if (!AcceptableRowArgs(0, 2, __func__, rows, start, end))
1703  return ParagraphModel();
1704 
1705  // Ensure the caller only passed us a region with a common rmargin and
1706  // lmargin.
1707  int lmargin = (*rows)[start].lmargin_;
1708  int rmargin = (*rows)[start].rmargin_;
1709  int lmin, lmax, rmin, rmax, cmin, cmax;
1710  lmin = lmax = (*rows)[start + 1].lindent_;
1711  rmin = rmax = (*rows)[start + 1].rindent_;
1712  cmin = cmax = 0;
1713  for (int i = start + 1; i < end; i++) {
1714  if ((*rows)[i].lmargin_ != lmargin || (*rows)[i].rmargin_ != rmargin) {
1715  tprintf("Margins don't match! Software error.\n");
1716  *consistent = false;
1717  return ParagraphModel();
1718  }
1719  UpdateRange((*rows)[i].lindent_, &lmin, &lmax);
1720  UpdateRange((*rows)[i].rindent_, &rmin, &rmax);
1721  UpdateRange((*rows)[i].rindent_ - (*rows)[i].lindent_, &cmin, &cmax);
1722  }
1723  int ldiff = lmax - lmin;
1724  int rdiff = rmax - rmin;
1725  int cdiff = cmax - cmin;
1726  if (rdiff > tolerance && ldiff > tolerance) {
1727  if (cdiff < tolerance * 2) {
1728  if (end - start < 3)
1729  return ParagraphModel();
1730  return ParagraphModel(JUSTIFICATION_CENTER, 0, 0, 0, tolerance);
1731  }
1732  *consistent = false;
1733  return ParagraphModel();
1734  }
1735  if (end - start < 3) // Don't return a model for two line paras.
1736  return ParagraphModel();
1737 
1738  // These booleans keep us from saying something is aligned left when the body
1739  // left variance is too large.
1740  bool body_admits_left_alignment = ldiff < tolerance;
1741  bool body_admits_right_alignment = rdiff < tolerance;
1742 
1743  ParagraphModel left_model =
1744  ParagraphModel(JUSTIFICATION_LEFT, lmargin, (*rows)[start].lindent_,
1745  (lmin + lmax) / 2, tolerance);
1746  ParagraphModel right_model =
1747  ParagraphModel(JUSTIFICATION_RIGHT, rmargin, (*rows)[start].rindent_,
1748  (rmin + rmax) / 2, tolerance);
1749 
1750  // These booleans keep us from having an indent on the "wrong side" for the
1751  // first line.
1752  bool text_admits_left_alignment = ltr || left_model.is_flush();
1753  bool text_admits_right_alignment = !ltr || right_model.is_flush();
1754 
1755  // At least one of the edges is less than tolerance in variance.
1756  // If the other is obviously ragged, it can't be the one aligned to.
1757  // [Note the last line is included in this raggedness.]
1758  if (tolerance < rdiff) {
1759  if (body_admits_left_alignment && text_admits_left_alignment)
1760  return left_model;
1761  *consistent = false;
1762  return ParagraphModel();
1763  }
1764  if (tolerance < ldiff) {
1765  if (body_admits_right_alignment && text_admits_right_alignment)
1766  return right_model;
1767  *consistent = false;
1768  return ParagraphModel();
1769  }
1770 
1771  // At this point, we know the body text doesn't vary much on either side.
1772 
1773  // If the first line juts out oddly in one direction or the other,
1774  // that likely indicates the side aligned to.
1775  int first_left = (*rows)[start].lindent_;
1776  int first_right = (*rows)[start].rindent_;
1777 
1778  if (ltr && body_admits_left_alignment &&
1779  (first_left < lmin || first_left > lmax))
1780  return left_model;
1781  if (!ltr && body_admits_right_alignment &&
1782  (first_right < rmin || first_right > rmax))
1783  return right_model;
1784 
1785  *consistent = false;
1786  return ParagraphModel();
1787 }
1788 
1789 // Examine rows[start, end) and try to determine what sort of ParagraphModel
1790 // would fit them as a single paragraph. If nothing fits,
1791 // justification_ = JUSTIFICATION_UNKNOWN and print the paragraph to debug
1792 // output if we're debugging.
1794  int debug_level,
1796  int start, int end, int tolerance) {
1797  bool unused_consistent;
1799  rows, start, end, tolerance, &unused_consistent);
1800  if (debug_level >= 2 && retval.justification() == JUSTIFICATION_UNKNOWN) {
1801  tprintf("Could not determine a model for this paragraph:\n");
1802  PrintRowRange(*rows, start, end);
1803  }
1804  return retval;
1805 }
1806 
1807 // Do rows[start, end) form a single instance of the given paragraph model?
1809  int start, int end, const ParagraphModel *model) {
1810  if (!AcceptableRowArgs(0, 1, __func__, rows, start, end))
1811  return false;
1812  if (!ValidFirstLine(rows, start, model)) return false;
1813  for (int i = start + 1 ; i < end; i++) {
1814  if (!ValidBodyLine(rows, i, model)) return false;
1815  }
1816  return true;
1817 }
1818 
1819 // Examine rows[row_start, row_end) as an independent section of text,
1820 // and mark rows that are exceptionally clear as start-of-paragraph
1821 // and paragraph-body lines.
1822 //
1823 // We presume that any lines surrounding rows[row_start, row_end) may
1824 // have wildly different paragraph models, so we don't key any data off
1825 // of those lines.
1826 //
1827 // We only take the very strongest signals, as we don't want to get
1828 // confused and marking up centered text, poetry, or source code as
1829 // clearly part of a typical paragraph.
1831  int row_start, int row_end) {
1832  // Record patently obvious body text.
1833  for (int i = row_start + 1; i < row_end; i++) {
1834  const RowScratchRegisters &prev = (*rows)[i - 1];
1835  RowScratchRegisters &curr = (*rows)[i];
1836  tesseract::ParagraphJustification typical_justification =
1838  if (!curr.ri_->rword_likely_starts_idea &&
1839  !curr.ri_->lword_likely_starts_idea &&
1840  !FirstWordWouldHaveFit(prev, curr, typical_justification)) {
1841  curr.SetBodyLine();
1842  }
1843  }
1844 
1845  // Record patently obvious start paragraph lines.
1846  //
1847  // It's an extremely good signal of the start of a paragraph that
1848  // the first word would have fit on the end of the previous line.
1849  // However, applying just that signal would have us mark random
1850  // start lines of lineated text (poetry and source code) and some
1851  // centered headings as paragraph start lines. Therefore, we use
1852  // a second qualification for a paragraph start: Not only should
1853  // the first word of this line have fit on the previous line,
1854  // but also, this line should go full to the right of the block,
1855  // disallowing a subsequent word from having fit on this line.
1856 
1857  // First row:
1858  {
1859  RowScratchRegisters &curr = (*rows)[row_start];
1860  RowScratchRegisters &next = (*rows)[row_start + 1];
1863  if (curr.GetLineType() == LT_UNKNOWN &&
1864  !FirstWordWouldHaveFit(curr, next, j) &&
1865  (curr.ri_->lword_likely_starts_idea ||
1866  curr.ri_->rword_likely_starts_idea)) {
1867  curr.SetStartLine();
1868  }
1869  }
1870  // Middle rows
1871  for (int i = row_start + 1; i < row_end - 1; i++) {
1872  RowScratchRegisters &prev = (*rows)[i - 1];
1873  RowScratchRegisters &curr = (*rows)[i];
1874  RowScratchRegisters &next = (*rows)[i + 1];
1877  if (curr.GetLineType() == LT_UNKNOWN &&
1878  !FirstWordWouldHaveFit(curr, next, j) &&
1879  LikelyParagraphStart(prev, curr, j)) {
1880  curr.SetStartLine();
1881  }
1882  }
1883  // Last row
1884  { // the short circuit at the top means we have at least two lines.
1885  RowScratchRegisters &prev = (*rows)[row_end - 2];
1886  RowScratchRegisters &curr = (*rows)[row_end - 1];
1889  if (curr.GetLineType() == LT_UNKNOWN &&
1890  !FirstWordWouldHaveFit(curr, curr, j) &&
1891  LikelyParagraphStart(prev, curr, j)) {
1892  curr.SetStartLine();
1893  }
1894  }
1895 }
1896 
1897 // Look for sequences of a start line followed by some body lines in
1898 // rows[row_start, row_end) and create ParagraphModels for them if
1899 // they seem coherent.
1900 void ModelStrongEvidence(int debug_level,
1902  int row_start, int row_end,
1903  bool allow_flush_models,
1904  ParagraphTheory *theory) {
1905  if (!AcceptableRowArgs(debug_level, 2, __func__, rows, row_start, row_end))
1906  return;
1907 
1908  int start = row_start;
1909  while (start < row_end) {
1910  while (start < row_end && (*rows)[start].GetLineType() != LT_START)
1911  start++;
1912  if (start >= row_end - 1)
1913  break;
1914 
1915  int tolerance = Epsilon((*rows)[start + 1].ri_->average_interword_space);
1916  int end = start;
1917  ParagraphModel last_model;
1918  bool next_consistent;
1919  do {
1920  ++end;
1921  // rows[row, end) was consistent.
1922  // If rows[row, end + 1) is not consistent,
1923  // just model rows[row, end)
1924  if (end < row_end - 1) {
1925  RowScratchRegisters &next = (*rows)[end];
1926  LineType lt = next.GetLineType();
1927  next_consistent = lt == LT_BODY ||
1928  (lt == LT_UNKNOWN &&
1929  !FirstWordWouldHaveFit((*rows)[end - 1], (*rows)[end]));
1930  } else {
1931  next_consistent = false;
1932  }
1933  if (next_consistent) {
1935  rows, start, end + 1, tolerance, &next_consistent);
1936  if (((*rows)[start].ri_->ltr &&
1937  last_model.justification() == JUSTIFICATION_LEFT &&
1938  next_model.justification() != JUSTIFICATION_LEFT) ||
1939  (!(*rows)[start].ri_->ltr &&
1940  last_model.justification() == JUSTIFICATION_RIGHT &&
1941  next_model.justification() != JUSTIFICATION_RIGHT)) {
1942  next_consistent = false;
1943  }
1944  last_model = next_model;
1945  } else {
1946  next_consistent = false;
1947  }
1948  } while (next_consistent && end < row_end);
1949  // At this point, rows[start, end) looked like it could have been a
1950  // single paragraph. If we can make a good ParagraphModel for it,
1951  // do so and mark this sequence with that model.
1952  if (end > start + 1) {
1953  // emit a new paragraph if we have more than one line.
1954  const ParagraphModel *model = NULL;
1956  debug_level, rows, start, end,
1957  Epsilon(InterwordSpace(*rows, start, end)));
1958  if (new_model.justification() == JUSTIFICATION_UNKNOWN) {
1959  // couldn't create a good model, oh well.
1960  } else if (new_model.is_flush()) {
1961  if (end == start + 2) {
1962  // It's very likely we just got two paragraph starts in a row.
1963  end = start + 1;
1964  } else if (start == row_start) {
1965  // Mark this as a Crown.
1966  if (new_model.justification() == JUSTIFICATION_LEFT) {
1967  model = kCrownLeft;
1968  } else {
1969  model = kCrownRight;
1970  }
1971  } else if (allow_flush_models) {
1972  model = theory->AddModel(new_model);
1973  }
1974  } else {
1975  model = theory->AddModel(new_model);
1976  }
1977  if (model) {
1978  (*rows)[start].AddStartLine(model);
1979  for (int i = start + 1; i < end; i++) {
1980  (*rows)[i].AddBodyLine(model);
1981  }
1982  }
1983  }
1984  start = end;
1985  }
1986 }
1987 
1988 // We examine rows[row_start, row_end) and do the following:
1989 // (1) Clear all existing hypotheses for the rows being considered.
1990 // (2) Mark up any rows as exceptionally likely to be paragraph starts
1991 // or paragraph body lines as such using both geometric and textual
1992 // clues.
1993 // (3) Form models for any sequence of start + continuation lines.
1994 // (4) Smear the paragraph models to cover surrounding text.
1995 void StrongEvidenceClassify(int debug_level,
1997  int row_start, int row_end,
1998  ParagraphTheory *theory) {
1999  if (!AcceptableRowArgs(debug_level, 2, __func__, rows, row_start, row_end))
2000  return;
2001 
2002  if (debug_level > 1) {
2003  tprintf("#############################################\n");
2004  tprintf("# StrongEvidenceClassify( rows[%d:%d) )\n", row_start, row_end);
2005  tprintf("#############################################\n");
2006  }
2007 
2008  RecomputeMarginsAndClearHypotheses(rows, row_start, row_end, 10);
2009  MarkStrongEvidence(rows, row_start, row_end);
2010 
2011  DebugDump(debug_level > 2, "Initial strong signals.", *theory, *rows);
2012 
2013  // Create paragraph models.
2014  ModelStrongEvidence(debug_level, rows, row_start, row_end, false, theory);
2015 
2016  DebugDump(debug_level > 2, "Unsmeared hypotheses.s.", *theory, *rows);
2017 
2018  // At this point, some rows are marked up as paragraphs with model numbers,
2019  // and some rows are marked up as either LT_START or LT_BODY. Now let's
2020  // smear any good paragraph hypotheses forward and backward.
2021  ParagraphModelSmearer smearer(rows, row_start, row_end, theory);
2022  smearer.Smear();
2023 }
2024 
2026  int row_start, int row_end,
2027  ParagraphTheory *theory) {
2028  for (int i = row_start + 1; i < row_end - 1; i++) {
2029  if ((*rows)[i - 1].ri_->has_leaders &&
2030  (*rows)[i].ri_->has_leaders &&
2031  (*rows)[i + 1].ri_->has_leaders) {
2032  const ParagraphModel *model = theory->AddModel(
2033  ParagraphModel(JUSTIFICATION_UNKNOWN, 0, 0, 0, 0));
2034  (*rows)[i].AddStartLine(model);
2035  }
2036  }
2037 }
2038 
2039 // Collect sequences of unique hypotheses in row registers and create proper
2040 // paragraphs for them, referencing the paragraphs in row_owners.
2042  int debug_level,
2044  GenericVector<PARA *> *row_owners,
2045  ParagraphTheory *theory) {
2046  int end = rows.size();
2047  int start;
2048  for (; end > 0; end = start) {
2049  start = end - 1;
2050  const ParagraphModel *model = NULL;
2051  // TODO(eger): Be smarter about dealing with multiple hypotheses.
2052  bool single_line_paragraph = false;
2053  SetOfModels models;
2054  rows[start].NonNullHypotheses(&models);
2055  if (models.size() > 0) {
2056  model = models[0];
2057  if (rows[start].GetLineType(model) != LT_BODY)
2058  single_line_paragraph = true;
2059  }
2060  if (model && !single_line_paragraph) {
2061  // walk back looking for more body lines and then a start line.
2062  while (--start > 0 && rows[start].GetLineType(model) == LT_BODY) {
2063  // do nothing
2064  }
2065  if (start < 0 || rows[start].GetLineType(model) != LT_START) {
2066  model = NULL;
2067  }
2068  }
2069  if (model == NULL) {
2070  continue;
2071  }
2072  // rows[start, end) should be a paragraph.
2073  PARA *p = new PARA();
2074  if (model == kCrownLeft || model == kCrownRight) {
2076  // Crown paragraph.
2077  // If we can find an existing ParagraphModel that fits, use it,
2078  // else create a new one.
2079  for (int row = end; row < rows.size(); row++) {
2080  if ((*row_owners)[row] &&
2081  (ValidBodyLine(&rows, start, (*row_owners)[row]->model) &&
2082  (start == 0 ||
2083  ValidFirstLine(&rows, start, (*row_owners)[row]->model)))) {
2084  model = (*row_owners)[row]->model;
2085  break;
2086  }
2087  }
2088  if (model == kCrownLeft) {
2089  // No subsequent model fits, so cons one up.
2090  model = theory->AddModel(ParagraphModel(
2091  JUSTIFICATION_LEFT, rows[start].lmargin_ + rows[start].lindent_,
2092  0, 0, Epsilon(rows[start].ri_->average_interword_space)));
2093  } else if (model == kCrownRight) {
2094  // No subsequent model fits, so cons one up.
2095  model = theory->AddModel(ParagraphModel(
2096  JUSTIFICATION_RIGHT, rows[start].rmargin_ + rows[start].rmargin_,
2097  0, 0, Epsilon(rows[start].ri_->average_interword_space)));
2098  }
2099  }
2100  rows[start].SetUnknown();
2101  rows[start].AddStartLine(model);
2102  for (int i = start + 1; i < end; i++) {
2103  rows[i].SetUnknown();
2104  rows[i].AddBodyLine(model);
2105  }
2106  p->model = model;
2107  p->has_drop_cap = rows[start].ri_->has_drop_cap;
2108  p->is_list_item =
2110  ? rows[start].ri_->rword_indicates_list_item
2111  : rows[start].ri_->lword_indicates_list_item;
2112  for (int row = start; row < end; row++) {
2113  if ((*row_owners)[row] != NULL) {
2114  tprintf("Memory leak! ConvertHypothesizeModelRunsToParagraphs() called "
2115  "more than once!\n");
2116  }
2117  (*row_owners)[row] = p;
2118  }
2119  }
2120 }
2121 
2122 struct Interval {
2123  Interval() : begin(0), end(0) {}
2124  Interval(int b, int e) : begin(b), end(e) {}
2125 
2126  int begin;
2127  int end;
2128 };
2129 
2130 // Return whether rows[row] appears to be stranded, meaning that the evidence
2131 // for this row is very weak due to context. For instance, two lines of source
2132 // code may happen to be indented at the same tab vector as body text starts,
2133 // leading us to think they are two start-of-paragraph lines. This is not
2134 // optimal. However, we also don't want to mark a sequence of short dialog
2135 // as "weak," so our heuristic is:
2136 // (1) If a line is surrounded by lines of unknown type, it's weak.
2137 // (2) If two lines in a row are start lines for a given paragraph type, but
2138 // after that the same paragraph type does not continue, they're weak.
2140  SetOfModels row_models;
2141  rows[row].StrongHypotheses(&row_models);
2142 
2143  for (int m = 0; m < row_models.size(); m++) {
2144  bool all_starts = rows[row].GetLineType();
2145  int run_length = 1;
2146  bool continues = true;
2147  for (int i = row - 1; i >= 0 && continues; i--) {
2148  SetOfModels models;
2149  rows[i].NonNullHypotheses(&models);
2150  switch (rows[i].GetLineType(row_models[m])) {
2151  case LT_START: run_length++; break;
2152  case LT_MULTIPLE: // explicit fall-through
2153  case LT_BODY: run_length++; all_starts = false; break;
2154  case LT_UNKNOWN: // explicit fall-through
2155  default: continues = false;
2156  }
2157  }
2158  continues = true;
2159  for (int i = row + 1; i < rows.size() && continues; i++) {
2160  SetOfModels models;
2161  rows[i].NonNullHypotheses(&models);
2162  switch (rows[i].GetLineType(row_models[m])) {
2163  case LT_START: run_length++; break;
2164  case LT_MULTIPLE: // explicit fall-through
2165  case LT_BODY: run_length++; all_starts = false; break;
2166  case LT_UNKNOWN: // explicit fall-through
2167  default: continues = false;
2168  }
2169  }
2170  if (run_length > 2 || (!all_starts && run_length > 1)) return false;
2171  }
2172  return true;
2173 }
2174 
2175 // Go through rows[row_start, row_end) and gather up sequences that need better
2176 // classification.
2177 // + Sequences of non-empty rows without hypotheses.
2178 // + Crown paragraphs not immediately followed by a strongly modeled line.
2179 // + Single line paragraphs surrounded by text that doesn't match the
2180 // model.
2182  GenericVector<Interval> *to_fix,
2183  int row_start, int row_end) {
2184  to_fix->clear();
2185  for (int i = row_start; i < row_end; i++) {
2186  bool needs_fixing = false;
2187 
2188  SetOfModels models;
2189  SetOfModels models_w_crowns;
2190  rows[i].StrongHypotheses(&models);
2191  rows[i].NonNullHypotheses(&models_w_crowns);
2192  if (models.empty() && models_w_crowns.size() > 0) {
2193  // Crown paragraph. Is it followed by a modeled line?
2194  for (int end = i + 1; end < rows.size(); end++) {
2195  SetOfModels end_models;
2196  SetOfModels strong_end_models;
2197  rows[end].NonNullHypotheses(&end_models);
2198  rows[end].StrongHypotheses(&strong_end_models);
2199  if (end_models.size() == 0) {
2200  needs_fixing = true;
2201  break;
2202  } else if (strong_end_models.size() > 0) {
2203  needs_fixing = false;
2204  break;
2205  }
2206  }
2207  } else if (models.empty() && rows[i].ri_->num_words > 0) {
2208  // No models at all.
2209  needs_fixing = true;
2210  }
2211 
2212  if (!needs_fixing && !models.empty()) {
2213  needs_fixing = RowIsStranded(rows, i);
2214  }
2215 
2216  if (needs_fixing) {
2217  if (!to_fix->empty() && to_fix->back().end == i - 1)
2218  to_fix->back().end = i;
2219  else
2220  to_fix->push_back(Interval(i, i));
2221  }
2222  }
2223  // Convert inclusive intervals to half-open intervals.
2224  for (int i = 0; i < to_fix->size(); i++) {
2225  (*to_fix)[i].end = (*to_fix)[i].end + 1;
2226  }
2227 }
2228 
2229 // Given a set of row_owners pointing to PARAs or NULL (no paragraph known),
2230 // normalize each row_owner to point to an actual PARA, and output the
2231 // paragraphs in order onto paragraphs.
2233  GenericVector<PARA *> *row_owners,
2234  PARA_LIST *paragraphs) {
2235  GenericVector<PARA *> &rows = *row_owners;
2236  paragraphs->clear();
2237  PARA_IT out(paragraphs);
2238  PARA *formerly_null = NULL;
2239  for (int i = 0; i < rows.size(); i++) {
2240  if (rows[i] == NULL) {
2241  if (i == 0 || rows[i - 1] != formerly_null) {
2242  rows[i] = formerly_null = new PARA();
2243  } else {
2244  rows[i] = formerly_null;
2245  continue;
2246  }
2247  } else if (i > 0 && rows[i - 1] == rows[i]) {
2248  continue;
2249  }
2250  out.add_after_then_move(rows[i]);
2251  }
2252 }
2253 
2254 // Main entry point for Paragraph Detection Algorithm.
2255 //
2256 // Given a set of equally spaced textlines (described by row_infos),
2257 // Split them into paragraphs.
2258 //
2259 // Output:
2260 // row_owners - one pointer for each row, to the paragraph it belongs to.
2261 // paragraphs - this is the actual list of PARA objects.
2262 // models - the list of paragraph models referenced by the PARA objects.
2263 // caller is responsible for deleting the models.
2264 void DetectParagraphs(int debug_level,
2265  GenericVector<RowInfo> *row_infos,
2266  GenericVector<PARA *> *row_owners,
2267  PARA_LIST *paragraphs,
2270  ParagraphTheory theory(models);
2271 
2272  // Initialize row_owners to be a bunch of NULL pointers.
2273  row_owners->init_to_size(row_infos->size(), NULL);
2274 
2275  // Set up row scratch registers for the main algorithm.
2276  rows.init_to_size(row_infos->size(), RowScratchRegisters());
2277  for (int i = 0; i < row_infos->size(); i++) {
2278  rows[i].Init((*row_infos)[i]);
2279  }
2280 
2281  // Pass 1:
2282  // Detect sequences of lines that all contain leader dots (.....)
2283  // These are likely Tables of Contents. If there are three text lines in
2284  // a row with leader dots, it's pretty safe to say the middle one should
2285  // be a paragraph of its own.
2286  SeparateSimpleLeaderLines(&rows, 0, rows.size(), &theory);
2287 
2288  DebugDump(debug_level > 1, "End of Pass 1", theory, rows);
2289 
2290  GenericVector<Interval> leftovers;
2291  LeftoverSegments(rows, &leftovers, 0, rows.size());
2292  for (int i = 0; i < leftovers.size(); i++) {
2293  // Pass 2a:
2294  // Find any strongly evidenced start-of-paragraph lines. If they're
2295  // followed by two lines that look like body lines, make a paragraph
2296  // model for that and see if that model applies throughout the text
2297  // (that is, "smear" it).
2298  StrongEvidenceClassify(debug_level, &rows,
2299  leftovers[i].begin, leftovers[i].end, &theory);
2300 
2301  // Pass 2b:
2302  // If we had any luck in pass 2a, we got part of the page and didn't
2303  // know how to classify a few runs of rows. Take the segments that
2304  // didn't find a model and reprocess them individually.
2305  GenericVector<Interval> leftovers2;
2306  LeftoverSegments(rows, &leftovers2, leftovers[i].begin, leftovers[i].end);
2307  bool pass2a_was_useful = leftovers2.size() > 1 ||
2308  (leftovers2.size() == 1 &&
2309  (leftovers2[0].begin != 0 || leftovers2[0].end != rows.size()));
2310  if (pass2a_was_useful) {
2311  for (int j = 0; j < leftovers2.size(); j++) {
2312  StrongEvidenceClassify(debug_level, &rows,
2313  leftovers2[j].begin, leftovers2[j].end,
2314  &theory);
2315  }
2316  }
2317  }
2318 
2319  DebugDump(debug_level > 1, "End of Pass 2", theory, rows);
2320 
2321  // Pass 3:
2322  // These are the dregs for which we didn't have enough strong textual
2323  // and geometric clues to form matching models for. Let's see if
2324  // the geometric clues are simple enough that we could just use those.
2325  LeftoverSegments(rows, &leftovers, 0, rows.size());
2326  for (int i = 0; i < leftovers.size(); i++) {
2327  GeometricClassify(debug_level, &rows,
2328  leftovers[i].begin, leftovers[i].end, &theory);
2329  }
2330 
2331  // Undo any flush models for which there's little evidence.
2332  DowngradeWeakestToCrowns(debug_level, &theory, &rows);
2333 
2334  DebugDump(debug_level > 1, "End of Pass 3", theory, rows);
2335 
2336  // Pass 4:
2337  // Take everything that's still not marked up well and clear all markings.
2338  LeftoverSegments(rows, &leftovers, 0, rows.size());
2339  for (int i = 0; i < leftovers.size(); i++) {
2340  for (int j = leftovers[i].begin; j < leftovers[i].end; j++) {
2341  rows[j].SetUnknown();
2342  }
2343  }
2344 
2345  DebugDump(debug_level > 1, "End of Pass 4", theory, rows);
2346 
2347  // Convert all of the unique hypothesis runs to PARAs.
2348  ConvertHypothesizedModelRunsToParagraphs(debug_level, rows, row_owners,
2349  &theory);
2350 
2351  DebugDump(debug_level > 0, "Final Paragraph Segmentation", theory, rows);
2352 
2353  // Finally, clean up any dangling NULL row paragraph parents.
2354  CanonicalizeDetectionResults(row_owners, paragraphs);
2355 }
2356 
2357 // ============ Code interfacing with the rest of Tesseract ==================
2358 
2360  RowInfo *info) {
2361  // Set up text, lword_text, and rword_text (mostly for debug printing).
2362  STRING fake_text;
2363  PageIterator pit(static_cast<const PageIterator&>(it));
2364  bool first_word = true;
2365  if (!pit.Empty(RIL_WORD)) {
2366  do {
2367  fake_text += "x";
2368  if (first_word) info->lword_text += "x";
2369  info->rword_text += "x";
2370  if (pit.IsAtFinalElement(RIL_WORD, RIL_SYMBOL) &&
2372  fake_text += " ";
2373  info->rword_text = "";
2374  first_word = false;
2375  }
2376  } while (!pit.IsAtFinalElement(RIL_TEXTLINE, RIL_SYMBOL) &&
2377  pit.Next(RIL_SYMBOL));
2378  }
2379  if (fake_text.size() == 0) return;
2380 
2381  int lspaces = info->pix_ldistance / info->average_interword_space;
2382  for (int i = 0; i < lspaces; i++) {
2383  info->text += ' ';
2384  }
2385  info->text += fake_text;
2386 
2387  // Set up lword_box, rword_box, and num_words.
2388  PAGE_RES_IT page_res_it = *it.PageResIt();
2389  WERD_RES *word_res = page_res_it.restart_row();
2390  ROW_RES *this_row = page_res_it.row();
2391 
2392  WERD_RES *lword = NULL;
2393  WERD_RES *rword = NULL;
2394  info->num_words = 0;
2395  do {
2396  if (word_res) {
2397  if (!lword) lword = word_res;
2398  if (rword != word_res) info->num_words++;
2399  rword = word_res;
2400  }
2401  word_res = page_res_it.forward();
2402  } while (page_res_it.row() == this_row);
2403 
2404  if (lword) info->lword_box = lword->word->bounding_box();
2405  if (rword) info->rword_box = rword->word->bounding_box();
2406 }
2407 
2408 
2409 // Given a Tesseract Iterator pointing to a text line, fill in the paragraph
2410 // detector RowInfo with all relevant information from the row.
2411 void InitializeRowInfo(bool after_recognition,
2412  const MutableIterator &it,
2413  RowInfo *info) {
2414  if (it.PageResIt()->row() != NULL) {
2415  ROW *row = it.PageResIt()->row()->row;
2416  info->pix_ldistance = row->lmargin();
2417  info->pix_rdistance = row->rmargin();
2418  info->average_interword_space =
2419  row->space() > 0 ? row->space() : MAX(row->x_height(), 1);
2420  info->pix_xheight = row->x_height();
2421  info->has_leaders = false;
2422  info->has_drop_cap = row->has_drop_cap();
2423  info->ltr = true; // set below depending on word scripts
2424  } else {
2425  info->pix_ldistance = info->pix_rdistance = 0;
2426  info->average_interword_space = 1;
2427  info->pix_xheight = 1.0;
2428  info->has_leaders = false;
2429  info->has_drop_cap = false;
2430  info->ltr = true;
2431  }
2432 
2433  info->num_words = 0;
2434  info->lword_indicates_list_item = false;
2435  info->lword_likely_starts_idea = false;
2436  info->lword_likely_ends_idea = false;
2437  info->rword_indicates_list_item = false;
2438  info->rword_likely_starts_idea = false;
2439  info->rword_likely_ends_idea = false;
2440  info->has_leaders = false;
2441  info->ltr = 1;
2442 
2443  if (!after_recognition) {
2445  return;
2446  }
2447  info->text = "";
2448  char *text = it.GetUTF8Text(RIL_TEXTLINE);
2449  int trailing_ws_idx = strlen(text); // strip trailing space
2450  while (trailing_ws_idx > 0 &&
2451  // isspace() only takes ASCII
2452  ((text[trailing_ws_idx - 1] & 0x80) == 0) &&
2453  isspace(text[trailing_ws_idx - 1]))
2454  trailing_ws_idx--;
2455  if (trailing_ws_idx > 0) {
2456  int lspaces = info->pix_ldistance / info->average_interword_space;
2457  for (int i = 0; i < lspaces; i++)
2458  info->text += ' ';
2459  for (int i = 0; i < trailing_ws_idx; i++)
2460  info->text += text[i];
2461  }
2462  delete []text;
2463 
2464  if (info->text.size() == 0) {
2465  return;
2466  }
2467 
2468  PAGE_RES_IT page_res_it = *it.PageResIt();
2470  WERD_RES *word_res = page_res_it.restart_row();
2471  ROW_RES *this_row = page_res_it.row();
2472  int num_leaders = 0;
2473  int ltr = 0;
2474  int rtl = 0;
2475  do {
2476  if (word_res && word_res->best_choice->unichar_string().length() > 0) {
2477  werds.push_back(word_res);
2478  ltr += word_res->AnyLtrCharsInWord() ? 1 : 0;
2479  rtl += word_res->AnyRtlCharsInWord() ? 1 : 0;
2480  if (word_res->word->flag(W_REP_CHAR)) num_leaders++;
2481  }
2482  word_res = page_res_it.forward();
2483  } while (page_res_it.row() == this_row);
2484  info->ltr = ltr >= rtl;
2485  info->has_leaders = num_leaders > 3;
2486  info->num_words = werds.size();
2487  if (werds.size() > 0) {
2488  WERD_RES *lword = werds[0], *rword = werds[werds.size() - 1];
2489  info->lword_text = lword->best_choice->unichar_string().string();
2490  info->rword_text = rword->best_choice->unichar_string().string();
2491  info->lword_box = lword->word->bounding_box();
2492  info->rword_box = rword->word->bounding_box();
2493  LeftWordAttributes(lword->uch_set, lword->best_choice,
2494  info->lword_text,
2496  &info->lword_likely_starts_idea,
2497  &info->lword_likely_ends_idea);
2498  RightWordAttributes(rword->uch_set, rword->best_choice,
2499  info->rword_text,
2501  &info->rword_likely_starts_idea,
2502  &info->rword_likely_ends_idea);
2503  }
2504 }
2505 
2506 // This is called after rows have been identified and words are recognized.
2507 // Much of this could be implemented before word recognition, but text helps
2508 // to identify bulleted lists and gives good signals for sentence boundaries.
2509 void DetectParagraphs(int debug_level,
2510  bool after_text_recognition,
2511  const MutableIterator *block_start,
2513  // Clear out any preconceived notions.
2514  if (block_start->Empty(RIL_TEXTLINE)) {
2515  return;
2516  }
2517  BLOCK *block = block_start->PageResIt()->block()->block;
2518  block->para_list()->clear();
2519  bool is_image_block = block->poly_block() && !block->poly_block()->IsText();
2520 
2521  // Convert the Tesseract structures to RowInfos
2522  // for the paragraph detection algorithm.
2523  MutableIterator row(*block_start);
2524  if (row.Empty(RIL_TEXTLINE))
2525  return; // end of input already.
2526 
2527  GenericVector<RowInfo> row_infos;
2528  do {
2529  if (!row.PageResIt()->row())
2530  continue; // empty row.
2531  row.PageResIt()->row()->row->set_para(NULL);
2532  row_infos.push_back(RowInfo());
2533  RowInfo &ri = row_infos.back();
2534  InitializeRowInfo(after_text_recognition, row, &ri);
2535  } while (!row.IsAtFinalElement(RIL_BLOCK, RIL_TEXTLINE) &&
2536  row.Next(RIL_TEXTLINE));
2537 
2538  // If we're called before text recognition, we might not have
2539  // tight block bounding boxes, so trim by the minimum on each side.
2540  if (row_infos.size() > 0) {
2541  int min_lmargin = row_infos[0].pix_ldistance;
2542  int min_rmargin = row_infos[0].pix_rdistance;
2543  for (int i = 1; i < row_infos.size(); i++) {
2544  if (row_infos[i].pix_ldistance < min_lmargin)
2545  min_lmargin = row_infos[i].pix_ldistance;
2546  if (row_infos[i].pix_rdistance < min_rmargin)
2547  min_rmargin = row_infos[i].pix_rdistance;
2548  }
2549  if (min_lmargin > 0 || min_rmargin > 0) {
2550  for (int i = 0; i < row_infos.size(); i++) {
2551  row_infos[i].pix_ldistance -= min_lmargin;
2552  row_infos[i].pix_rdistance -= min_rmargin;
2553  }
2554  }
2555  }
2556 
2557  // Run the paragraph detection algorithm.
2558  GenericVector<PARA *> row_owners;
2559  GenericVector<PARA *> the_paragraphs;
2560  if (!is_image_block) {
2561  DetectParagraphs(debug_level, &row_infos, &row_owners, block->para_list(),
2562  models);
2563  } else {
2564  row_owners.init_to_size(row_infos.size(), NULL);
2565  CanonicalizeDetectionResults(&row_owners, block->para_list());
2566  }
2567 
2568  // Now stitch in the row_owners into the rows.
2569  row = *block_start;
2570  for (int i = 0; i < row_owners.size(); i++) {
2571  while (!row.PageResIt()->row())
2572  row.Next(RIL_TEXTLINE);
2573  row.PageResIt()->row()->row->set_para(row_owners[i]);
2574  row.Next(RIL_TEXTLINE);
2575  }
2576 }
2577 
2578 } // namespace
ParagraphModel InternalParagraphModelByOutline(const GenericVector< RowScratchRegisters > *rows, int start, int end, int tolerance, bool *consistent)
bool FirstWordWouldHaveFit(const RowScratchRegisters &before, const RowScratchRegisters &after)
bool rword_indicates_list_item
Definition: paragraphs.h:75
int size() const
Definition: genericvector.h:72
bool ValidFirstLine(const GenericVector< RowScratchRegisters > *rows, int row, const ParagraphModel *model)
bool IsOpeningPunct(int ch)
Definition: paragraphs.cpp:201
void GeometricClassifyThreeTabStopTextBlock(int debug_level, GeometricClassifierState &s, ParagraphTheory *theory)
Definition: paragraphs.cpp:985
int body_indent() const
Definition: ocrpara.h:169
void InitializeTextAndBoxesPreRecognition(const MutableIterator &it, RowInfo *info)
inT32 space() const
Definition: ocrrow.h:76
bool LikelyListNumeral(const STRING &word)
Definition: paragraphs.cpp:228
int tolerance() const
Definition: ocrpara.h:170
#define MAX(x, y)
Definition: ndminx.h:24
const ParagraphModel * UniqueStartHypothesis() const
Definition: paragraphs.cpp:617
void DiscardUnusedModels(const GenericVector< RowScratchRegisters > &rows, ParagraphTheory *theory)
bool RowsFitModel(const GenericVector< RowScratchRegisters > *rows, int start, int end, const ParagraphModel *model)
int length() const
Definition: ratngs.h:300
WERD_CHOICE * best_choice
Definition: pageres.h:219
SimpleClusterer(int max_cluster_width)
Definition: paragraphs.cpp:653
void LeftWordAttributes(const UNICHARSET *unicharset, const WERD_CHOICE *werd, const STRING &utf8, bool *is_list, bool *starts_idea, bool *ends_idea)
Definition: paragraphs.cpp:394
int push_back(T object)
void CalculateTabStops(GenericVector< RowScratchRegisters > *rows, int row_start, int row_end, int tolerance, GenericVector< Cluster > *left_tabs, GenericVector< Cluster > *right_tabs)
Definition: paragraphs.cpp:691
GenericVector< RowScratchRegisters > * rows
Definition: paragraphs.cpp:932
void NonNullHypotheses(SetOfModels *models) const
Definition: paragraphs.cpp:610
bool lword_likely_ends_idea
Definition: paragraphs.h:73
void ConvertHypothesizedModelRunsToParagraphs(int debug_level, const GenericVector< RowScratchRegisters > &rows, GenericVector< PARA * > *row_owners, ParagraphTheory *theory)
void ModelStrongEvidence(int debug_level, GenericVector< RowScratchRegisters > *rows, int row_start, int row_end, bool allow_flush_models, ParagraphTheory *theory)
#define tprintf(...)
Definition: tprintf.h:31
bool get_isupper(UNICHAR_ID unichar_id) const
Definition: unicharset.h:463
bool IsTerminalPunct(int ch)
Definition: paragraphs.cpp:205
bool IsDigitLike(int ch)
Definition: paragraphs.cpp:197
void InitializeRowInfo(bool after_recognition, const MutableIterator &it, RowInfo *info)
GeometricClassifierState(int dbg_level, GenericVector< RowScratchRegisters > *r, int r_start, int r_end)
Definition: paragraphs.cpp:855
bool lword_likely_starts_idea
Definition: paragraphs.h:72
ParagraphModel ParagraphModelByOutline(int debug_level, const GenericVector< RowScratchRegisters > *rows, int start, int end, int tolerance)
Definition: statistc.h:33
int UnicodeFor(const UNICHARSET *u, const WERD_CHOICE *werd, int pos)
Definition: paragraphs.cpp:274
T & back() const
bool Empty(PageIteratorLevel level) const
bool has_drop_cap() const
Definition: ocrrow.h:108
const ParagraphModel * kCrownRight
Definition: paragraphs.cpp:47
inT16 rmargin() const
Definition: ocrrow.h:101
void NonCenteredModels(SetOfModels *models)
bool FirstWordWouldHaveFit(int row_a, int row_b)
Definition: paragraphs.cpp:910
void add(inT32 value, inT32 count)
Definition: statistc.cpp:104
virtual bool Next(PageIteratorLevel level)
bool LikelyListMarkUnicode(int ch)
Definition: paragraphs.cpp:328
int average_interword_space
Definition: paragraphs.h:52
bool is_list_item
Definition: ocrpara.h:38
bool ValidBodyLine(int lmargin, int lindent, int rindent, int rmargin) const
Definition: ocrpara.cpp:63
float x_height() const
Definition: ocrrow.h:61
TBOX bounding_box() const
Definition: werd.cpp:160
const GenericVector< Cluster > & AlignTabs() const
Definition: paragraphs.cpp:882
inT32 length() const
Definition: strngs.cpp:188
virtual char * GetUTF8Text(PageIteratorLevel level) const
bool StrongModel(const ParagraphModel *model)
ParagraphModel Model() const
Definition: paragraphs.cpp:923
GenericVector< Cluster > left_tabs
Definition: paragraphs.cpp:945
void RightWordAttributes(const UNICHARSET *unicharset, const WERD_CHOICE *werd, const STRING &utf8, bool *is_list, bool *starts_idea, bool *ends_idea)
Definition: paragraphs.cpp:441
void UpdateRange(const T1 &x, T2 *lower_bound, T2 *upper_bound)
Definition: helpers.h:125
ParagraphModelSmearer(GenericVector< RowScratchRegisters > *rows, int row_start, int row_end, ParagraphTheory *theory)
GenericVectorEqEq< const ParagraphModel * > SetOfModels
bool ValidBodyLine(const GenericVector< RowScratchRegisters > *rows, int row, const ParagraphModel *model)
bool rword_likely_ends_idea
Definition: paragraphs.h:77
int first_indent() const
Definition: ocrpara.h:168
bool IsText() const
Definition: polyblk.h:52
bool AnyRtlCharsInWord() const
Definition: pageres.h:372
static void AppendDebugHeaderFields(GenericVector< STRING > *header)
Definition: paragraphs.cpp:475
void StrongHypotheses(SetOfModels *models) const
Definition: paragraphs.cpp:603
BLOCK * block
Definition: pageres.h:99
T ClipToRange(const T &x, const T &lower_bound, const T &upper_bound)
Definition: helpers.h:115
void LeftoverSegments(const GenericVector< RowScratchRegisters > &rows, GenericVector< Interval > *to_fix, int row_start, int row_end)
void AddStartLine(const ParagraphModel *model)
Definition: paragraphs.cpp:582
void MarkStrongEvidence(GenericVector< RowScratchRegisters > *rows, int row_start, int row_end)
Definition: ocrrow.h:32
void Init(const RowInfo &row)
Definition: paragraphs.cpp:512
void DowngradeWeakestToCrowns(int debug_level, ParagraphTheory *theory, GenericVector< RowScratchRegisters > *rows)
const STRING & unichar_string() const
Definition: ratngs.h:524
bool RowIsStranded(const GenericVector< RowScratchRegisters > &rows, int row)
BLOCK_RES * block() const
Definition: pageres.h:739
void RecomputeMarginsAndClearHypotheses(GenericVector< RowScratchRegisters > *rows, int start, int end, int percentile)
bool ValidFirstLine(int lmargin, int lindent, int rindent, int rmargin) const
Definition: ocrpara.cpp:46
WERD_RES * forward()
Definition: pageres.h:713
inT16 lmargin() const
Definition: ocrrow.h:98
bool lword_indicates_list_item
Definition: paragraphs.h:71
bool get_isdigit(UNICHAR_ID unichar_id) const
Definition: unicharset.h:470
double median() const
Definition: statistc.cpp:243
const ParagraphModel * AddModel(const ParagraphModel &model)
bool FirstWordWouldHaveFit(const RowScratchRegisters &before, const RowScratchRegisters &after, tesseract::ParagraphJustification justification)
bool LikelyListMark(const STRING &word)
Definition: paragraphs.cpp:262
void StartHypotheses(SetOfModels *models) const
Definition: paragraphs.cpp:596
void MarkRowsWithModel(GenericVector< RowScratchRegisters > *rows, int row_start, int row_end, const ParagraphModel *model, bool ltr, int eop_threshold)
Definition: paragraphs.cpp:807
void AddBodyLine(const ParagraphModel *model)
Definition: paragraphs.cpp:589
void CanonicalizeDetectionResults(GenericVector< PARA * > *row_owners, PARA_LIST *paragraphs)
PARA_LIST * para_list()
Definition: ocrblock.h:128
double ile(double frac) const
Definition: statistc.cpp:177
bool NearlyEqual(T x, T y, T tolerance)
Definition: host.h:148
int AlignsideTabIndex(int row_idx) const
Definition: paragraphs.cpp:904
const UNICHAR_ID unichar_id(int index) const
Definition: ratngs.h:312
const char *const id_to_unichar(UNICHAR_ID id) const
Definition: unicharset.cpp:266
int first_uni() const
Definition: unichar.cpp:97
Definition: ocrblock.h:30
const UNICHARSET * uch_set
Definition: pageres.h:192
Interval(int b, int e)
void init_to_size(int size, T t)
ROW_RES * row() const
Definition: pageres.h:736
virtual bool IsAtFinalElement(PageIteratorLevel level, PageIteratorLevel element) const
const char * SkipChars(const char *str, const char *toskip)
Definition: paragraphs.cpp:210
Definition: ocrpara.h:29
WERD_RES * restart_row()
Definition: pageres.cpp:1636
const GenericVector< Cluster > & OffsideTabs() const
Definition: paragraphs.cpp:892
tesseract::ParagraphJustification justification() const
Definition: ocrpara.h:164
inT32 size() const
Definition: strngs.h:66
const char * kRLE
Definition: unicodes.cpp:29
ParagraphJustification
Definition: publictypes.h:239
int UNICHAR_ID
Definition: unichar.h:33
bool get_ispunctuation(UNICHAR_ID unichar_id) const
Definition: unicharset.h:477
bool rword_likely_starts_idea
Definition: paragraphs.h:76
const char * kPDF
Definition: unicodes.cpp:30
WERD * word
Definition: pageres.h:175
const ParagraphModel * UniqueBodyHypothesis() const
Definition: paragraphs.cpp:623
bool contains(T object) const
int push_back_new(T object)
bool empty() const
Definition: genericvector.h:84
void DiscardNonMatchingHypotheses(const SetOfModels &models)
Definition: paragraphs.cpp:630
const ParagraphModel * kCrownLeft
Definition: paragraphs.cpp:45
void remove(int index)
void AppendDebugInfo(const ParagraphTheory &theory, GenericVector< STRING > *dbg) const
Definition: paragraphs.cpp:481
void GetClusters(GenericVector< Cluster > *clusters)
Definition: paragraphs.cpp:675
const PAGE_RES_IT * PageResIt() const
void DetectParagraphs(int debug_level, GenericVector< RowInfo > *row_infos, GenericVector< PARA * > *row_owners, PARA_LIST *paragraphs, GenericVector< ParagraphModel * > *models)
inT16 width() const
Definition: rect.h:111
bool LikelyParagraphStart(const RowScratchRegisters &before, const RowScratchRegisters &after)
void SeparateSimpleLeaderLines(GenericVector< RowScratchRegisters > *rows, int row_start, int row_end, ParagraphTheory *theory)
UnicodeSpanSkipper(const UNICHARSET *unicharset, const WERD_CHOICE *word)
Definition: paragraphs.cpp:284
bool is_very_first_or_continuation
Definition: ocrpara.h:43
int count(LIST var_list)
Definition: oldlist.cpp:108
bool is_flush() const
Definition: ocrpara.h:171
void Fail(int min_debug_level, const char *why) const
Definition: paragraphs.cpp:917
ROW * row
Definition: pageres.h:127
STRING RtlEmbed(const STRING &word, bool rtlify)
Definition: paragraphs.cpp:121
BOOL8 flag(WERD_FLAGS mask) const
Definition: werd.h:128
bool TextSupportsBreak(const RowScratchRegisters &before, const RowScratchRegisters &after)
virtual bool IsAtFinalElement(PageIteratorLevel level, PageIteratorLevel element) const
Definition: strngs.h:44
void DiscardUnusedModels(const SetOfModels &used_models)
LineType GetLineType() const
Definition: paragraphs.cpp:520
bool AnyLtrCharsInWord() const
Definition: pageres.h:389
const char * SkipOne(const char *str, const char *toskip)
Definition: paragraphs.cpp:220
#define NULL
Definition: host.h:144
bool CrownCompatible(const GenericVector< RowScratchRegisters > *rows, int a, int b, const ParagraphModel *model)
virtual bool Next(PageIteratorLevel level)
bool AsciiLikelyListItem(const STRING &word)
Definition: paragraphs.cpp:267
const ParagraphModel * Fits(const GenericVector< RowScratchRegisters > *rows, int start, int end) const
const ParagraphModel * model
Definition: ocrpara.h:36
void GeometricClassify(int debug_level, GenericVector< RowScratchRegisters > *rows, int row_start, int row_end, ParagraphTheory *theory)
const char * string() const
Definition: strngs.cpp:193
int OffsideIndent(tesseract::ParagraphJustification just) const
int InterwordSpace(const GenericVector< RowScratchRegisters > &rows, int row_start, int row_end)
POLY_BLOCK * poly_block() const
Definition: pdblock.h:59
void set_para(PARA *p)
Definition: ocrrow.h:112
int ClosestCluster(const GenericVector< Cluster > &clusters, int value)
Definition: paragraphs.cpp:665
int get_index(T object) const
bool UniLikelyListItem(const UNICHARSET *u, const WERD_CHOICE *werd)
Definition: paragraphs.cpp:357
bool has_drop_cap
Definition: ocrpara.h:46
void StrongEvidenceClassify(int debug_level, GenericVector< RowScratchRegisters > *rows, int row_start, int row_end, ParagraphTheory *theory)
tesseract::ParagraphJustification just
Definition: paragraphs.cpp:949
bool IsLatinLetter(int ch)
Definition: paragraphs.cpp:193
Cluster(int cen, int num)
Definition: paragraphs.cpp:645
GenericVector< Cluster > right_tabs
Definition: paragraphs.cpp:946
int IndexOf(const ParagraphModel *model) const