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
|
package main
// Cross-checking Gemini's transcription against the OCR.
//
// Gemini's text is the skeleton: its blocks, italics and footnote marks are
// what the book is built from. Every word in it is aligned with tesseract's
// reading of the same page (and with the PDF's text layer, if there is one)
// and ends up in one of these states:
//
// ok the readings agree, up to what normalisation folds away
// (case, punctuation, hyphenation, ſ and ligatures);
// decided they disagree, and Jev, shown the printed word, picked a
// reading other than Gemini's (or text layer and tesseract
// outvoted it), which replaced Gemini's;
// suspect they disagree and nothing settled it, or the word is only in
// Gemini's reading;
// inserted a run of words only the OCR has, put into the text because
// leaving it out silently is worse than showing it marked.
//
// Words confirmed by Jev in Gemini's favour count as ok. See epubify(1),
// CROSS-CHECK.
import (
"fmt"
"image"
"math"
"sort"
"strings"
"unicode"
"unicode/utf8"
)
// seg is a stretch of a word in one style.
type seg struct {
T string `json:"t"`
I bool `json:"i,omitempty"`
}
// tok is one word of the merged text, with the punctuation around it.
type tok struct {
Segs []seg `json:"s"`
Note string `json:"n,omitempty"` // footnote reference after this word
Class string `json:"c,omitempty"` // "", decided, suspect, inserted
Was string `json:"w,omitempty"` // Gemini's reading, if replaced
Other string `json:"o,omitempty"` // the OCR's reading, if it differed
Soft bool `json:"-"` // a footnote's own mark: never suspect
norm string `json:"-"`
}
func (t tok) surface() string {
var b strings.Builder
for _, s := range t.Segs {
b.WriteString(s.T)
}
return b.String()
}
// norm folds what the sources legitimately differ in: case, punctuation,
// hyphens, long s and ligatures. Letters and digits survive, umlauts and ß
// included — those are exactly what a "corrected" spelling changes.
func norm(s string) string {
var b strings.Builder
for _, r := range strings.ToLower(s) {
switch r {
case 'ſ':
b.WriteRune('s')
continue
case 'fi':
b.WriteString("fi")
continue
case 'fl':
b.WriteString("fl")
continue
case 'ff':
b.WriteString("ff")
continue
case 'ffi':
b.WriteString("ffi")
continue
case 'ffl':
b.WriteString("ffl")
continue
case 'ſt', 'st':
b.WriteString("st")
continue
}
if unicode.IsLetter(r) || unicode.IsDigit(r) {
b.WriteRune(r)
}
}
return b.String()
}
// ocrFold folds the confusions tesseract typically makes on German text
// set in an old-style face: a circumflex for an umlaut (ô for ö), a capital
// umlaut without its dots, B or R for ß. Two readings equal after folding
// differ in nothing Gemini is likely to have got wrong; only Jev, confidently
// picking the OCR's reading, can make such a word suspect.
func ocrFold(s string) string {
r := strings.NewReplacer(
"ô", "o", "ö", "o", "ò", "o", "ó", "o",
"û", "u", "ü", "u", "ù", "u", "ú", "u",
"â", "a", "ä", "a", "à", "a", "á", "a",
"ß", "b", "r", "b", // auBen, AuRerlichkeit
"rn", "m", // Entfemung
"1", "i", "l", "i", "ı", "i",
"0", "o",
)
return r.Replace(s)
}
// quoteAsS says whether the OCR read a closing guillemet as an s, as
// tesseract does with »Beerdigung« -> »Beerdigungs.
func quoteAsS(surface, g, x string) bool {
return strings.ContainsAny(surface, "«»") && (x == g+"s" || x == "s"+g)
}
// parseGeminiText splits a block's text into words, reading *italic* and
// [^N] footnote references.
func parseGeminiText(text string) []tok {
var toks []tok
var cur tok
var buf strings.Builder
italic := false
flushSeg := func() {
if buf.Len() > 0 {
cur.Segs = append(cur.Segs, seg{T: buf.String(), I: italic})
buf.Reset()
}
}
flushTok := func() {
flushSeg()
if len(cur.Segs) > 0 {
toks = append(toks, cur)
} else if cur.Note != "" && len(toks) > 0 {
toks[len(toks)-1].Note = cur.Note
}
cur = tok{}
}
rs := []rune(text)
for i := 0; i < len(rs); i++ {
r := rs[i]
switch {
case r == '*':
flushSeg()
italic = !italic
case r == '[' && i+1 < len(rs) && rs[i+1] == '^':
end := strings.IndexRune(string(rs[i:]), ']')
if end < 0 {
buf.WriteRune(r)
continue
}
mark := string(rs[i+2 : i+len([]rune(string(rs[i:])[:end]))])
flushSeg()
if len(cur.Segs) == 0 && len(toks) > 0 {
toks[len(toks)-1].Note = mark
} else {
cur.Note = mark
}
i += len([]rune(string(rs[i:])[:end]))
case unicode.IsSpace(r):
flushTok()
default:
buf.WriteRune(r)
}
}
flushTok()
for i := range toks {
toks[i].norm = norm(toks[i].surface())
}
return toks
}
// ocrTok is one OCR word, or two joined across a line-end hyphen.
type ocrTok struct {
Text string
Conf float64
Boxes []image.Rectangle
norm string
}
// ocrTokens turns tesseract's words into tokens, joining words hyphenated
// at the end of a line.
func ocrTokens(words []ocrWord) []ocrTok {
var out []ocrTok
for i := 0; i < len(words); i++ {
w := words[i]
t := ocrTok{Text: w.Text, Conf: w.Conf, Boxes: []image.Rectangle{w.Box}}
lastOnLine := i+1 < len(words) && !sameLine(w, words[i+1])
if lastOnLine && (strings.HasSuffix(w.Text, "-") || strings.HasSuffix(w.Text, "¬")) && len(w.Text) > 1 {
n := words[i+1]
t.Text = strings.TrimRight(w.Text, "-¬") + n.Text
t.Conf = math.Min(w.Conf, n.Conf)
t.Boxes = append(t.Boxes, n.Box)
i++
}
t.norm = norm(t.Text)
out = append(out, t)
}
return out
}
// dropFurniture removes the running head and page number from the OCR: the
// lines at the very top and bottom of the page made only of words from the
// running head and of numbers. Gemini reports them separately; leaving them
// in would make every page start with words only the OCR has. It returns
// what it took for the page number.
func dropFurniture(words []ocrWord, height int, runningHead, pageNum string) ([]ocrWord, string) {
// Compared folded, as tesseract reads the head's AUFKLÄRUNG as
// AUFKLARUNG.
allowed := map[string]bool{}
for _, w := range strings.Fields(runningHead) {
allowed[ocrFold(norm(w))] = true
}
if pageNum != "" {
allowed[ocrFold(norm(pageNum))] = true
}
type line struct{ from, to int }
var lines []line
for i := range words {
if i == 0 || !sameLine(words[i-1], words[i]) {
lines = append(lines, line{i, i + 1})
} else {
lines[len(lines)-1].to = i + 1
}
}
// By position, not tesseract's reading order: specks in the bottom
// margin can come out first and hide the head behind them.
sort.SliceStable(lines, func(a, b int) bool {
return words[lines[a].from].Box.Min.Y < words[lines[b].from].Box.Min.Y
})
drop := make([]bool, len(words))
found := ""
// Every word must be the head's or a number anyway; the limit only
// keeps a short line of text that happens to repeat the head. A long
// head ("BEANTWORTUNG DER FRAGE: WAS IST AUFKLÄRUNG? 57") raises it,
// with room for a number and stray punctuation tesseract splits off.
maxWords := max(6, len(strings.Fields(runningHead))+3)
check := func(l line) bool {
ws := words[l.from:l.to]
if len(ws) > maxWords {
return false
}
for _, w := range ws {
n := norm(w.Text)
if n == "" || allowed[ocrFold(n)] || isPageNumberLike(w.Text) {
continue
}
return false
}
for i := l.from; i < l.to; i++ {
drop[i] = true
if isPageNumberLike(words[i].Text) {
found = words[i].Text
}
}
return true
}
// At most two lines from the top and one from the bottom, and only
// inside the outer eighth of the page.
for k := 0; k < len(lines) && k < 2; k++ {
if words[lines[k].from].Box.Max.Y > height/8 || !check(lines[k]) {
break
}
}
if n := len(lines); n > 0 && words[lines[n-1].from].Box.Min.Y > height*7/8 {
check(lines[n-1])
}
var out []ocrWord
for i, w := range words {
if !drop[i] {
out = append(out, w)
}
}
return out, found
}
func isPageNumberLike(s string) bool {
s = strings.Trim(s, ".-–— ")
if s == "" || utf8.RuneCountInString(s) > 5 {
return false
}
for _, r := range strings.ToLower(s) {
if !(unicode.IsDigit(r) || strings.ContainsRune("ivxlcdmo", r)) {
return false
}
}
return true
}
// --- alignment ------------------------------------------------------------
func levenshtein(a, b string) int {
ra, rb := []rune(a), []rune(b)
prev := make([]int, len(rb)+1)
cur := make([]int, len(rb)+1)
for j := range prev {
prev[j] = j
}
for i := 1; i <= len(ra); i++ {
cur[0] = i
for j := 1; j <= len(rb); j++ {
c := 1
if ra[i-1] == rb[j-1] {
c = 0
}
cur[j] = min(prev[j]+1, cur[j-1]+1, prev[j-1]+c)
}
prev, cur = cur, prev
}
return prev[len(rb)]
}
// ned is the edit distance relative to the longer word, 0 to 1.
func ned(a, b string) float64 {
n := max(utf8.RuneCountInString(a), utf8.RuneCountInString(b))
if n == 0 {
return 0
}
return float64(levenshtein(a, b)) / float64(n)
}
// joinCost is the cost of aligning two words with one: free if the letters
// agree, up to a typical OCR confusion; otherwise impossible.
func joinCost(a, b string) int {
if a == b || ocrFold(a) == ocrFold(b) {
return 0
}
if ned(a, b) <= 0.1 {
return 20
}
return math.MaxInt32 / 4
}
// opKind is one step of an alignment of Gemini's words (g) with another
// reading's (x).
type opKind int
const (
opMatch opKind = iota // g[i] == x[j]
opSub // g[i] read as x[j]
opGOnly // g[i] has no counterpart
opXOnly // x[j] has no counterpart
opG2X1 // g[i] g[i+1] == x[j] (OCR ran two words together)
opG1X2 // g[i] == x[j] x[j+1] (OCR split a word)
)
type op struct {
Kind opKind
G, X int
}
// align computes a minimum-cost alignment of two word sequences: exact
// matches are free, a substitution costs twice its edit distance (so two
// unrelated words are cheaper as a deletion and an insertion), a gap costs
// one, and a word run together or split by the OCR is free when the letters
// agree. Footnote references count as matching a digit the OCR glued on.
func align(g []string, gNote []string, x []string) []op {
n, m := len(g), len(x)
const gap = 100
sub := func(i, j int) int {
if g[i] == x[j] {
return 0
}
if gNote[i] != "" && x[j] == g[i]+norm(gNote[i]) {
return 0
}
if ocrFold(g[i]) == ocrFold(x[j]) {
return 10
}
d := ned(g[i], x[j])
if d >= 0.5 {
return 2*gap + 1
}
return int(2 * gap * d)
}
inf := math.MaxInt32 / 2
cost := make([][]int32, n+1)
for i := range cost {
cost[i] = make([]int32, m+1)
}
for i := 0; i <= n; i++ {
for j := 0; j <= m; j++ {
if i == 0 && j == 0 {
continue
}
best := inf
if i > 0 && j > 0 {
best = min(best, int(cost[i-1][j-1])+sub(i-1, j-1))
}
if i > 0 {
best = min(best, int(cost[i-1][j])+gap)
}
if j > 0 {
best = min(best, int(cost[i][j-1])+gap)
}
if i > 1 && j > 0 {
best = min(best, int(cost[i-2][j-1])+joinCost(g[i-2]+g[i-1], x[j-1]))
}
if i > 0 && j > 1 {
best = min(best, int(cost[i-1][j-2])+joinCost(g[i-1], x[j-2]+x[j-1]))
}
cost[i][j] = int32(best)
}
}
var ops []op
i, j := n, m
for i > 0 || j > 0 {
c := int(cost[i][j])
switch {
case i > 0 && j > 0 && c == int(cost[i-1][j-1])+sub(i-1, j-1):
k := opSub
if sub(i-1, j-1) == 0 {
k = opMatch
}
ops = append(ops, op{k, i - 1, j - 1})
i, j = i-1, j-1
case i > 1 && j > 0 && c == int(cost[i-2][j-1])+joinCost(g[i-2]+g[i-1], x[j-1]):
ops = append(ops, op{opG2X1, i - 2, j - 1})
i, j = i-2, j-1
case i > 0 && j > 1 && c == int(cost[i-1][j-2])+joinCost(g[i-1], x[j-2]+x[j-1]):
ops = append(ops, op{opG1X2, i - 1, j - 2})
i, j = i-1, j-2
case i > 0 && c == int(cost[i-1][j])+gap:
ops = append(ops, op{opGOnly, i - 1, -1})
i--
default:
ops = append(ops, op{opXOnly, -1, j - 1})
j--
}
}
for a, b := 0, len(ops)-1; a < b; a, b = a+1, b-1 {
ops[a], ops[b] = ops[b], ops[a]
}
return pairLoneGaps(ops)
}
// pairLoneGaps turns a single Gemini-only word next to a single OCR-only
// word into a substitution: the two readings of one word, too different to
// align by spelling ("45." read as "as."), but standing in the same place.
// It is then put to Jev like any other disagreement.
func pairLoneGaps(ops []op) []op {
isMatch := func(i int) bool {
if i < 0 || i >= len(ops) {
return true
}
k := ops[i].Kind
return k == opMatch || k == opSub || k == opG2X1 || k == opG1X2
}
var out []op
for i := 0; i < len(ops); i++ {
if i+1 < len(ops) && isMatch(i-1) && isMatch(i+2) {
a, b := ops[i], ops[i+1]
if a.Kind == opGOnly && b.Kind == opXOnly {
out = append(out, op{opSub, a.G, b.X})
i++
continue
}
if a.Kind == opXOnly && b.Kind == opGOnly {
out = append(out, op{opSub, b.G, a.X})
i++
continue
}
}
out = append(out, ops[i])
}
return out
}
// --- the merge --------------------------------------------------------------
// mBlock is one block of the merged page.
type mBlock struct {
Kind string `json:"kind"`
Continues bool `json:"continues,omitempty"`
Mark string `json:"mark,omitempty"`
Toks []tok `json:"toks"`
}
// question is a disagreement put to Jev: which reading is printed in crop.
type question struct {
Block, Tok int
Readings []string // distinct cores; [0] is Gemini's
Sources []string // which source each reading came from
Crop []byte // JPEG
OCRConf float64
Ned float64
Majority string // set when layer and tesseract agree against Gemini
Fold bool // the readings differ only in a typical OCR confusion
}
// pageMerge is the merged reading of one book page, before and after Jev.
type pageMerge struct {
Blocks []mBlock `json:"blocks"`
Score float64 `json:"score"` // share of Gemini's words confirmed
Words int `json:"words"` // alignable words in Gemini's reading
Suspects int `json:"suspects"` // words marked suspect
Inserted int `json:"inserted"` // words inserted from the OCR
Decided int `json:"decided"` // words where Gemini was overruled
Confirmed int `json:"confirmed"` // disagreements Jev settled for Gemini
LongRuns []string `json:"long_runs"` // runs of ≥3 suspect/inserted words, as text
Ignored []string `json:"ignored"` // short OCR-only runs left out
Moved int `json:"moved"` // words found in a different order
OCRPageNum string `json:"ocr_page_num"`
Sources []string `json:"sources"`
Flagged bool `json:"flagged"`
Attempt int `json:"attempt"`
questions []question
}
// pos addresses a token in the merged blocks.
type pos struct{ B, T int }
type mergeInput struct {
Gemini transcription
OCR []ocrWord // on the page crop, already without furniture
OCRPageNum string
Layer []string // words of the text layer, nil if none or unusable
PageImg *image.Gray
MinAgree float64
}
// mergePage aligns and votes; disagreements that need Jev are left in
// questions, to be answered by applyDecisions.
func mergePage(in mergeInput) *pageMerge {
pm := &pageMerge{OCRPageNum: in.OCRPageNum, Sources: []string{"gemini", "tesseract"}}
if in.Layer != nil {
pm.Sources = append(pm.Sources, "layer")
}
// Gemini's words, flattened, remembering where each lives.
var flat []pos
for bi, b := range in.Gemini.Blocks {
mb := mBlock{Kind: b.Kind, Continues: b.Continues, Mark: b.FootnoteMark}
if b.Kind == "footnote" && b.FootnoteMark != "" {
// The mark is aligned too (the OCR reads it at the start of
// the note) but never shown as text, and never suspect.
mb.Toks = append(mb.Toks, tok{Segs: []seg{{T: b.FootnoteMark}}, Soft: true, norm: norm(b.FootnoteMark)})
}
mb.Toks = append(mb.Toks, parseGeminiText(b.Text)...)
pm.Blocks = append(pm.Blocks, mb)
for ti, t := range mb.Toks {
if t.norm != "" {
flat = append(flat, pos{bi, ti})
}
}
}
at := func(p pos) *tok { return &pm.Blocks[p.B].Toks[p.T] }
gn := make([]string, len(flat))
gNote := make([]string, len(flat))
for i, p := range flat {
gn[i], gNote[i] = at(p).norm, at(p).Note
}
ocr := ocrTokens(in.OCR)
var ox []ocrTok
for _, o := range ocr {
if o.norm != "" {
ox = append(ox, o)
}
}
xn := make([]string, len(ox))
for i, o := range ox {
xn[i] = o.norm
}
ops := align(gn, gNote, xn)
// The layer, aligned the same way, gives each Gemini word a third vote.
layerAt := map[int]string{}
layerGap := map[int]bool{}
if in.Layer != nil {
var ln []string
var lraw []string
for _, w := range in.Layer {
if n := norm(w); n != "" {
ln = append(ln, n)
lraw = append(lraw, w)
}
}
for _, o := range align(gn, gNote, ln) {
switch o.Kind {
case opMatch, opSub:
layerAt[o.G] = lraw[o.X]
case opG2X1:
layerAt[o.G], layerAt[o.G+1] = gn[o.G], gn[o.G+1]
case opG1X2:
layerAt[o.G] = gn[o.G]
case opGOnly:
layerGap[o.G] = true
}
}
}
confirmed := make([]bool, len(flat))
gOnly := make([]bool, len(flat))
type xrun struct {
after int // index into flat of the Gemini word before it, -1 at start
toks []ocrTok
}
var xruns []xrun
// anchored says whether the alignment is trustworthy around ops[k]: the
// nearest Gemini words on both sides matched the OCR. Without that, a
// "substitution" may pair words from different lines — on a skewed page
// that paired "ohne" with the "ne" ending another line — and showing Jev
// the OCR word's place on the page would show the wrong word.
anchored := func(k int) bool {
ok := func(o op) bool { return o.Kind == opMatch || o.Kind == opG2X1 || o.Kind == opG1X2 }
side := func(from, step int) bool {
if from < 0 || from >= len(ops) {
return true // the start or end of the page anchors
}
seen := 0
for i := from; i >= 0 && i < len(ops) && seen < 3; i += step {
if ops[i].Kind == opXOnly {
continue
}
if ok(ops[i]) {
return true
}
seen++
}
return false
}
return side(k-1, -1) && side(k+1, 1)
}
lastG := -1
for k, o := range ops {
switch o.Kind {
case opMatch, opG2X1, opG1X2:
confirmed[o.G] = true
if o.Kind == opG2X1 {
confirmed[o.G+1] = true
}
lastG = o.G
if o.Kind == opG2X1 {
lastG = o.G + 1
}
if l, ok := layerAt[o.G]; ok && norm(l) != gn[o.G] && o.Kind == opMatch {
// Gemini and tesseract agree against the layer: the
// layer is wrong here, nothing to do.
_ = l
}
case opSub:
lastG = o.G
t := at(flat[o.G])
x := ox[o.X]
l, hasL := layerAt[o.G]
switch {
case hasL && norm(l) == gn[o.G]:
// Layer agrees with Gemini: tesseract misread.
confirmed[o.G] = true
case !anchored(k):
if !t.Soft {
t.Class = "suspect"
t.Other = x.Text
}
case hasL && norm(l) == x.norm:
// Layer and tesseract agree against Gemini.
replaceCore(t, core(l))
t.Class = "decided"
pm.Decided++
confirmed[o.G] = true
default:
q := question{
Block: flat[o.G].B, Tok: flat[o.G].T,
Readings: []string{core(t.surface()), core(x.Text)},
Sources: []string{"gemini", "tesseract"},
OCRConf: x.Conf,
Ned: ned(gn[o.G], x.norm),
Fold: ocrFold(gn[o.G]) == ocrFold(x.norm) || quoteAsS(t.surface(), gn[o.G], x.norm),
}
if hasL && norm(l) != x.norm {
q.Readings = append(q.Readings, core(l))
q.Sources = append(q.Sources, "layer")
}
q.Crop = cropWord(in.PageImg, x.Boxes)
t.Other = x.Text
pm.questions = append(pm.questions, q)
}
case opGOnly:
lastG = o.G
gOnly[o.G] = true
if in.Layer != nil && !layerGap[o.G] {
// Tesseract missed it, the layer has it.
gOnly[o.G] = false
confirmed[o.G] = true
}
case opXOnly:
if n := len(xruns); n > 0 && xruns[n-1].after == lastG {
xruns[n-1].toks = append(xruns[n-1].toks, ox[o.X])
} else {
xruns = append(xruns, xrun{after: lastG, toks: []ocrTok{ox[o.X]}})
}
}
}
// Runs of Gemini-only words. A run found among the OCR-only runs, in
// another place, is the two reading the page in different orders.
type grun struct{ from, to int }
var gruns []grun
for i := range flat {
if !gOnly[i] {
continue
}
if n := len(gruns); n > 0 && gruns[n-1].to == i {
gruns[n-1].to = i + 1
} else {
gruns = append(gruns, grun{i, i + 1})
}
}
usedX := make([]bool, len(xruns))
for _, r := range gruns {
if r.to-r.from >= 3 {
gtext := strings.Join(gn[r.from:r.to], "")
for k, xr := range xruns {
if usedX[k] || len(xr.toks) < 3 {
continue
}
var xs []string
for _, t := range xr.toks {
xs = append(xs, t.norm)
}
if ned(gtext, strings.Join(xs, "")) < 0.15 {
usedX[k] = true
for i := r.from; i < r.to; i++ {
gOnly[i], confirmed[i] = false, true
}
pm.Moved += r.to - r.from
break
}
}
}
if !gOnly[r.from] {
continue
}
for i := r.from; i < r.to; i++ {
t := at(flat[i])
if t.Soft {
continue
}
t.Class = "suspect"
}
if r.to-r.from >= 3 {
pm.LongRuns = append(pm.LongRuns, "only in Gemini's reading: "+joinSurface(pm, flat[r.from:r.to]))
}
}
// Runs of OCR-only words: three or more words read with some
// confidence go into the text, marked; shorter ones are noise (a
// smudge read as "w", a broken rule).
type ins struct {
at pos
toks []tok
}
var inserts []ins
for k, xr := range xruns {
if usedX[k] {
continue
}
var conf float64
var texts []string
for _, t := range xr.toks {
conf += t.Conf
texts = append(texts, t.Text)
}
conf /= float64(len(xr.toks))
if len(xr.toks) < 3 || conf < 60 {
pm.Ignored = append(pm.Ignored, strings.Join(texts, " "))
continue
}
var nt []tok
for _, t := range xr.toks {
nt = append(nt, tok{Segs: []seg{{T: t.Text}}, Class: "inserted", norm: t.norm})
}
p := pos{0, 0}
if xr.after >= 0 {
p = flat[xr.after]
p.T++
}
inserts = append(inserts, ins{p, nt})
pm.Inserted += len(nt)
pm.LongRuns = append(pm.LongRuns, "only in the OCR's reading, inserted: "+strings.Join(texts, " "))
}
// Insert from the back so positions stay valid.
for k := len(inserts) - 1; k >= 0; k-- {
in := inserts[k]
b := &pm.Blocks[in.at.B]
b.Toks = append(b.Toks[:in.at.T], append(in.toks, b.Toks[in.at.T:]...)...)
// Questions pointing behind the insertion move with it.
for qi := range pm.questions {
q := &pm.questions[qi]
if q.Block == in.at.B && q.Tok >= in.at.T {
q.Tok += len(in.toks)
}
}
}
pm.Words = len(flat)
for _, c := range confirmed {
if c {
pm.Score++
}
}
return pm
}
// applyDecisions takes Jev's answers to the page's questions (nil: Jev was
// not asked) and finishes the merge.
func (pm *pageMerge) applyDecisions(answers []decision, minAgree float64) {
for i, q := range pm.questions {
t := &pm.Blocks[q.Block].Toks[q.Tok]
var d decision
if i < len(answers) {
d = answers[i]
}
switch {
case d.Pick == 0 && d.Sure:
pm.Confirmed++
pm.Score++
t.Other = ""
case d.Pick > 0 && d.Sure:
t.Was = t.surface()
replaceCore(t, q.Readings[d.Pick])
t.Class = "decided"
pm.Decided++
pm.Score++
default:
// Unsettled. A typical OCR confusion, or a small difference
// tesseract was unsure of, is most likely its own misreading;
// anything else is marked.
if q.Fold || (q.Ned <= 0.34 && q.OCRConf < 90) {
pm.Score++
} else {
t.Class = "suspect"
}
}
}
pm.questions = nil
if pm.Words > 0 {
pm.Score /= float64(pm.Words)
} else {
pm.Score = 1
}
pm.Suspects = 0
for _, b := range pm.Blocks {
for _, t := range b.Toks {
if t.Class == "suspect" {
pm.Suspects++
}
}
}
pm.Flagged = pm.Score < minAgree || len(pm.LongRuns) > 0
}
// badness orders two merges of the same page: fewer marked words is better.
func (pm *pageMerge) badness() int { return pm.Suspects + pm.Inserted + 3*len(pm.LongRuns) }
func joinSurface(pm *pageMerge, ps []pos) string {
var s []string
for _, p := range ps {
s = append(s, pm.Blocks[p.B].Toks[p.T].surface())
}
return strings.Join(s, " ")
}
// core strips the punctuation around a word.
func core(s string) string {
return strings.TrimFunc(s, func(r rune) bool { return !unicode.IsLetter(r) && !unicode.IsDigit(r) })
}
// replaceCore puts c in place of the letters of t, keeping the punctuation
// around them and the style of the word.
func replaceCore(t *tok, c string) {
s := t.surface()
start := strings.IndexFunc(s, func(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) })
end := strings.LastIndexFunc(s, func(r rune) bool { return unicode.IsLetter(r) || unicode.IsDigit(r) })
italic := false
n := 0
for _, sg := range t.Segs {
if sg.I {
n += len(sg.T)
}
}
italic = n*2 > len(s)
if start < 0 {
t.Segs = []seg{{T: c, I: italic}}
} else {
_, size := utf8.DecodeRuneInString(s[end:])
t.Segs = []seg{{T: s[:start] + c + s[end+size:], I: italic}}
}
t.norm = norm(t.surface())
}
// cropWord cuts the word out of the page with a margin, side by side if it
// was broken over two lines, enlarged so the letters are at least about
// 60 pixels high, and padded to Jev's minimum size.
func cropWord(page *image.Gray, boxes []image.Rectangle) []byte {
var parts []*image.Gray
for _, b := range boxes {
m := b.Dy()/2 + 4
parts = append(parts, cropGray(page, b.Inset(-m)))
}
w, h := 0, 0
for _, p := range parts {
w += p.Rect.Dx() + 10
h = max(h, p.Rect.Dy())
}
img := image.NewGray(image.Rect(0, 0, w, h))
for i := range img.Pix {
img.Pix[i] = 255
}
x := 0
for _, p := range parts {
for y := 0; y < p.Rect.Dy(); y++ {
copy(img.Pix[y*img.Stride+x:], p.Pix[y*p.Stride:y*p.Stride+p.Rect.Dx()])
}
x += p.Rect.Dx() + 10
}
if f := 120 / max(h, 1); f > 1 {
img = enlarge(img, f)
}
return encodeJPEG(padGray(scaleGray(img, jevMaxSide), jevMinSide, jevMinSide), 92)
}
func enlarge(src *image.Gray, f int) *image.Gray {
w, h := src.Rect.Dx(), src.Rect.Dy()
dst := image.NewGray(image.Rect(0, 0, w*f, h*f))
for y := 0; y < h*f; y++ {
for x := 0; x < w*f; x++ {
dst.Pix[y*dst.Stride+x] = src.Pix[(y/f)*src.Stride+x/f]
}
}
return dst
}
func (q question) String() string {
var parts []string
for i, r := range q.Readings {
parts = append(parts, fmt.Sprintf("%s %q", q.Sources[i], r))
}
return strings.Join(parts, " / ")
}
|