Image Classification
ONNX
onnxruntime
document-orientation
deskew
ocr
image-preprocessing
cpu
File size: 4,865 Bytes
5c3729a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Evaluate eight recovery transforms on real source pages with synthetic orientation changes."""

import argparse
from concurrent.futures import ProcessPoolExecutor
import hashlib
import json
from pathlib import Path
import sys

import numpy as np
from PIL import Image, ImageOps

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from folio_orient import PageOrienter, text_patches, transpose_cw
from reflect import ReflectionDetector, mean_votes

_models = {}


def sources(args):
    manifest = json.loads(args.historical_manifest.read_text())
    rows = [
        ("historical", args.historical / r["file"], r["book"], r["page_type"])
        for r in manifest
        if r["split"] == args.split
    ]
    if args.split == "dev":
        return rows
    for r in json.loads((args.modern / "manifest.json").read_text()):
        if r["reason"] == "eligible":
            rows.append(
                (
                    "contemporary",
                    args.modern / (r["page_hash"] + ".png"),
                    r["category"],
                    "print",
                )
            )
    for r in json.loads((args.newspapers / "manifest.json").read_text()):
        rows.append(
            (
                "newspaper",
                args.newspapers / (r["page_id"] + ".png"),
                r["archive_part"],
                "print",
            )
        )
    return rows


def run_page(task):
    (cohort, file, category, kind), model_path, mirror = task
    if model_path not in _models:
        _models[model_path] = (
            ReflectionDetector(model_path) if mirror else PageOrienter(model_path)
        )
    model = _models[model_path]
    with Image.open(file) as image:
        page = image.convert("L")
    digest = hashlib.sha256(("reflection-tilt|" + file.name).encode()).digest()
    tilt = (1.5 + int.from_bytes(digest[:4], "big") % 550 / 100) * (
        -1 if digest[4] % 2 else 1
    )
    results = []
    for angle in (0, tilt):
        tilted = (
            page.rotate(
                angle,
                Image.Resampling.BICUBIC,
                expand=True,
                fillcolor=page.getpixel((0, 0)),
            )
            if angle
            else page
        )
        for turns in range(4):
            rotated = transpose_cw(tilted, (-90 * turns) % 360)
            for flipped in (False, True):
                observed = ImageOps.mirror(rotated) if flipped else rotated
                patches = text_patches(observed)
                votes = None
                if len(patches):
                    if mirror:
                        votes = model.votes(patches)
                    else:
                        # Test both handedness hypotheses with the same sampled
                        # areas. Each four-way pass normalizes independently.
                        paired = np.concatenate((patches, patches[..., ::-1]))
                        logits = model.session.run(["logits"], {"patches": paired})[0]
                        votes = np.concatenate(
                            [mean_votes(part) for part in np.split(logits, 2)]
                        )
                results.append(
                    dict(
                        tilt=angle,
                        target=turns + 4 * flipped,
                        patches=len(patches),
                        predicted=int(votes.argmax()) if votes is not None else None,
                        agreement=float(votes.max()) if votes is not None else 0.0,
                    )
                )
    return dict(
        cohort=cohort, file=file.name, category=category, page_type=kind, views=results
    )


if __name__ == "__main__":
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--historical", type=Path, required=True)
    p.add_argument("--historical-manifest", type=Path, required=True)
    p.add_argument("--modern", type=Path, required=True)
    p.add_argument("--newspapers", type=Path, required=True)
    p.add_argument("--model", type=Path, required=True)
    p.add_argument("--two-pass-baseline", action="store_true")
    p.add_argument("--workers", type=int, default=8)
    p.add_argument("output", type=Path)
    p.add_argument(
        "--split",
        choices=["test", "dev"],
        default="test",
        help="Dev runs on historical pages only",
    )
    args = p.parse_args()
    rows = sources(args)
    with ProcessPoolExecutor(args.workers) as pool:
        result = list(
            pool.map(
                run_page, [(r, args.model, not args.two_pass_baseline) for r in rows]
            )
        )
    args.output.write_text(
        json.dumps(
            dict(
                model_sha256=hashlib.sha256(args.model.read_bytes()).hexdigest(),
                pages=result,
            ),
            indent=1,
        )
        + "\n"
    )