/
paragraphs.cpp
2583 lines (2366 loc) · 94.4 KB
/
paragraphs.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**********************************************************************
* File: paragraphs.cpp
* Description: Paragraph detection for tesseract.
* Author: David Eger
* Created: 25 February 2011
*
* (C) Copyright 2011, Google Inc.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include "paragraphs.h"
#include <cctype> // for isspace
#include <cmath> // for abs
#include <cstdio> // for snprintf
#include <cstdlib> // for abs
#include <cstring> // for strchr, strlen
#include <algorithm> // for max
#include <memory> // for unique_ptr
#include "genericvector.h" // for GenericVector, GenericVectorEqEq
#include "helpers.h" // for UpdateRange, ClipToRange
#include "host.h" // for NearlyEqual
#include "mutableiterator.h" // for MutableIterator
#include "ocrblock.h" // for BLOCK
#include "ocrpara.h" // for ParagraphModel, PARA, PARA_IT, PARA...
#include "ocrrow.h" // for ROW
#include "pageiterator.h" // for PageIterator
#include "pageres.h" // for PAGE_RES_IT, WERD_RES, ROW_RES, BLO...
#include "paragraphs_internal.h" // for RowScratchRegisters, SetOfModels
#include "pdblock.h" // for PDBLK
#include "polyblk.h" // for POLY_BLOCK
#include "publictypes.h" // for JUSTIFICATION_LEFT, JUSTIFICATION_R...
#include "ratngs.h" // for WERD_CHOICE
#include "rect.h" // for TBOX
#include "statistc.h" // for STATS
#include "strngs.h" // for STRING
#include "tprintf.h" // for tprintf
#include "unichar.h" // for UNICHAR, UNICHAR_ID
#include "unicharset.h" // for UNICHARSET
#include "unicodes.h" // for kPDF, kRLE
#include "werd.h" // for WERD, W_REP_CHAR
namespace tesseract {
// Special "weak" ParagraphModels.
const ParagraphModel *kCrownLeft
= reinterpret_cast<ParagraphModel *>(0xDEAD111F);
const ParagraphModel *kCrownRight
= reinterpret_cast<ParagraphModel *>(0xDEAD888F);
// Do the text and geometry of two rows support a paragraph break between them?
static bool LikelyParagraphStart(const RowScratchRegisters &before,
const RowScratchRegisters &after,
tesseract::ParagraphJustification j);
// Given the width of a typical space between words, what is the threshold
// by which by which we think left and right alignments for paragraphs
// can vary and still be aligned.
static int Epsilon(int space_pix) {
return space_pix * 4 / 5;
}
static bool AcceptableRowArgs(
int debug_level, int min_num_rows, const char *function_name,
const GenericVector<RowScratchRegisters> *rows,
int row_start, int row_end) {
if (row_start < 0 || row_end > rows->size() || row_start > row_end) {
tprintf("Invalid arguments rows[%d, %d) while rows is of size %d.\n",
row_start, row_end, rows->size());
return false;
}
if (row_end - row_start < min_num_rows) {
if (debug_level > 1) {
tprintf("# Too few rows[%d, %d) for %s.\n",
row_start, row_end, function_name);
}
return false;
}
return true;
}
// =============================== Debug Code ================================
// Convert an integer to a decimal string.
static STRING StrOf(int num) {
char buffer[30];
snprintf(buffer, sizeof(buffer), "%d", num);
return STRING(buffer);
}
// Given a row-major matrix of unicode text and a column separator, print
// a formatted table. For ASCII, we get good column alignment.
static void PrintTable(const GenericVector<GenericVector<STRING> > &rows,
const STRING &colsep) {
GenericVector<int> max_col_widths;
for (int r = 0; r < rows.size(); r++) {
int num_columns = rows[r].size();
for (int c = 0; c < num_columns; c++) {
int num_unicodes = 0;
for (int i = 0; i < rows[r][c].size(); i++) {
if ((rows[r][c][i] & 0xC0) != 0x80) num_unicodes++;
}
if (c >= max_col_widths.size()) {
max_col_widths.push_back(num_unicodes);
} else {
if (num_unicodes > max_col_widths[c])
max_col_widths[c] = num_unicodes;
}
}
}
GenericVector<STRING> col_width_patterns;
for (int c = 0; c < max_col_widths.size(); c++) {
col_width_patterns.push_back(
STRING("%-") + StrOf(max_col_widths[c]) + "s");
}
for (int r = 0; r < rows.size(); r++) {
for (int c = 0; c < rows[r].size(); c++) {
if (c > 0)
tprintf("%s", colsep.string());
tprintf(col_width_patterns[c].string(), rows[r][c].string());
}
tprintf("\n");
}
}
static STRING RtlEmbed(const STRING &word, bool rtlify) {
if (rtlify)
return STRING(kRLE) + word + STRING(kPDF);
return word;
}
// Print the current thoughts of the paragraph detector.
static void PrintDetectorState(const ParagraphTheory &theory,
const GenericVector<RowScratchRegisters> &rows) {
GenericVector<GenericVector<STRING> > output;
output.push_back(GenericVector<STRING>());
output.back().push_back("#row");
output.back().push_back("space");
output.back().push_back("..");
output.back().push_back("lword[widthSEL]");
output.back().push_back("rword[widthSEL]");
RowScratchRegisters::AppendDebugHeaderFields(&output.back());
output.back().push_back("text");
for (int i = 0; i < rows.size(); i++) {
output.push_back(GenericVector<STRING>());
GenericVector<STRING> &row = output.back();
const RowInfo& ri = *rows[i].ri_;
row.push_back(StrOf(i));
row.push_back(StrOf(ri.average_interword_space));
row.push_back(ri.has_leaders ? ".." : " ");
row.push_back(RtlEmbed(ri.lword_text, !ri.ltr) +
"[" + StrOf(ri.lword_box.width()) +
(ri.lword_likely_starts_idea ? "S" : "s") +
(ri.lword_likely_ends_idea ? "E" : "e") +
(ri.lword_indicates_list_item ? "L" : "l") +
"]");
row.push_back(RtlEmbed(ri.rword_text, !ri.ltr) +
"[" + StrOf(ri.rword_box.width()) +
(ri.rword_likely_starts_idea ? "S" : "s") +
(ri.rword_likely_ends_idea ? "E" : "e") +
(ri.rword_indicates_list_item ? "L" : "l") +
"]");
rows[i].AppendDebugInfo(theory, &row);
row.push_back(RtlEmbed(ri.text, !ri.ltr));
}
PrintTable(output, " ");
tprintf("Active Paragraph Models:\n");
for (int m = 0; m < theory.models().size(); m++) {
tprintf(" %d: %s\n", m + 1, theory.models()[m]->ToString().string());
}
}
static void DebugDump(
bool should_print,
const STRING &phase,
const ParagraphTheory &theory,
const GenericVector<RowScratchRegisters> &rows) {
if (!should_print)
return;
tprintf("# %s\n", phase.string());
PrintDetectorState(theory, rows);
}
// Print out the text for rows[row_start, row_end)
static void PrintRowRange(const GenericVector<RowScratchRegisters> &rows,
int row_start, int row_end) {
tprintf("======================================\n");
for (int row = row_start; row < row_end; row++) {
tprintf("%s\n", rows[row].ri_->text.string());
}
tprintf("======================================\n");
}
// ============= Brain Dead Language Model (ASCII Version) ===================
static bool IsLatinLetter(int ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
static bool IsDigitLike(int ch) {
return ch == 'o' || ch == 'O' || ch == 'l' || ch == 'I';
}
static bool IsOpeningPunct(int ch) {
return strchr("'\"({[", ch) != nullptr;
}
static bool IsTerminalPunct(int ch) {
return strchr(":'\".?!]})", ch) != nullptr;
}
// Return a pointer after consuming as much text as qualifies as roman numeral.
static const char *SkipChars(const char *str, const char *toskip) {
while (*str != '\0' && strchr(toskip, *str)) { str++; }
return str;
}
static const char *SkipChars(const char *str, bool (*skip)(int)) {
while (*str != '\0' && skip(*str)) { str++; }
return str;
}
static const char *SkipOne(const char *str, const char *toskip) {
if (*str != '\0' && strchr(toskip, *str)) return str + 1;
return str;
}
// Return whether it is very likely that this is a numeral marker that could
// start a list item. Some examples include:
// A I iii. VI (2) 3.5. [C-4]
static bool LikelyListNumeral(const STRING &word) {
const char *kRomans = "ivxlmdIVXLMD";
const char *kDigits = "012345789";
const char *kOpen = "[{(";
const char *kSep = ":;-.,";
const char *kClose = "]})";
int num_segments = 0;
const char *pos = word.string();
while (*pos != '\0' && num_segments < 3) {
// skip up to two open parens.
const char *numeral_start = SkipOne(SkipOne(pos, kOpen), kOpen);
const char *numeral_end = SkipChars(numeral_start, kRomans);
if (numeral_end != numeral_start) {
// Got Roman Numeral. Great.
} else {
numeral_end = SkipChars(numeral_start, kDigits);
if (numeral_end == numeral_start) {
// If there's a single latin letter, we can use that.
numeral_end = SkipChars(numeral_start, IsLatinLetter);
if (numeral_end - numeral_start != 1)
break;
}
}
// We got some sort of numeral.
num_segments++;
// Skip any trailing parens or punctuation.
pos = SkipChars(SkipChars(numeral_end, kClose), kSep);
if (pos == numeral_end)
break;
}
return *pos == '\0';
}
static bool LikelyListMark(const STRING &word) {
const char *kListMarks = "0Oo*.,+.";
return word.size() == 1 && strchr(kListMarks, word[0]) != nullptr;
}
bool AsciiLikelyListItem(const STRING &word) {
return LikelyListMark(word) || LikelyListNumeral(word);
}
// ========== Brain Dead Language Model (Tesseract Version) ================
// Return the first Unicode Codepoint from werd[pos].
int UnicodeFor(const UNICHARSET *u, const WERD_CHOICE *werd, int pos) {
if (!u || !werd || pos > werd->length())
return 0;
return UNICHAR(u->id_to_unichar(werd->unichar_id(pos)), -1).first_uni();
}
// A useful helper class for finding the first j >= i so that word[j]
// does not have given character type.
class UnicodeSpanSkipper {
public:
UnicodeSpanSkipper(const UNICHARSET *unicharset, const WERD_CHOICE *word)
: u_(unicharset), word_(word) { wordlen_ = word->length(); }
// Given an input position, return the first position >= pos not punc.
int SkipPunc(int pos);
// Given an input position, return the first position >= pos not digit.
int SkipDigits(int pos);
// Given an input position, return the first position >= pos not roman.
int SkipRomans(int pos);
// Given an input position, return the first position >= pos not alpha.
int SkipAlpha(int pos);
private:
const UNICHARSET *u_;
const WERD_CHOICE *word_;
int wordlen_;
};
int UnicodeSpanSkipper::SkipPunc(int pos) {
while (pos < wordlen_ && u_->get_ispunctuation(word_->unichar_id(pos))) pos++;
return pos;
}
int UnicodeSpanSkipper::SkipDigits(int pos) {
while (pos < wordlen_ && (u_->get_isdigit(word_->unichar_id(pos)) ||
IsDigitLike(UnicodeFor(u_, word_, pos)))) pos++;
return pos;
}
int UnicodeSpanSkipper::SkipRomans(int pos) {
const char *kRomans = "ivxlmdIVXLMD";
while (pos < wordlen_) {
int ch = UnicodeFor(u_, word_, pos);
if (ch >= 0xF0 || strchr(kRomans, ch) == nullptr) break;
pos++;
}
return pos;
}
int UnicodeSpanSkipper::SkipAlpha(int pos) {
while (pos < wordlen_ && u_->get_isalpha(word_->unichar_id(pos))) pos++;
return pos;
}
static bool LikelyListMarkUnicode(int ch) {
if (ch < 0x80) {
STRING single_ch;
single_ch += ch;
return LikelyListMark(single_ch);
}
switch (ch) {
// TODO(eger) expand this list of unicodes as needed.
case 0x00B0: // degree sign
case 0x2022: // bullet
case 0x25E6: // white bullet
case 0x00B7: // middle dot
case 0x25A1: // white square
case 0x25A0: // black square
case 0x25AA: // black small square
case 0x2B1D: // black very small square
case 0x25BA: // black right-pointing pointer
case 0x25CF: // black circle
case 0x25CB: // white circle
return true;
default:
break; // fall through
}
return false;
}
// Return whether it is very likely that this is a numeral marker that could
// start a list item. Some examples include:
// A I iii. VI (2) 3.5. [C-4]
static bool UniLikelyListItem(const UNICHARSET *u, const WERD_CHOICE *werd) {
if (werd->length() == 1 && LikelyListMarkUnicode(UnicodeFor(u, werd, 0)))
return true;
UnicodeSpanSkipper m(u, werd);
int num_segments = 0;
int pos = 0;
while (pos < werd->length() && num_segments < 3) {
int numeral_start = m.SkipPunc(pos);
if (numeral_start > pos + 1) break;
int numeral_end = m.SkipRomans(numeral_start);
if (numeral_end == numeral_start) {
numeral_end = m.SkipDigits(numeral_start);
if (numeral_end == numeral_start) {
// If there's a single latin letter, we can use that.
numeral_end = m.SkipAlpha(numeral_start);
if (numeral_end - numeral_start != 1)
break;
}
}
// We got some sort of numeral.
num_segments++;
// Skip any trailing punctuation.
pos = m.SkipPunc(numeral_end);
if (pos == numeral_end)
break;
}
return pos == werd->length();
}
// ========= Brain Dead Language Model (combined entry points) ================
// Given the leftmost word of a line either as a Tesseract unicharset + werd
// or a utf8 string, set the following attributes for it:
// is_list - this word might be a list number or bullet.
// starts_idea - this word is likely to start a sentence.
// ends_idea - this word is likely to end a sentence.
void LeftWordAttributes(const UNICHARSET *unicharset, const WERD_CHOICE *werd,
const STRING &utf8,
bool *is_list, bool *starts_idea, bool *ends_idea) {
*is_list = false;
*starts_idea = false;
*ends_idea = false;
if (utf8.size() == 0 || (werd != nullptr && werd->length() == 0)) { // Empty
*ends_idea = true;
return;
}
if (unicharset && werd) { // We have a proper werd and unicharset so use it.
if (UniLikelyListItem(unicharset, werd)) {
*is_list = true;
*starts_idea = true;
*ends_idea = true;
}
if (unicharset->get_isupper(werd->unichar_id(0))) {
*starts_idea = true;
}
if (unicharset->get_ispunctuation(werd->unichar_id(0))) {
*starts_idea = true;
*ends_idea = true;
}
} else { // Assume utf8 is mostly ASCII
if (AsciiLikelyListItem(utf8)) {
*is_list = true;
*starts_idea = true;
}
int start_letter = utf8[0];
if (IsOpeningPunct(start_letter)) {
*starts_idea = true;
}
if (IsTerminalPunct(start_letter)) {
*ends_idea = true;
}
if (start_letter >= 'A' && start_letter <= 'Z') {
*starts_idea = true;
}
}
}
// Given the rightmost word of a line either as a Tesseract unicharset + werd
// or a utf8 string, set the following attributes for it:
// is_list - this word might be a list number or bullet.
// starts_idea - this word is likely to start a sentence.
// ends_idea - this word is likely to end a sentence.
void RightWordAttributes(const UNICHARSET *unicharset, const WERD_CHOICE *werd,
const STRING &utf8,
bool *is_list, bool *starts_idea, bool *ends_idea) {
*is_list = false;
*starts_idea = false;
*ends_idea = false;
if (utf8.size() == 0 || (werd != nullptr && werd->length() == 0)) { // Empty
*ends_idea = true;
return;
}
if (unicharset && werd) { // We have a proper werd and unicharset so use it.
if (UniLikelyListItem(unicharset, werd)) {
*is_list = true;
*starts_idea = true;
}
UNICHAR_ID last_letter = werd->unichar_id(werd->length() - 1);
if (unicharset->get_ispunctuation(last_letter)) {
*ends_idea = true;
}
} else { // Assume utf8 is mostly ASCII
if (AsciiLikelyListItem(utf8)) {
*is_list = true;
*starts_idea = true;
}
int last_letter = utf8[utf8.size() - 1];
if (IsOpeningPunct(last_letter) || IsTerminalPunct(last_letter)) {
*ends_idea = true;
}
}
}
// =============== Implementation of RowScratchRegisters =====================
/* static */
void RowScratchRegisters::AppendDebugHeaderFields(
GenericVector<STRING> *header) {
header->push_back("[lmarg,lind;rind,rmarg]");
header->push_back("model");
}
void RowScratchRegisters::AppendDebugInfo(const ParagraphTheory &theory,
GenericVector<STRING> *dbg) const {
char s[30];
snprintf(s, sizeof(s), "[%3d,%3d;%3d,%3d]",
lmargin_, lindent_, rindent_, rmargin_);
dbg->push_back(s);
STRING model_string;
model_string += static_cast<char>(GetLineType());
model_string += ":";
int model_numbers = 0;
for (int h = 0; h < hypotheses_.size(); h++) {
if (hypotheses_[h].model == nullptr)
continue;
if (model_numbers > 0)
model_string += ",";
if (StrongModel(hypotheses_[h].model)) {
model_string += StrOf(1 + theory.IndexOf(hypotheses_[h].model));
} else if (hypotheses_[h].model == kCrownLeft) {
model_string += "CrL";
} else if (hypotheses_[h].model == kCrownRight) {
model_string += "CrR";
}
model_numbers++;
}
if (model_numbers == 0)
model_string += "0";
dbg->push_back(model_string);
}
void RowScratchRegisters::Init(const RowInfo &row) {
ri_ = &row;
lmargin_ = 0;
lindent_ = row.pix_ldistance;
rmargin_ = 0;
rindent_ = row.pix_rdistance;
}
LineType RowScratchRegisters::GetLineType() const {
if (hypotheses_.empty())
return LT_UNKNOWN;
bool has_start = false;
bool has_body = false;
for (int i = 0; i < hypotheses_.size(); i++) {
switch (hypotheses_[i].ty) {
case LT_START: has_start = true; break;
case LT_BODY: has_body = true; break;
default:
tprintf("Encountered bad value in hypothesis list: %c\n",
hypotheses_[i].ty);
break;
}
}
if (has_start && has_body)
return LT_MULTIPLE;
return has_start ? LT_START : LT_BODY;
}
LineType RowScratchRegisters::GetLineType(const ParagraphModel *model) const {
if (hypotheses_.empty())
return LT_UNKNOWN;
bool has_start = false;
bool has_body = false;
for (int i = 0; i < hypotheses_.size(); i++) {
if (hypotheses_[i].model != model)
continue;
switch (hypotheses_[i].ty) {
case LT_START: has_start = true; break;
case LT_BODY: has_body = true; break;
default:
tprintf("Encountered bad value in hypothesis list: %c\n",
hypotheses_[i].ty);
break;
}
}
if (has_start && has_body)
return LT_MULTIPLE;
return has_start ? LT_START : LT_BODY;
}
void RowScratchRegisters::SetStartLine() {
LineType current_lt = GetLineType();
if (current_lt != LT_UNKNOWN && current_lt != LT_START) {
tprintf("Trying to set a line to be START when it's already BODY.\n");
}
if (current_lt == LT_UNKNOWN || current_lt == LT_BODY) {
hypotheses_.push_back_new(LineHypothesis(LT_START, nullptr));
}
}
void RowScratchRegisters::SetBodyLine() {
LineType current_lt = GetLineType();
if (current_lt != LT_UNKNOWN && current_lt != LT_BODY) {
tprintf("Trying to set a line to be BODY when it's already START.\n");
}
if (current_lt == LT_UNKNOWN || current_lt == LT_START) {
hypotheses_.push_back_new(LineHypothesis(LT_BODY, nullptr));
}
}
void RowScratchRegisters::AddStartLine(const ParagraphModel *model) {
hypotheses_.push_back_new(LineHypothesis(LT_START, model));
int old_idx = hypotheses_.get_index(LineHypothesis(LT_START, nullptr));
if (old_idx >= 0)
hypotheses_.remove(old_idx);
}
void RowScratchRegisters::AddBodyLine(const ParagraphModel *model) {
hypotheses_.push_back_new(LineHypothesis(LT_BODY, model));
int old_idx = hypotheses_.get_index(LineHypothesis(LT_BODY, nullptr));
if (old_idx >= 0)
hypotheses_.remove(old_idx);
}
void RowScratchRegisters::StartHypotheses(SetOfModels *models) const {
for (int h = 0; h < hypotheses_.size(); h++) {
if (hypotheses_[h].ty == LT_START && StrongModel(hypotheses_[h].model))
models->push_back_new(hypotheses_[h].model);
}
}
void RowScratchRegisters::StrongHypotheses(SetOfModels *models) const {
for (int h = 0; h < hypotheses_.size(); h++) {
if (StrongModel(hypotheses_[h].model))
models->push_back_new(hypotheses_[h].model);
}
}
void RowScratchRegisters::NonNullHypotheses(SetOfModels *models) const {
for (int h = 0; h < hypotheses_.size(); h++) {
if (hypotheses_[h].model != nullptr)
models->push_back_new(hypotheses_[h].model);
}
}
const ParagraphModel *RowScratchRegisters::UniqueStartHypothesis() const {
if (hypotheses_.size() != 1 || hypotheses_[0].ty != LT_START)
return nullptr;
return hypotheses_[0].model;
}
const ParagraphModel *RowScratchRegisters::UniqueBodyHypothesis() const {
if (hypotheses_.size() != 1 || hypotheses_[0].ty != LT_BODY)
return nullptr;
return hypotheses_[0].model;
}
// Discard any hypotheses whose model is not in the given list.
void RowScratchRegisters::DiscardNonMatchingHypotheses(
const SetOfModels &models) {
if (models.empty())
return;
for (int h = hypotheses_.size() - 1; h >= 0; h--) {
if (!models.contains(hypotheses_[h].model)) {
hypotheses_.remove(h);
}
}
}
// ============ Geometry based Paragraph Detection Algorithm =================
struct Cluster {
Cluster() : center(0), count(0) {}
Cluster(int cen, int num) : center(cen), count(num) {}
int center; // The center of the cluster.
int count; // The number of entries within the cluster.
};
class SimpleClusterer {
public:
explicit SimpleClusterer(int max_cluster_width)
: max_cluster_width_(max_cluster_width) {}
void Add(int value) { values_.push_back(value); }
int size() const { return values_.size(); }
void GetClusters(GenericVector<Cluster> *clusters);
private:
int max_cluster_width_;
GenericVectorEqEq<int> values_;
};
// Return the index of the cluster closest to value.
static int ClosestCluster(const GenericVector<Cluster> &clusters, int value) {
int best_index = 0;
for (int i = 0; i < clusters.size(); i++) {
if (abs(value - clusters[i].center) <
abs(value - clusters[best_index].center))
best_index = i;
}
return best_index;
}
void SimpleClusterer::GetClusters(GenericVector<Cluster> *clusters) {
clusters->clear();
values_.sort();
for (int i = 0; i < values_.size();) {
int orig_i = i;
int lo = values_[i];
int hi = lo;
while (++i < values_.size() && values_[i] <= lo + max_cluster_width_) {
hi = values_[i];
}
clusters->push_back(Cluster((hi + lo) / 2, i - orig_i));
}
}
// Calculate left- and right-indent tab stop values seen in
// rows[row_start, row_end) given a tolerance of tolerance.
static void CalculateTabStops(GenericVector<RowScratchRegisters> *rows,
int row_start, int row_end, int tolerance,
GenericVector<Cluster> *left_tabs,
GenericVector<Cluster> *right_tabs) {
if (!AcceptableRowArgs(0, 1, __func__, rows, row_start, row_end))
return;
// First pass: toss all left and right indents into clusterers.
SimpleClusterer initial_lefts(tolerance);
SimpleClusterer initial_rights(tolerance);
GenericVector<Cluster> initial_left_tabs;
GenericVector<Cluster> initial_right_tabs;
for (int i = row_start; i < row_end; i++) {
initial_lefts.Add((*rows)[i].lindent_);
initial_rights.Add((*rows)[i].rindent_);
}
initial_lefts.GetClusters(&initial_left_tabs);
initial_rights.GetClusters(&initial_right_tabs);
// Second pass: cluster only lines that are not "stray"
// An example of a stray line is a page number -- a line whose start
// and end tab-stops are far outside the typical start and end tab-stops
// for the block.
// Put another way, we only cluster data from lines whose start or end
// tab stop is frequent.
SimpleClusterer lefts(tolerance);
SimpleClusterer rights(tolerance);
// Outlier elimination. We might want to switch this to test outlier-ness
// based on how strange a position an outlier is in instead of or in addition
// to how rare it is. These outliers get re-added if we end up having too
// few tab stops, to work with, however.
int infrequent_enough_to_ignore = 0;
if (row_end - row_start >= 8) infrequent_enough_to_ignore = 1;
if (row_end - row_start >= 20) infrequent_enough_to_ignore = 2;
for (int i = row_start; i < row_end; i++) {
int lidx = ClosestCluster(initial_left_tabs, (*rows)[i].lindent_);
int ridx = ClosestCluster(initial_right_tabs, (*rows)[i].rindent_);
if (initial_left_tabs[lidx].count > infrequent_enough_to_ignore ||
initial_right_tabs[ridx].count > infrequent_enough_to_ignore) {
lefts.Add((*rows)[i].lindent_);
rights.Add((*rows)[i].rindent_);
}
}
lefts.GetClusters(left_tabs);
rights.GetClusters(right_tabs);
if ((left_tabs->size() == 1 && right_tabs->size() >= 4) ||
(right_tabs->size() == 1 && left_tabs->size() >= 4)) {
// One side is really ragged, and the other only has one tab stop,
// so those "insignificant outliers" are probably important, actually.
// This often happens on a page of an index. Add back in the ones
// we omitted in the first pass.
for (int i = row_start; i < row_end; i++) {
int lidx = ClosestCluster(initial_left_tabs, (*rows)[i].lindent_);
int ridx = ClosestCluster(initial_right_tabs, (*rows)[i].rindent_);
if (!(initial_left_tabs[lidx].count > infrequent_enough_to_ignore ||
initial_right_tabs[ridx].count > infrequent_enough_to_ignore)) {
lefts.Add((*rows)[i].lindent_);
rights.Add((*rows)[i].rindent_);
}
}
}
lefts.GetClusters(left_tabs);
rights.GetClusters(right_tabs);
// If one side is almost a two-indent aligned side, and the other clearly
// isn't, try to prune out the least frequent tab stop from that side.
if (left_tabs->size() == 3 && right_tabs->size() >= 4) {
int to_prune = -1;
for (int i = left_tabs->size() - 1; i >= 0; i--) {
if (to_prune < 0 ||
(*left_tabs)[i].count < (*left_tabs)[to_prune].count) {
to_prune = i;
}
}
if (to_prune >= 0 &&
(*left_tabs)[to_prune].count <= infrequent_enough_to_ignore) {
left_tabs->remove(to_prune);
}
}
if (right_tabs->size() == 3 && left_tabs->size() >= 4) {
int to_prune = -1;
for (int i = right_tabs->size() - 1; i >= 0; i--) {
if (to_prune < 0 ||
(*right_tabs)[i].count < (*right_tabs)[to_prune].count) {
to_prune = i;
}
}
if (to_prune >= 0 &&
(*right_tabs)[to_prune].count <= infrequent_enough_to_ignore) {
right_tabs->remove(to_prune);
}
}
}
// Given a paragraph model mark rows[row_start, row_end) as said model
// start or body lines.
//
// Case 1: model->first_indent_ != model->body_indent_
// Differentiating the paragraph start lines from the paragraph body lines in
// this case is easy, we just see how far each line is indented.
//
// Case 2: model->first_indent_ == model->body_indent_
// Here, we find end-of-paragraph lines by looking for "short lines."
// What constitutes a "short line" changes depending on whether the text
// ragged-right[left] or fully justified (aligned left and right).
//
// Case 2a: Ragged Right (or Left) text. (eop_threshold == 0)
// We have a new paragraph it the first word would have at the end
// of the previous line.
//
// Case 2b: Fully Justified. (eop_threshold > 0)
// We mark a line as short (end of paragraph) if the offside indent
// is greater than eop_threshold.
static void MarkRowsWithModel(GenericVector<RowScratchRegisters> *rows,
int row_start, int row_end,
const ParagraphModel *model,
bool ltr, int eop_threshold) {
if (!AcceptableRowArgs(0, 0, __func__, rows, row_start, row_end))
return;
for (int row = row_start; row < row_end; row++) {
bool valid_first = ValidFirstLine(rows, row, model);
bool valid_body = ValidBodyLine(rows, row, model);
if (valid_first && !valid_body) {
(*rows)[row].AddStartLine(model);
} else if (valid_body && !valid_first) {
(*rows)[row].AddBodyLine(model);
} else if (valid_body && valid_first) {
bool after_eop = (row == row_start);
if (row > row_start) {
if (eop_threshold > 0) {
if (model->justification() == JUSTIFICATION_LEFT) {
after_eop = (*rows)[row - 1].rindent_ > eop_threshold;
} else {
after_eop = (*rows)[row - 1].lindent_ > eop_threshold;
}
} else {
after_eop = FirstWordWouldHaveFit((*rows)[row - 1], (*rows)[row],
model->justification());
}
}
if (after_eop) {
(*rows)[row].AddStartLine(model);
} else {
(*rows)[row].AddBodyLine(model);
}
} else {
// Do nothing. Stray row.
}
}
}
// GeometricClassifierState holds all of the information we'll use while
// trying to determine a paragraph model for the text lines in a block of
// text:
// + the rows under consideration [row_start, row_end)
// + the common left- and right-indent tab stops
// + does the block start out left-to-right or right-to-left
// Further, this struct holds the data we amass for the (single) ParagraphModel
// we'll assign to the text lines (assuming we get that far).
struct GeometricClassifierState {
GeometricClassifierState(int dbg_level,
GenericVector<RowScratchRegisters> *r,
int r_start, int r_end)
: debug_level(dbg_level), rows(r), row_start(r_start), row_end(r_end),
margin(0) {
tolerance = InterwordSpace(*r, r_start, r_end);
CalculateTabStops(r, r_start, r_end, tolerance,
&left_tabs, &right_tabs);
if (debug_level >= 3) {
tprintf("Geometry: TabStop cluster tolerance = %d; "
"%d left tabs; %d right tabs\n",
tolerance, left_tabs.size(), right_tabs.size());
}
ltr = (*r)[r_start].ri_->ltr;
}
void AssumeLeftJustification() {
just = tesseract::JUSTIFICATION_LEFT;
margin = (*rows)[row_start].lmargin_;
}
void AssumeRightJustification() {
just = tesseract::JUSTIFICATION_RIGHT;
margin = (*rows)[row_start].rmargin_;
}
// Align tabs are the tab stops the text is aligned to.
const GenericVector<Cluster> &AlignTabs() const {
if (just == tesseract::JUSTIFICATION_RIGHT) return right_tabs;
return left_tabs;
}
// Offside tabs are the tab stops opposite the tabs used to align the text.
//
// Note that for a left-to-right text which is aligned to the right such as
// this function comment, the offside tabs are the horizontal tab stops
// marking the beginning of ("Note", "this" and "marking").
const GenericVector<Cluster> &OffsideTabs() const {
if (just == tesseract::JUSTIFICATION_RIGHT) return left_tabs;
return right_tabs;
}
// Return whether the i'th row extends from the leftmost left tab stop
// to the right most right tab stop.
bool IsFullRow(int i) const {
return ClosestCluster(left_tabs, (*rows)[i].lindent_) == 0 &&
ClosestCluster(right_tabs, (*rows)[i].rindent_) == 0;
}
int AlignsideTabIndex(int row_idx) const {
return ClosestCluster(AlignTabs(), (*rows)[row_idx].AlignsideIndent(just));
}
// Given what we know about the paragraph justification (just), would the
// first word of row_b have fit at the end of row_a?
bool FirstWordWouldHaveFit(int row_a, int row_b) {
return ::tesseract::FirstWordWouldHaveFit(
(*rows)[row_a], (*rows)[row_b], just);
}
void PrintRows() const { PrintRowRange(*rows, row_start, row_end); }
void Fail(int min_debug_level, const char *why) const {
if (debug_level < min_debug_level) return;
tprintf("# %s\n", why);
PrintRows();
}
ParagraphModel Model() const {
return ParagraphModel(just, margin, first_indent, body_indent, tolerance);
}
// We print out messages with a debug level at least as great as debug_level.
int debug_level;
// The Geometric Classifier was asked to find a single paragraph model
// to fit the text rows (*rows)[row_start, row_end)
GenericVector<RowScratchRegisters> *rows;
int row_start;
int row_end;
// The amount by which we expect the text edge can vary and still be aligned.
int tolerance;
// Is the script in this text block left-to-right?
// HORRIBLE ROUGH APPROXIMATION. TODO(eger): Improve
bool ltr;
// These left and right tab stops were determined to be the common tab
// stops for the given text.
GenericVector<Cluster> left_tabs;
GenericVector<Cluster> right_tabs;
// These are parameters we must determine to create a ParagraphModel.
tesseract::ParagraphJustification just;
int margin;
int first_indent;
int body_indent;
// eop_threshold > 0 if the text is fully justified. See MarkRowsWithModel()
int eop_threshold;
};
// Given a section of text where strong textual clues did not help identifying
// paragraph breaks, and for which the left and right indents have exactly
// three tab stops between them, attempt to find the paragraph breaks based
// solely on the outline of the text and whether the script is left-to-right.
//
// Algorithm Detail:
// The selected rows are in the form of a rectangle except
// for some number of "short lines" of the same length:
//
// (A1) xxxxxxxxxxxxx (B1) xxxxxxxxxxxx
// xxxxxxxxxxx xxxxxxxxxx # A "short" line.
// xxxxxxxxxxxxx xxxxxxxxxxxx
// xxxxxxxxxxxxx xxxxxxxxxxxx
//
// We have a slightly different situation if the only short
// line is at the end of the excerpt.
//
// (A2) xxxxxxxxxxxxx (B2) xxxxxxxxxxxx
// xxxxxxxxxxxxx xxxxxxxxxxxx
// xxxxxxxxxxxxx xxxxxxxxxxxx
// xxxxxxxxxxx xxxxxxxxxx # A "short" line.
//
// We'll interpret these as follows based on the reasoning in the comment for
// GeometricClassify():
// [script direction: first indent, body indent]
// (A1) LtR: 2,0 RtL: 0,0 (B1) LtR: 0,0 RtL: 2,0
// (A2) LtR: 2,0 RtL: CrR (B2) LtR: CrL RtL: 2,0
static void GeometricClassifyThreeTabStopTextBlock(
int debug_level,
GeometricClassifierState &s,