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
|
package main
// Gemini transcribes: it is the one source that reads a page the way a person
// does — paragraphs, footnotes, italics, a word broken over a line — and the
// one most likely to quietly improve on it. Everything it says about the
// words is checked against tesseract (and a text layer) in align.go.
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"image"
"io"
"net/http"
"strconv"
"strings"
"sync"
"time"
"unicode"
)
const geminiBase = "https://generativelanguage.googleapis.com/v1beta/models/"
// errRecitation is Gemini refusing to reproduce text it recognises as
// published. It is not an error of the request, and not retried with a delay.
var errRecitation = errors.New("gemini refused to transcribe (RECITATION: it recognised the text as published)")
type geminiClient struct {
key string
model string
http *http.Client
usage *usage
}
type gPart struct {
Text string `json:"text,omitempty"`
InlineData *gInline `json:"inline_data,omitempty"`
Thought bool `json:"thought,omitempty"`
}
type gInline struct {
MimeType string `json:"mime_type"`
Data string `json:"data"`
}
// generate sends images and a prompt and returns the text of the answer.
// With a schema, the answer is JSON constrained to it.
func (c *geminiClient) generate(ctx context.Context, images [][]byte, prompt string, schema any) (string, int, int, error) {
var parts []gPart
for _, im := range images {
parts = append(parts, gPart{InlineData: &gInline{MimeType: "image/jpeg", Data: base64.StdEncoding.EncodeToString(im)}})
}
parts = append(parts, gPart{Text: prompt})
// Each attempt samples differently. Gemini's recitation filter refuses
// some pages of published books, not reproducibly; a refusal is retried
// at once with a higher temperature, in the hope that a different
// sample passes.
temps := []float64{0, 0.7, 1.0}
var lastErr error
tin, tout := 0, 0
for attempt := 0; attempt < len(temps); attempt++ {
cfg := map[string]any{
// Copying text needs little thought; "low" halves the time of
// the default and gave the same transcription on the pages
// tried. This model refuses "minimal".
"thinkingConfig": map[string]any{"thinkingLevel": "low"},
"temperature": temps[attempt],
}
if schema != nil {
cfg["responseMimeType"] = "application/json"
cfg["responseSchema"] = schema
}
js, err := json.Marshal(map[string]any{
"contents": []any{map[string]any{"role": "user", "parts": parts}},
"generationConfig": cfg,
})
if err != nil {
return "", tin, tout, err
}
if attempt > 0 && !errors.Is(lastErr, errRecitation) {
select {
case <-ctx.Done():
return "", tin, tout, ctx.Err()
case <-time.After(time.Duration(2<<attempt) * time.Second):
}
}
rctx, cancel := context.WithTimeout(ctx, 4*time.Minute)
req, _ := http.NewRequestWithContext(rctx, "POST", geminiBase+c.model+":generateContent", bytes.NewReader(js))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-goog-api-key", c.key)
resp, err := c.http.Do(req)
if err != nil {
cancel()
lastErr = err
continue
}
data, _ := io.ReadAll(resp.Body)
resp.Body.Close()
cancel()
if resp.StatusCode == 429 || resp.StatusCode >= 500 {
lastErr = fmt.Errorf("gemini: %s: %s", resp.Status, bytes.TrimSpace(data))
continue
}
if resp.StatusCode != 200 {
return "", tin, tout, fmt.Errorf("gemini: %s: %s", resp.Status, bytes.TrimSpace(data))
}
var r struct {
Candidates []struct {
Content struct {
Parts []gPart `json:"parts"`
} `json:"content"`
FinishReason string `json:"finishReason"`
} `json:"candidates"`
UsageMetadata struct {
Prompt int `json:"promptTokenCount"`
Candidates int `json:"candidatesTokenCount"`
Thoughts int `json:"thoughtsTokenCount"`
} `json:"usageMetadata"`
}
if err := json.Unmarshal(data, &r); err != nil {
return "", tin, tout, fmt.Errorf("gemini: decode: %w", err)
}
in, out := r.UsageMetadata.Prompt, r.UsageMetadata.Candidates+r.UsageMetadata.Thoughts
tin, tout = tin+in, tout+out
c.usage.add("gemini", in, out)
if len(r.Candidates) == 0 {
lastErr = fmt.Errorf("gemini: no candidates")
continue
}
cand := r.Candidates[0]
var text strings.Builder
for _, p := range cand.Content.Parts {
if !p.Thought {
text.WriteString(p.Text)
}
}
switch cand.FinishReason {
case "STOP":
return text.String(), tin, tout, nil
case "RECITATION":
lastErr = errRecitation
default:
lastErr = fmt.Errorf("gemini: finished with %s", cand.FinishReason)
}
}
return "", tin, tout, lastErr
}
// --- transcription -----------------------------------------------------
// transcription is what Gemini read on one book page.
type transcription struct {
PrintedPageNumber string `json:"printed_page_number"`
RunningHead string `json:"running_head"`
Blocks []gBlock `json:"blocks"`
Strips int `json:"strips,omitempty"` // >0: read in this many strips
Raw string `json:"raw"`
}
type gBlock struct {
Kind string `json:"kind"` // heading, paragraph, blockquote, footnote
Text string `json:"text"`
Continues bool `json:"continues_previous_page"`
FootnoteMark string `json:"footnote_mark,omitempty"`
}
// transcribePrompt is part of the cache key: changing it re-transcribes.
//
// The answer is plain text, line for line as printed, with a few marks for
// structure — not JSON, and not reflowed paragraphs. Asked for paragraphs
// as JSON, Gemini's recitation filter refused about one page in four of a
// published book, at every temperature; asked to reproduce the lines for a
// screen reader, it refused none. Lines are also what tesseract reads, and
// hyphenation is undone in code (parseLines), where it can be checked.
const transcribePrompt = `This is a scan of a printed page, for a screen reader. Output the page line by line, exactly as printed: one output line per printed line, with every hyphen at a line end kept as printed. Do not join, correct, complete or modernise anything; keep old spellings such as "daß" and typographic quotes, dashes and ellipses as printed.
Mark structure like this:
- a heading line starts with "# "
- the first line of a new paragraph starts with "¶ " (no mark on the first line if the page starts in the middle of a paragraph)
- a block quotation line starts with "> "
- the first line of a footnote starts with "[^N] " where N is its printed mark; further lines of that footnote start with two spaces; a footnote continued from the previous page starts with "[^] "
- the running head line starts with "HEAD: ", the page number line with "PAGE: "
- italic text is wrapped in *asterisks*; text in small capitals or letter-spaced is written normally
- a superscript footnote reference in the text is written [^N] directly after what it follows
- an illegible passage is written [?]
Output nothing but the page.`
func (c *geminiClient) transcribe(ctx context.Context, page []byte, extra string) (transcription, int, int, error) {
prompt := transcribePrompt
if extra != "" {
prompt += "\n\n" + extra
}
text, in, out, err := c.generate(ctx, [][]byte{page}, prompt, nil)
if err != nil {
return transcription{}, in, out, err
}
t := parseLines(text)
return t, in, out, nil
}
// parseLines reads the line-for-line transcription into blocks, joining the
// lines of a block and undoing the hyphenation at line ends: a word broken
// as "Eintre-" / "ten" becomes "Eintreten", but "Nicht-" / "Text" (a capital
// after the hyphen) and "und -" stay as they are. A hyphen at the end of the
// block's last line is kept: the word may continue on the next page.
func parseLines(text string) transcription {
t := transcription{Raw: text}
var cur *gBlock
var lines []string
flush := func() {
if cur != nil {
cur.Text = joinLines(lines)
if strings.TrimSpace(cur.Text) != "" || cur.FootnoteMark != "" {
t.Blocks = append(t.Blocks, *cur)
}
}
cur, lines = nil, nil
}
start := func(kind string, cont bool, mark string) {
flush()
cur = &gBlock{Kind: kind, Continues: cont, FootnoteMark: mark}
}
first := true
for _, raw := range strings.Split(strings.ReplaceAll(text, "\r", ""), "\n") {
line := strings.TrimRight(raw, " \t")
trimmed := strings.TrimSpace(line)
if trimmed == "" || trimmed == "```" || strings.HasPrefix(trimmed, "```") {
continue
}
switch {
case strings.HasPrefix(trimmed, "HEAD:"):
t.RunningHead = strings.TrimSpace(strings.TrimPrefix(trimmed, "HEAD:"))
continue
case strings.HasPrefix(trimmed, "PAGE:"):
t.PrintedPageNumber = strings.TrimSpace(strings.TrimPrefix(trimmed, "PAGE:"))
continue
case strings.HasPrefix(trimmed, "# "):
if cur == nil || cur.Kind != "heading" {
start("heading", false, "")
}
lines = append(lines, strings.TrimPrefix(trimmed, "# "))
case strings.HasPrefix(trimmed, "¶"):
start("paragraph", false, "")
lines = append(lines, strings.TrimSpace(strings.TrimPrefix(trimmed, "¶")))
case strings.HasPrefix(trimmed, ">"):
if cur == nil || cur.Kind != "blockquote" {
start("blockquote", first, "")
}
lines = append(lines, strings.TrimSpace(strings.TrimPrefix(trimmed, ">")))
case strings.HasPrefix(trimmed, "[^") && !strings.HasPrefix(line, " "):
end := strings.Index(trimmed, "]")
if end < 0 {
lines = append(lines, trimmed)
break
}
mark := trimmed[2:end]
start("footnote", mark == "", mark)
lines = append(lines, strings.TrimSpace(trimmed[end+1:]))
default:
if cur == nil || cur.Kind == "heading" {
// Text without a paragraph mark at the top of the page
// continues the previous page.
start("paragraph", first, "")
}
lines = append(lines, trimmed)
}
first = false
}
flush()
return t
}
// numberFromHead moves a page number Gemini wrote into the running head
// ("HEAD: 56 BEANTWORTUNG DER FRAGE", with no PAGE line) out of it, where
// the head and the number are printed on one line, as in many editions. It
// is applied to stored transcriptions too, so it runs after the cache, not
// in parseLines.
func (t transcription) numberFromHead() transcription {
if t.PrintedPageNumber != "" {
return t
}
f := strings.Fields(t.RunningHead)
if len(f) < 2 {
return t
}
// Digits only: a head such as "I. KAPITEL" or "II" names a chapter.
isNum := func(s string) bool {
_, err := strconv.Atoi(s)
return err == nil && len(s) <= 4
}
switch {
case isNum(f[0]) && !isNum(f[len(f)-1]):
t.PrintedPageNumber, t.RunningHead = f[0], strings.Join(f[1:], " ")
case isNum(f[len(f)-1]) && !isNum(f[0]):
t.PrintedPageNumber, t.RunningHead = f[len(f)-1], strings.Join(f[:len(f)-1], " ")
}
return t
}
func joinLines(lines []string) string {
var b strings.Builder
for i, l := range lines {
if i == 0 {
b.WriteString(l)
continue
}
prev := b.String()
if strings.HasSuffix(prev, "-") && !strings.HasSuffix(prev, " -") && len(prev) > 1 && startsLower(l) && !endsWithMarkup(prev) {
// Line-end hyphenation: drop the hyphen, join the halves. An
// italic word broken over the line ("*Morsu-*" / "*re*")
// has its markers in the middle; they are merged away.
s := strings.TrimSuffix(prev, "-")
if strings.HasSuffix(s, "*") && strings.HasPrefix(l, "*") {
s, l = strings.TrimSuffix(s, "*"), strings.TrimPrefix(l, "*")
}
b.Reset()
b.WriteString(s)
b.WriteString(l)
continue
}
if strings.HasSuffix(prev, "-*") && strings.HasPrefix(l, "*") && startsLower(strings.TrimPrefix(l, "*")) {
s := strings.TrimSuffix(prev, "-*")
b.Reset()
b.WriteString(s)
b.WriteString(strings.TrimPrefix(l, "*"))
continue
}
b.WriteString(" ")
b.WriteString(l)
}
return b.String()
}
func endsWithMarkup(s string) bool { return strings.HasSuffix(s, "]-") }
func startsLower(s string) bool {
for _, r := range strings.TrimLeft(s, "*»«„“\"'(") {
return unicode.IsLower(r)
}
return false
}
// retryHint is added to the prompt of a second transcription of a page whose
// first one disagreed with the OCR. It names the passages, in the OCR's words,
// without saying which reading is right — that is what the second reading is
// for.
func retryHint(passages []string) string {
var b strings.Builder
b.WriteString("A previous transcription of this page may have left out or altered text. Check these passages (as read by an OCR program, which makes its own errors) especially carefully against the image:\n")
for _, p := range passages {
fmt.Fprintf(&b, "- %q\n", p)
}
return b.String()
}
// --- strips: the way around the recitation filter, if it still bites -------
const stripPrompt = `This image is a horizontal strip cut out of the page, not the whole page. If the strip starts in the middle of a paragraph or footnote, do not mark its first line.`
// lineGaps returns the y positions between consecutive OCR lines, which is
// where a page can be cut without cutting through a line of text.
func lineGaps(words []ocrWord) []int {
type span struct{ top, bottom int }
var lines []span
for i, w := range words {
if i == 0 || !sameLine(words[i-1], w) {
lines = append(lines, span{w.Box.Min.Y, w.Box.Max.Y})
} else {
l := &lines[len(lines)-1]
l.top, l.bottom = min(l.top, w.Box.Min.Y), max(l.bottom, w.Box.Max.Y)
}
}
var gaps []int
for i := 1; i < len(lines); i++ {
if lines[i].top > lines[i-1].bottom {
gaps = append(gaps, (lines[i].top+lines[i-1].bottom)/2)
}
}
return gaps
}
// transcribeStrips transcribes a page in strips of at most perStrip lines,
// cutting strips that Gemini still refuses in half again, down to two lines.
// The strips' raw lines are concatenated and parsed as one page.
func (c *geminiClient) transcribeStrips(ctx context.Context, page *image.Gray, gaps []int, perStrip int, extra string) (string, int, int, int, error) {
h := page.Rect.Dy()
cuts := []int{0}
for i := perStrip; i < len(gaps); i += perStrip {
cuts = append(cuts, gaps[i-1])
}
cuts = append(cuts, h)
var raws []string
tin, tout, strips := 0, 0, 0
for i := 0; i+1 < len(cuts); i++ {
strip := cropGray(page, image.Rect(0, cuts[i], page.Rect.Dx(), cuts[i+1]))
prompt := transcribePrompt + "\n\n" + stripPrompt
if extra != "" {
prompt += "\n\n" + extra
}
raw, in, out, err := c.generate(ctx, [][]byte{encodeJPEG(padGray(strip, 0, 64), 90)}, prompt, nil)
tin, tout = tin+in, tout+out
n := 1
if errors.Is(err, errRecitation) && perStrip > 2 {
var sub []int
for _, g := range gaps {
if g > cuts[i] && g < cuts[i+1] {
sub = append(sub, g-cuts[i])
}
}
raw, in, out, n, err = c.transcribeStrips(ctx, strip, sub, max(2, perStrip/2), extra)
tin, tout = tin+in, tout+out
}
if err != nil {
return "", tin, tout, strips, fmt.Errorf("strip %d of %d: %w", i+1, len(cuts)-1, err)
}
strips += n
raws = append(raws, strings.TrimSpace(raw))
}
return strings.Join(raws, "\n"), tin, tout, strips, nil
}
// --- bibliographic data from the front matter ----------------------------
type biblio struct {
Title string `json:"title"`
Subtitle string `json:"subtitle"`
Authors string `json:"authors"`
Translator string `json:"translator"`
Publisher string `json:"publisher"`
Place string `json:"place"`
Year string `json:"year"`
Edition string `json:"edition"`
Series string `json:"series"`
ISBN string `json:"isbn"`
Original string `json:"original_title"`
}
var biblioSchema = map[string]any{
"type": "OBJECT",
"properties": map[string]any{
"title": map[string]any{"type": "STRING"},
"subtitle": map[string]any{"type": "STRING"},
"authors": map[string]any{"type": "STRING"},
"translator": map[string]any{"type": "STRING"},
"publisher": map[string]any{"type": "STRING"},
"place": map[string]any{"type": "STRING"},
"year": map[string]any{"type": "STRING", "description": "Year of the edition shown (not of the first edition or the original), as printed."},
"edition": map[string]any{"type": "STRING"},
"series": map[string]any{"type": "STRING"},
"isbn": map[string]any{"type": "STRING"},
"original_title": map[string]any{"type": "STRING"},
},
"required": []string{"title", "subtitle", "authors", "translator", "publisher", "place", "year", "edition", "series", "isbn", "original_title"},
}
const biblioPrompt = `These are the title page and imprint (copyright page) of a book. Copy the bibliographic details exactly as printed; leave a field empty if it is not printed on these pages. Do not use knowledge from outside the images.`
func (c *geminiClient) biblio(ctx context.Context, imgs [][]byte) (biblio, int, int, error) {
var b biblio
text, in, out, err := c.generate(ctx, imgs, biblioPrompt, biblioSchema)
if err != nil {
return b, in, out, err
}
if err := json.Unmarshal([]byte(text), &b); err != nil {
return b, in, out, fmt.Errorf("gemini: answer is not the requested JSON: %w", err)
}
return b, in, out, nil
}
// usage counts API calls and tokens per service, for the run's record.
type usage struct {
mu sync.Mutex
m map[string]*serviceUsage
}
type serviceUsage struct {
Calls int `json:"calls"`
TokensIn int `json:"tokens_in"`
TokensOut int `json:"tokens_out"`
}
func (u *usage) add(svc string, in, out int) {
u.mu.Lock()
defer u.mu.Unlock()
if u.m == nil {
u.m = map[string]*serviceUsage{}
}
s := u.m[svc]
if s == nil {
s = &serviceUsage{}
u.m[svc] = s
}
s.Calls++
s.TokensIn += in
s.TokensOut += out
}
func (u *usage) snapshot() map[string]serviceUsage {
u.mu.Lock()
defer u.mu.Unlock()
r := map[string]serviceUsage{}
for k, v := range u.m {
r[k] = *v
}
return r
}
|