-
Notifications
You must be signed in to change notification settings - Fork 9.6k
/
Copy pathrecodebeam.cpp
1384 lines (1341 loc) · 53 KB
/
recodebeam.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: recodebeam.cpp
// Description: Beam search to decode from the re-encoded CJK as a sequence of
// smaller numbers in place of a single large code.
// Author: Ray Smith
//
// (C) Copyright 2015, 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 "recodebeam.h"
#include "networkio.h"
#include "pageres.h"
#include "unicharcompress.h"
#include <algorithm> // for std::reverse
namespace tesseract {
// The beam width at each code position.
const int RecodeBeamSearch::kBeamWidths[RecodedCharID::kMaxCodeLen + 1] = {
5, 10, 16, 16, 16, 16, 16, 16, 16, 16,
};
static const char *kNodeContNames[] = {"Anything", "OnlyDup", "NoDup"};
// Prints debug details of the node.
void RecodeNode::Print(int null_char, const UNICHARSET &unicharset,
int depth) const {
if (code == null_char) {
tprintf("null_char");
} else {
tprintf("label=%d, uid=%d=%s", code, unichar_id,
unicharset.debug_str(unichar_id).c_str());
}
tprintf(" score=%g, c=%g,%s%s%s perm=%d, hash=%" PRIx64, score, certainty,
start_of_dawg ? " DawgStart" : "", start_of_word ? " Start" : "",
end_of_word ? " End" : "", permuter, code_hash);
if (depth > 0 && prev != nullptr) {
tprintf(" prev:");
prev->Print(null_char, unicharset, depth - 1);
} else {
tprintf("\n");
}
}
// Borrows the pointer, which is expected to survive until *this is deleted.
RecodeBeamSearch::RecodeBeamSearch(const UnicharCompress &recoder,
int null_char, bool simple_text, Dict *dict)
: recoder_(recoder),
beam_size_(0),
top_code_(-1),
second_code_(-1),
dict_(dict),
space_delimited_(true),
is_simple_text_(simple_text),
null_char_(null_char) {
if (dict_ != nullptr && !dict_->IsSpaceDelimitedLang()) {
space_delimited_ = false;
}
}
RecodeBeamSearch::~RecodeBeamSearch() {
for (auto data : beam_) {
delete data;
}
for (auto data : secondary_beam_) {
delete data;
}
}
// Decodes the set of network outputs, storing the lattice internally.
void RecodeBeamSearch::Decode(const NetworkIO &output, double dict_ratio,
double cert_offset, double worst_dict_cert,
const UNICHARSET *charset, int lstm_choice_mode) {
beam_size_ = 0;
int width = output.Width();
if (lstm_choice_mode) {
timesteps.clear();
}
for (int t = 0; t < width; ++t) {
ComputeTopN(output.f(t), output.NumFeatures(), kBeamWidths[0]);
DecodeStep(output.f(t), t, dict_ratio, cert_offset, worst_dict_cert,
charset);
if (lstm_choice_mode) {
SaveMostCertainChoices(output.f(t), output.NumFeatures(), charset, t);
}
}
}
void RecodeBeamSearch::Decode(const GENERIC_2D_ARRAY<float> &output,
double dict_ratio, double cert_offset,
double worst_dict_cert,
const UNICHARSET *charset) {
beam_size_ = 0;
int width = output.dim1();
for (int t = 0; t < width; ++t) {
ComputeTopN(output[t], output.dim2(), kBeamWidths[0]);
DecodeStep(output[t], t, dict_ratio, cert_offset, worst_dict_cert, charset);
}
}
void RecodeBeamSearch::DecodeSecondaryBeams(
const NetworkIO &output, double dict_ratio, double cert_offset,
double worst_dict_cert, const UNICHARSET *charset, int lstm_choice_mode) {
for (auto data : secondary_beam_) {
delete data;
}
secondary_beam_.clear();
if (character_boundaries_.size() < 2) {
return;
}
int width = output.Width();
unsigned bucketNumber = 0;
for (int t = 0; t < width; ++t) {
while ((bucketNumber + 1) < character_boundaries_.size() &&
t >= character_boundaries_[bucketNumber + 1]) {
++bucketNumber;
}
ComputeSecTopN(&(excludedUnichars)[bucketNumber], output.f(t),
output.NumFeatures(), kBeamWidths[0]);
DecodeSecondaryStep(output.f(t), t, dict_ratio, cert_offset,
worst_dict_cert, charset);
}
}
void RecodeBeamSearch::SaveMostCertainChoices(const float *outputs,
int num_outputs,
const UNICHARSET *charset,
int xCoord) {
std::vector<std::pair<const char *, float>> choices;
for (int i = 0; i < num_outputs; ++i) {
if (outputs[i] >= 0.01f) {
const char *character;
if (i + 2 >= num_outputs) {
character = "";
} else if (i > 0) {
character = charset->id_to_unichar_ext(i + 2);
} else {
character = charset->id_to_unichar_ext(i);
}
size_t pos = 0;
// order the possible choices within one timestep
// beginning with the most likely
while (choices.size() > pos && choices[pos].second > outputs[i]) {
pos++;
}
choices.insert(choices.begin() + pos,
std::pair<const char *, float>(character, outputs[i]));
}
}
timesteps.push_back(choices);
}
void RecodeBeamSearch::segmentTimestepsByCharacters() {
for (unsigned i = 1; i < character_boundaries_.size(); ++i) {
std::vector<std::vector<std::pair<const char *, float>>> segment;
for (int j = character_boundaries_[i - 1]; j < character_boundaries_[i];
++j) {
segment.push_back(timesteps[j]);
}
segmentedTimesteps.push_back(segment);
}
}
std::vector<std::vector<std::pair<const char *, float>>>
RecodeBeamSearch::combineSegmentedTimesteps(
std::vector<std::vector<std::vector<std::pair<const char *, float>>>>
*segmentedTimesteps) {
std::vector<std::vector<std::pair<const char *, float>>> combined_timesteps;
for (auto &segmentedTimestep : *segmentedTimesteps) {
for (auto &j : segmentedTimestep) {
combined_timesteps.push_back(j);
}
}
return combined_timesteps;
}
void RecodeBeamSearch::calculateCharBoundaries(std::vector<int> *starts,
std::vector<int> *ends,
std::vector<int> *char_bounds_,
int maxWidth) {
char_bounds_->push_back(0);
for (unsigned i = 0; i < ends->size(); ++i) {
int middle = ((*starts)[i + 1] - (*ends)[i]) / 2;
char_bounds_->push_back((*ends)[i] + middle);
}
char_bounds_->pop_back();
char_bounds_->push_back(maxWidth);
}
// Returns the best path as labels/scores/xcoords similar to simple CTC.
void RecodeBeamSearch::ExtractBestPathAsLabels(
std::vector<int> *labels, std::vector<int> *xcoords) const {
labels->clear();
xcoords->clear();
std::vector<const RecodeNode *> best_nodes;
ExtractBestPaths(&best_nodes, nullptr);
// Now just run CTC on the best nodes.
int t = 0;
int width = best_nodes.size();
while (t < width) {
int label = best_nodes[t]->code;
if (label != null_char_) {
labels->push_back(label);
xcoords->push_back(t);
}
while (++t < width && !is_simple_text_ && best_nodes[t]->code == label) {
}
}
xcoords->push_back(width);
}
// Returns the best path as unichar-ids/certs/ratings/xcoords skipping
// duplicates, nulls and intermediate parts.
void RecodeBeamSearch::ExtractBestPathAsUnicharIds(
bool debug, const UNICHARSET *unicharset, std::vector<int> *unichar_ids,
std::vector<float> *certs, std::vector<float> *ratings,
std::vector<int> *xcoords) const {
std::vector<const RecodeNode *> best_nodes;
ExtractBestPaths(&best_nodes, nullptr);
ExtractPathAsUnicharIds(best_nodes, unichar_ids, certs, ratings, xcoords);
if (debug) {
DebugPath(unicharset, best_nodes);
DebugUnicharPath(unicharset, best_nodes, *unichar_ids, *certs, *ratings,
*xcoords);
}
}
// Returns the best path as a set of WERD_RES.
void RecodeBeamSearch::ExtractBestPathAsWords(const TBOX &line_box,
float scale_factor, bool debug,
const UNICHARSET *unicharset,
PointerVector<WERD_RES> *words,
int lstm_choice_mode) {
words->truncate(0);
std::vector<int> unichar_ids;
std::vector<float> certs;
std::vector<float> ratings;
std::vector<int> xcoords;
std::vector<const RecodeNode *> best_nodes;
std::vector<const RecodeNode *> second_nodes;
character_boundaries_.clear();
ExtractBestPaths(&best_nodes, &second_nodes);
if (debug) {
DebugPath(unicharset, best_nodes);
ExtractPathAsUnicharIds(second_nodes, &unichar_ids, &certs, &ratings,
&xcoords);
tprintf("\nSecond choice path:\n");
DebugUnicharPath(unicharset, second_nodes, unichar_ids, certs, ratings,
xcoords);
}
// If lstm choice mode is required in granularity level 2, it stores the x
// Coordinates of every chosen character, to match the alternative choices to
// it.
ExtractPathAsUnicharIds(best_nodes, &unichar_ids, &certs, &ratings, &xcoords,
&character_boundaries_);
int num_ids = unichar_ids.size();
if (debug) {
DebugUnicharPath(unicharset, best_nodes, unichar_ids, certs, ratings,
xcoords);
}
// Convert labels to unichar-ids.
int word_end = 0;
float prev_space_cert = 0.0f;
for (int word_start = 0; word_start < num_ids; word_start = word_end) {
for (word_end = word_start + 1; word_end < num_ids; ++word_end) {
// A word is terminated when a space character or start_of_word flag is
// hit. We also want to force a separate word for every non
// space-delimited character when not in a dictionary context.
if (unichar_ids[word_end] == UNICHAR_SPACE) {
break;
}
int index = xcoords[word_end];
if (best_nodes[index]->start_of_word) {
break;
}
if (best_nodes[index]->permuter == TOP_CHOICE_PERM &&
(!unicharset->IsSpaceDelimited(unichar_ids[word_end]) ||
!unicharset->IsSpaceDelimited(unichar_ids[word_end - 1]))) {
break;
}
}
float space_cert = 0.0f;
if (word_end < num_ids && unichar_ids[word_end] == UNICHAR_SPACE) {
space_cert = certs[word_end];
}
bool leading_space =
word_start > 0 && unichar_ids[word_start - 1] == UNICHAR_SPACE;
// Create a WERD_RES for the output word.
WERD_RES *word_res =
InitializeWord(leading_space, line_box, word_start, word_end,
std::min(space_cert, prev_space_cert), unicharset,
xcoords, scale_factor);
for (int i = word_start; i < word_end; ++i) {
auto *choices = new BLOB_CHOICE_LIST;
BLOB_CHOICE_IT bc_it(choices);
auto *choice = new BLOB_CHOICE(unichar_ids[i], ratings[i], certs[i], -1,
1.0f, static_cast<float>(INT16_MAX), 0.0f,
BCC_STATIC_CLASSIFIER);
int col = i - word_start;
choice->set_matrix_cell(col, col);
bc_it.add_after_then_move(choice);
word_res->ratings->put(col, col, choices);
}
int index = xcoords[word_end - 1];
word_res->FakeWordFromRatings(best_nodes[index]->permuter);
words->push_back(word_res);
prev_space_cert = space_cert;
if (word_end < num_ids && unichar_ids[word_end] == UNICHAR_SPACE) {
++word_end;
}
}
}
struct greater_than {
inline bool operator()(const RecodeNode *&node1, const RecodeNode *&node2) const {
return (node1->score > node2->score);
}
};
void RecodeBeamSearch::PrintBeam2(bool uids, int num_outputs,
const UNICHARSET *charset,
bool secondary) const {
std::vector<std::vector<const RecodeNode *>> topology;
std::unordered_set<const RecodeNode *> visited;
const std::vector<RecodeBeam *> &beam = !secondary ? beam_ : secondary_beam_;
// create the topology
for (int step = beam.size() - 1; step >= 0; --step) {
std::vector<const RecodeNode *> layer;
topology.push_back(layer);
}
// fill the topology with depths first
for (int step = beam.size() - 1; step >= 0; --step) {
std::vector<tesseract::RecodePair> &heaps = beam.at(step)->beams_->heap();
for (auto &&node : heaps) {
int backtracker = 0;
const RecodeNode *curr = &node.data();
while (curr != nullptr && !visited.count(curr)) {
visited.insert(curr);
topology[step - backtracker].push_back(curr);
curr = curr->prev;
++backtracker;
}
}
}
int ct = 0;
unsigned cb = 1;
for (const std::vector<const RecodeNode *> &layer : topology) {
if (cb >= character_boundaries_.size()) {
break;
}
if (ct == character_boundaries_[cb]) {
tprintf("***\n");
++cb;
}
for (const RecodeNode *node : layer) {
const char *code;
int intCode;
if (node->unichar_id != INVALID_UNICHAR_ID) {
code = charset->id_to_unichar(node->unichar_id);
intCode = node->unichar_id;
} else if (node->code == null_char_) {
intCode = 0;
code = " ";
} else {
intCode = 666;
code = "*";
}
int intPrevCode = 0;
const char *prevCode;
float prevScore = 0;
if (node->prev != nullptr) {
prevScore = node->prev->score;
if (node->prev->unichar_id != INVALID_UNICHAR_ID) {
prevCode = charset->id_to_unichar(node->prev->unichar_id);
intPrevCode = node->prev->unichar_id;
} else if (node->code == null_char_) {
intPrevCode = 0;
prevCode = " ";
} else {
prevCode = "*";
intPrevCode = 666;
}
} else {
prevCode = " ";
}
if (uids) {
tprintf("%x(|)%f(>)%x(|)%f\n", intPrevCode, prevScore, intCode,
node->score);
} else {
tprintf("%s(|)%f(>)%s(|)%f\n", prevCode, prevScore, code, node->score);
}
}
tprintf("-\n");
++ct;
}
tprintf("***\n");
}
void RecodeBeamSearch::extractSymbolChoices(const UNICHARSET *unicharset) {
if (character_boundaries_.size() < 2) {
return;
}
// For the first iteration the original beam is analyzed. After that a
// new beam is calculated based on the results from the original beam.
std::vector<RecodeBeam *> ¤tBeam =
secondary_beam_.empty() ? beam_ : secondary_beam_;
character_boundaries_[0] = 0;
for (unsigned j = 1; j < character_boundaries_.size(); ++j) {
std::vector<int> unichar_ids;
std::vector<float> certs;
std::vector<float> ratings;
std::vector<int> xcoords;
int backpath = character_boundaries_[j] - character_boundaries_[j - 1];
std::vector<tesseract::RecodePair> &heaps =
currentBeam.at(character_boundaries_[j] - 1)->beams_->heap();
std::vector<const RecodeNode *> best_nodes;
std::vector<const RecodeNode *> best;
// Scan the segmented node chain for valid unichar ids.
for (auto &&entry : heaps) {
bool validChar = false;
int backcounter = 0;
const RecodeNode *node = &entry.data();
while (node != nullptr && backcounter < backpath) {
if (node->code != null_char_ &&
node->unichar_id != INVALID_UNICHAR_ID) {
validChar = true;
break;
}
node = node->prev;
++backcounter;
}
if (validChar) {
best.push_back(&entry.data());
}
}
// find the best rated segmented node chain and extract the unichar id.
if (!best.empty()) {
std::sort(best.begin(), best.end(), greater_than());
ExtractPath(best[0], &best_nodes, backpath);
ExtractPathAsUnicharIds(best_nodes, &unichar_ids, &certs, &ratings,
&xcoords);
}
if (!unichar_ids.empty()) {
int bestPos = 0;
for (unsigned i = 1; i < unichar_ids.size(); ++i) {
if (ratings[i] < ratings[bestPos]) {
bestPos = i;
}
}
#if 0 // TODO: bestCode is currently unused (see commit 2dd5d0d60).
int bestCode = -10;
for (auto &node : best_nodes) {
if (node->unichar_id == unichar_ids[bestPos]) {
bestCode = node->code;
}
}
#endif
// Exclude the best choice for the followup decoding.
std::unordered_set<int> excludeCodeList;
for (auto &best_node : best_nodes) {
if (best_node->code != null_char_) {
excludeCodeList.insert(best_node->code);
}
}
if (j - 1 < excludedUnichars.size()) {
for (auto elem : excludeCodeList) {
excludedUnichars[j - 1].insert(elem);
}
} else {
excludedUnichars.push_back(excludeCodeList);
}
// Save the best choice for the choice iterator.
if (j - 1 < ctc_choices.size()) {
int id = unichar_ids[bestPos];
const char *result = unicharset->id_to_unichar_ext(id);
float rating = ratings[bestPos];
ctc_choices[j - 1].push_back(
std::pair<const char *, float>(result, rating));
} else {
std::vector<std::pair<const char *, float>> choice;
int id = unichar_ids[bestPos];
const char *result = unicharset->id_to_unichar_ext(id);
float rating = ratings[bestPos];
choice.emplace_back(result, rating);
ctc_choices.push_back(choice);
}
// fill the blank spot with an empty array
} else {
if (j - 1 >= excludedUnichars.size()) {
std::unordered_set<int> excludeCodeList;
excludedUnichars.push_back(excludeCodeList);
}
if (j - 1 >= ctc_choices.size()) {
std::vector<std::pair<const char *, float>> choice;
ctc_choices.push_back(choice);
}
}
}
for (auto data : secondary_beam_) {
delete data;
}
secondary_beam_.clear();
}
// Generates debug output of the content of the beams after a Decode.
void RecodeBeamSearch::DebugBeams(const UNICHARSET &unicharset) const {
for (int p = 0; p < beam_size_; ++p) {
for (int d = 0; d < 2; ++d) {
for (int c = 0; c < NC_COUNT; ++c) {
auto cont = static_cast<NodeContinuation>(c);
int index = BeamIndex(d, cont, 0);
if (beam_[p]->beams_[index].empty()) {
continue;
}
// Print all the best scoring nodes for each unichar found.
tprintf("Position %d: %s+%s beam\n", p, d ? "Dict" : "Non-Dict",
kNodeContNames[c]);
DebugBeamPos(unicharset, beam_[p]->beams_[index]);
}
}
}
}
// Generates debug output of the content of a single beam position.
void RecodeBeamSearch::DebugBeamPos(const UNICHARSET &unicharset,
const RecodeHeap &heap) const {
std::vector<const RecodeNode *> unichar_bests(unicharset.size());
const RecodeNode *null_best = nullptr;
int heap_size = heap.size();
for (int i = 0; i < heap_size; ++i) {
const RecodeNode *node = &heap.get(i).data();
if (node->unichar_id == INVALID_UNICHAR_ID) {
if (null_best == nullptr || null_best->score < node->score) {
null_best = node;
}
} else {
if (unichar_bests[node->unichar_id] == nullptr ||
unichar_bests[node->unichar_id]->score < node->score) {
unichar_bests[node->unichar_id] = node;
}
}
}
for (auto &unichar_best : unichar_bests) {
if (unichar_best != nullptr) {
const RecodeNode &node = *unichar_best;
node.Print(null_char_, unicharset, 1);
}
}
if (null_best != nullptr) {
null_best->Print(null_char_, unicharset, 1);
}
}
// Returns the given best_nodes as unichar-ids/certs/ratings/xcoords skipping
// duplicates, nulls and intermediate parts.
/* static */
void RecodeBeamSearch::ExtractPathAsUnicharIds(
const std::vector<const RecodeNode *> &best_nodes,
std::vector<int> *unichar_ids, std::vector<float> *certs,
std::vector<float> *ratings, std::vector<int> *xcoords,
std::vector<int> *character_boundaries) {
unichar_ids->clear();
certs->clear();
ratings->clear();
xcoords->clear();
std::vector<int> starts;
std::vector<int> ends;
// Backtrack extracting only valid, non-duplicate unichar-ids.
int t = 0;
int width = best_nodes.size();
while (t < width) {
double certainty = 0.0;
double rating = 0.0;
while (t < width && best_nodes[t]->unichar_id == INVALID_UNICHAR_ID) {
double cert = best_nodes[t++]->certainty;
if (cert < certainty) {
certainty = cert;
}
rating -= cert;
}
starts.push_back(t);
if (t < width) {
int unichar_id = best_nodes[t]->unichar_id;
if (unichar_id == UNICHAR_SPACE && !certs->empty() &&
best_nodes[t]->permuter != NO_PERM) {
// All the rating and certainty go on the previous character except
// for the space itself.
if (certainty < certs->back()) {
certs->back() = certainty;
}
ratings->back() += rating;
certainty = 0.0;
rating = 0.0;
}
unichar_ids->push_back(unichar_id);
xcoords->push_back(t);
do {
double cert = best_nodes[t++]->certainty;
// Special-case NO-PERM space to forget the certainty of the previous
// nulls. See long comment in ContinueContext.
if (cert < certainty || (unichar_id == UNICHAR_SPACE &&
best_nodes[t - 1]->permuter == NO_PERM)) {
certainty = cert;
}
rating -= cert;
} while (t < width && best_nodes[t]->duplicate);
ends.push_back(t);
certs->push_back(certainty);
ratings->push_back(rating);
} else if (!certs->empty()) {
if (certainty < certs->back()) {
certs->back() = certainty;
}
ratings->back() += rating;
}
}
starts.push_back(width);
if (character_boundaries != nullptr) {
calculateCharBoundaries(&starts, &ends, character_boundaries, width);
}
xcoords->push_back(width);
}
// Sets up a word with the ratings matrix and fake blobs with boxes in the
// right places.
WERD_RES *RecodeBeamSearch::InitializeWord(bool leading_space,
const TBOX &line_box, int word_start,
int word_end, float space_certainty,
const UNICHARSET *unicharset,
const std::vector<int> &xcoords,
float scale_factor) {
// Make a fake blob for each non-zero label.
C_BLOB_LIST blobs;
C_BLOB_IT b_it(&blobs);
for (int i = word_start; i < word_end; ++i) {
if (static_cast<unsigned>(i + 1) < character_boundaries_.size()) {
TBOX box(static_cast<int16_t>(
std::floor(character_boundaries_[i] * scale_factor)) +
line_box.left(),
line_box.bottom(),
static_cast<int16_t>(
std::ceil(character_boundaries_[i + 1] * scale_factor)) +
line_box.left(),
line_box.top());
b_it.add_after_then_move(C_BLOB::FakeBlob(box));
}
}
// Make a fake word from the blobs.
WERD *word = new WERD(&blobs, leading_space, nullptr);
// Make a WERD_RES from the word.
auto *word_res = new WERD_RES(word);
word_res->end = word_end - word_start + leading_space;
word_res->uch_set = unicharset;
word_res->combination = true; // Give it ownership of the word.
word_res->space_certainty = space_certainty;
word_res->ratings = new MATRIX(word_end - word_start, 1);
return word_res;
}
// Fills top_n_flags_ with bools that are true iff the corresponding output
// is one of the top_n.
void RecodeBeamSearch::ComputeTopN(const float *outputs, int num_outputs,
int top_n) {
top_n_flags_.clear();
top_n_flags_.resize(num_outputs, TN_ALSO_RAN);
top_code_ = -1;
second_code_ = -1;
top_heap_.clear();
for (int i = 0; i < num_outputs; ++i) {
if (top_heap_.size() < top_n || outputs[i] > top_heap_.PeekTop().key()) {
TopPair entry(outputs[i], i);
top_heap_.Push(&entry);
if (top_heap_.size() > top_n) {
top_heap_.Pop(&entry);
}
}
}
while (!top_heap_.empty()) {
TopPair entry;
top_heap_.Pop(&entry);
if (top_heap_.size() > 1) {
top_n_flags_[entry.data()] = TN_TOPN;
} else {
top_n_flags_[entry.data()] = TN_TOP2;
if (top_heap_.empty()) {
top_code_ = entry.data();
} else {
second_code_ = entry.data();
}
}
}
top_n_flags_[null_char_] = TN_TOP2;
}
void RecodeBeamSearch::ComputeSecTopN(std::unordered_set<int> *exList,
const float *outputs, int num_outputs,
int top_n) {
top_n_flags_.clear();
top_n_flags_.resize(num_outputs, TN_ALSO_RAN);
top_code_ = -1;
second_code_ = -1;
top_heap_.clear();
for (int i = 0; i < num_outputs; ++i) {
if ((top_heap_.size() < top_n || outputs[i] > top_heap_.PeekTop().key()) &&
!exList->count(i)) {
TopPair entry(outputs[i], i);
top_heap_.Push(&entry);
if (top_heap_.size() > top_n) {
top_heap_.Pop(&entry);
}
}
}
while (!top_heap_.empty()) {
TopPair entry;
top_heap_.Pop(&entry);
if (top_heap_.size() > 1) {
top_n_flags_[entry.data()] = TN_TOPN;
} else {
top_n_flags_[entry.data()] = TN_TOP2;
if (top_heap_.empty()) {
top_code_ = entry.data();
} else {
second_code_ = entry.data();
}
}
}
top_n_flags_[null_char_] = TN_TOP2;
}
// Adds the computation for the current time-step to the beam. Call at each
// time-step in sequence from left to right. outputs is the activation vector
// for the current timestep.
void RecodeBeamSearch::DecodeStep(const float *outputs, int t,
double dict_ratio, double cert_offset,
double worst_dict_cert,
const UNICHARSET *charset, bool debug) {
if (t == static_cast<int>(beam_.size())) {
beam_.push_back(new RecodeBeam);
}
RecodeBeam *step = beam_[t];
beam_size_ = t + 1;
step->Clear();
if (t == 0) {
// The first step can only use singles and initials.
ContinueContext(nullptr, BeamIndex(false, NC_ANYTHING, 0), outputs, TN_TOP2,
charset, dict_ratio, cert_offset, worst_dict_cert, step);
if (dict_ != nullptr) {
ContinueContext(nullptr, BeamIndex(true, NC_ANYTHING, 0), outputs,
TN_TOP2, charset, dict_ratio, cert_offset,
worst_dict_cert, step);
}
} else {
RecodeBeam *prev = beam_[t - 1];
if (debug) {
int beam_index = BeamIndex(true, NC_ANYTHING, 0);
for (int i = prev->beams_[beam_index].size() - 1; i >= 0; --i) {
std::vector<const RecodeNode *> path;
ExtractPath(&prev->beams_[beam_index].get(i).data(), &path);
tprintf("Step %d: Dawg beam %d:\n", t, i);
DebugPath(charset, path);
}
beam_index = BeamIndex(false, NC_ANYTHING, 0);
for (int i = prev->beams_[beam_index].size() - 1; i >= 0; --i) {
std::vector<const RecodeNode *> path;
ExtractPath(&prev->beams_[beam_index].get(i).data(), &path);
tprintf("Step %d: Non-Dawg beam %d:\n", t, i);
DebugPath(charset, path);
}
}
int total_beam = 0;
// Work through the scores by group (top-2, top-n, the rest) while the beam
// is empty. This enables extending the context using only the top-n results
// first, which may have an empty intersection with the valid codes, so we
// fall back to the rest if the beam is empty.
for (int tn = 0; tn < TN_COUNT && total_beam == 0; ++tn) {
auto top_n = static_cast<TopNState>(tn);
for (int index = 0; index < kNumBeams; ++index) {
// Working backwards through the heaps doesn't guarantee that we see the
// best first, but it comes before a lot of the worst, so it is slightly
// more efficient than going forwards.
for (int i = prev->beams_[index].size() - 1; i >= 0; --i) {
ContinueContext(&prev->beams_[index].get(i).data(), index, outputs,
top_n, charset, dict_ratio, cert_offset,
worst_dict_cert, step);
}
}
for (int index = 0; index < kNumBeams; ++index) {
if (ContinuationFromBeamsIndex(index) == NC_ANYTHING) {
total_beam += step->beams_[index].size();
}
}
}
// Special case for the best initial dawg. Push it on the heap if good
// enough, but there is only one, so it doesn't blow up the beam.
for (int c = 0; c < NC_COUNT; ++c) {
if (step->best_initial_dawgs_[c].code >= 0) {
int index = BeamIndex(true, static_cast<NodeContinuation>(c), 0);
RecodeHeap *dawg_heap = &step->beams_[index];
PushHeapIfBetter(kBeamWidths[0], &step->best_initial_dawgs_[c],
dawg_heap);
}
}
}
}
void RecodeBeamSearch::DecodeSecondaryStep(
const float *outputs, int t, double dict_ratio, double cert_offset,
double worst_dict_cert, const UNICHARSET *charset, bool debug) {
if (t == static_cast<int>(secondary_beam_.size())) {
secondary_beam_.push_back(new RecodeBeam);
}
RecodeBeam *step = secondary_beam_[t];
step->Clear();
if (t == 0) {
// The first step can only use singles and initials.
ContinueContext(nullptr, BeamIndex(false, NC_ANYTHING, 0), outputs, TN_TOP2,
charset, dict_ratio, cert_offset, worst_dict_cert, step);
if (dict_ != nullptr) {
ContinueContext(nullptr, BeamIndex(true, NC_ANYTHING, 0), outputs,
TN_TOP2, charset, dict_ratio, cert_offset,
worst_dict_cert, step);
}
} else {
RecodeBeam *prev = secondary_beam_[t - 1];
if (debug) {
int beam_index = BeamIndex(true, NC_ANYTHING, 0);
for (int i = prev->beams_[beam_index].size() - 1; i >= 0; --i) {
std::vector<const RecodeNode *> path;
ExtractPath(&prev->beams_[beam_index].get(i).data(), &path);
tprintf("Step %d: Dawg beam %d:\n", t, i);
DebugPath(charset, path);
}
beam_index = BeamIndex(false, NC_ANYTHING, 0);
for (int i = prev->beams_[beam_index].size() - 1; i >= 0; --i) {
std::vector<const RecodeNode *> path;
ExtractPath(&prev->beams_[beam_index].get(i).data(), &path);
tprintf("Step %d: Non-Dawg beam %d:\n", t, i);
DebugPath(charset, path);
}
}
int total_beam = 0;
// Work through the scores by group (top-2, top-n, the rest) while the beam
// is empty. This enables extending the context using only the top-n results
// first, which may have an empty intersection with the valid codes, so we
// fall back to the rest if the beam is empty.
for (int tn = 0; tn < TN_COUNT && total_beam == 0; ++tn) {
auto top_n = static_cast<TopNState>(tn);
for (int index = 0; index < kNumBeams; ++index) {
// Working backwards through the heaps doesn't guarantee that we see the
// best first, but it comes before a lot of the worst, so it is slightly
// more efficient than going forwards.
for (int i = prev->beams_[index].size() - 1; i >= 0; --i) {
ContinueContext(&prev->beams_[index].get(i).data(), index, outputs,
top_n, charset, dict_ratio, cert_offset,
worst_dict_cert, step);
}
}
for (int index = 0; index < kNumBeams; ++index) {
if (ContinuationFromBeamsIndex(index) == NC_ANYTHING) {
total_beam += step->beams_[index].size();
}
}
}
// Special case for the best initial dawg. Push it on the heap if good
// enough, but there is only one, so it doesn't blow up the beam.
for (int c = 0; c < NC_COUNT; ++c) {
if (step->best_initial_dawgs_[c].code >= 0) {
int index = BeamIndex(true, static_cast<NodeContinuation>(c), 0);
RecodeHeap *dawg_heap = &step->beams_[index];
PushHeapIfBetter(kBeamWidths[0], &step->best_initial_dawgs_[c],
dawg_heap);
}
}
}
}
// Adds to the appropriate beams the legal (according to recoder)
// continuations of context prev, which is of the given length, using the
// given network outputs to provide scores to the choices. Uses only those
// choices for which top_n_flags[index] == top_n_flag.
void RecodeBeamSearch::ContinueContext(
const RecodeNode *prev, int index, const float *outputs,
TopNState top_n_flag, const UNICHARSET *charset, double dict_ratio,
double cert_offset, double worst_dict_cert, RecodeBeam *step) {
RecodedCharID prefix;
RecodedCharID full_code;
const RecodeNode *previous = prev;
int length = LengthFromBeamsIndex(index);
bool use_dawgs = IsDawgFromBeamsIndex(index);
NodeContinuation prev_cont = ContinuationFromBeamsIndex(index);
for (int p = length - 1; p >= 0; --p, previous = previous->prev) {
while (previous != nullptr &&
(previous->duplicate || previous->code == null_char_)) {
previous = previous->prev;
}
if (previous != nullptr) {
prefix.Set(p, previous->code);
full_code.Set(p, previous->code);
}
}
if (prev != nullptr && !is_simple_text_) {
if (top_n_flags_[prev->code] == top_n_flag) {
if (prev_cont != NC_NO_DUP) {
float cert =
NetworkIO::ProbToCertainty(outputs[prev->code]) + cert_offset;
PushDupOrNoDawgIfBetter(length, true, prev->code, prev->unichar_id,
cert, worst_dict_cert, dict_ratio, use_dawgs,
NC_ANYTHING, prev, step);
}
if (prev_cont == NC_ANYTHING && top_n_flag == TN_TOP2 &&
prev->code != null_char_) {
float cert = NetworkIO::ProbToCertainty(outputs[prev->code] +
outputs[null_char_]) +
cert_offset;
PushDupOrNoDawgIfBetter(length, true, prev->code, prev->unichar_id,
cert, worst_dict_cert, dict_ratio, use_dawgs,
NC_NO_DUP, prev, step);
}
}
if (prev_cont == NC_ONLY_DUP) {
return;
}
if (prev->code != null_char_ && length > 0 &&
top_n_flags_[null_char_] == top_n_flag) {
// Allow nulls within multi code sequences, as the nulls within are not
// explicitly included in the code sequence.
float cert =
NetworkIO::ProbToCertainty(outputs[null_char_]) + cert_offset;
PushDupOrNoDawgIfBetter(length, false, null_char_, INVALID_UNICHAR_ID,
cert, worst_dict_cert, dict_ratio, use_dawgs,
NC_ANYTHING, prev, step);
}
}
const std::vector<int> *final_codes = recoder_.GetFinalCodes(prefix);
if (final_codes != nullptr) {
for (int code : *final_codes) {
if (top_n_flags_[code] != top_n_flag) {
continue;
}
if (prev != nullptr && prev->code == code && !is_simple_text_) {
continue;
}
float cert = NetworkIO::ProbToCertainty(outputs[code]) + cert_offset;
if (cert < kMinCertainty && code != null_char_) {
continue;
}
full_code.Set(length, code);
int unichar_id = recoder_.DecodeUnichar(full_code);
// Map the null char to INVALID.
if (length == 0 && code == null_char_) {
unichar_id = INVALID_UNICHAR_ID;
}
if (unichar_id != INVALID_UNICHAR_ID && charset != nullptr &&
!charset->get_enabled(unichar_id)) {
continue; // disabled by whitelist/blacklist
}
ContinueUnichar(code, unichar_id, cert, worst_dict_cert, dict_ratio,
use_dawgs, NC_ANYTHING, prev, step);
if (top_n_flag == TN_TOP2 && code != null_char_) {
float prob = outputs[code] + outputs[null_char_];
if (prev != nullptr && prev_cont == NC_ANYTHING &&
prev->code != null_char_ &&
((prev->code == top_code_ && code == second_code_) ||
(code == top_code_ && prev->code == second_code_))) {
prob += outputs[prev->code];
}
cert = NetworkIO::ProbToCertainty(prob) + cert_offset;
ContinueUnichar(code, unichar_id, cert, worst_dict_cert, dict_ratio,
use_dawgs, NC_ONLY_DUP, prev, step);
}
}
}
const std::vector<int> *next_codes = recoder_.GetNextCodes(prefix);
if (next_codes != nullptr) {
for (int code : *next_codes) {
if (top_n_flags_[code] != top_n_flag) {
continue;
}
if (prev != nullptr && prev->code == code && !is_simple_text_) {
continue;
}
float cert = NetworkIO::ProbToCertainty(outputs[code]) + cert_offset;
PushDupOrNoDawgIfBetter(length + 1, false, code, INVALID_UNICHAR_ID, cert,
worst_dict_cert, dict_ratio, use_dawgs,
NC_ANYTHING, prev, step);
if (top_n_flag == TN_TOP2 && code != null_char_) {
float prob = outputs[code] + outputs[null_char_];
if (prev != nullptr && prev_cont == NC_ANYTHING &&
prev->code != null_char_ &&
((prev->code == top_code_ && code == second_code_) ||