File size: 2,968 Bytes
7bb24f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Read printed Abkhaz text lines with the four-alphabet reader.

    python read_lines.py model line1.png line2.png …
        each image is ONE printed line; every line is read freely

    python read_lines.py model --block line1.png line2.png …
        the images are the lines of ONE text block (a column, a paragraph): the block is read
        in one alphabet, chosen from what its lines show — the way the Foundation's app reads.
        A block earns an old alphabet from several of its words, so give it the whole block;
        a single old-alphabet line is better read freely (without --block)

Needs torch, numpy, Pillow and `ocr_nets.py` from this folder. CPU is fine: a line takes
milliseconds. The reader was trained on lines cut tightly around the printed text (a few
pixels of paper around the letters), grey or colour scans of 25–80 px line height.
"""
import json
import os
import sys

import numpy as np
import torch
from PIL import Image

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from ocr_nets import CRNN, REC_HEIGHT, ctc_greedy, load_script_masks, lock_block  # noqa: E402


def load(model_dir):
    chars = json.loads(open(os.path.join(model_dir, "charset.json"), encoding="utf-8").read())
    itos = ["\0"] + list(chars)                      # class 0 is the CTC blank
    model = CRNN(len(itos))
    model.load_state_dict(torch.load(os.path.join(model_dir, "best.pt"), map_location="cpu"))
    model.eval()
    return model, itos, load_script_masks(model_dir, itos)


def prepare(path):
    """A line image → float array [48, W]: grey, 48 px high, ink high and paper low."""
    im = Image.open(path).convert("L")
    w = max(8, min(1000, round(im.width * REC_HEIGHT / max(1, im.height))))
    im = im.resize((w, REC_HEIGHT), Image.BILINEAR)
    return 1.0 - np.asarray(im, dtype="float32") / 255.0


def read(model, itos, paths):
    """Logits per line, [T, C] each — the input of both decoders below."""
    arrays = [prepare(p) for p in paths]
    width = max(a.shape[1] for a in arrays)
    batch = torch.zeros(len(arrays), 1, REC_HEIGHT, width)
    for i, a in enumerate(arrays):
        batch[i, 0, :, :a.shape[1]] = torch.from_numpy(a)
    with torch.inference_mode():
        return model(batch)


def main():
    args = sys.argv[1:]
    block = "--block" in args
    args = [a for a in args if a != "--block"]
    if len(args) < 2:
        sys.exit(__doc__)
    model, itos, masks = load(args[0])
    paths = args[1:]
    logits = read(model, itos, paths)
    if block and masks:
        alphabet, lines, vote = lock_block([logits[i] for i in range(len(paths))], itos, masks)
        print(f"block alphabet: {alphabet}")
        for p, (text, conf, alph) in zip(paths, lines):
            print(f"{os.path.basename(p)}\t{alph}\t{text}")
    else:
        for p, text in zip(paths, ctc_greedy(logits, itos)):
            print(f"{os.path.basename(p)}\t{text}")


if __name__ == "__main__":
    main()