Image Classification
ONNX
onnxruntime
document-orientation
deskew
ocr
image-preprocessing
cpu
File size: 3,430 Bytes
88248d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Exercise the reader commands and compare actual CSV rows to frozen decisions."""
import argparse
import csv
from hashlib import sha256
from html.parser import HTMLParser
from io import StringIO
import json
from pathlib import Path
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
from urllib.parse import unquote

STUDY = Path(__file__).resolve().parent
ROOT = STUDY.parent


class Report(HTMLParser):
    def __init__(self):
        super().__init__()
        self.hrefs = []
        self.thumbnails = []

    def handle_starttag(self, tag, attrs):
        attrs = dict(attrs)
        if tag == "a":
            self.hrefs.append(unquote(attrs["href"]))
        if tag == "img":
            assert attrs["src"].startswith("data:image/jpeg;base64,")
            self.thumbnails.append(attrs["alt"])


def run(*args, ok=True):
    result = subprocess.run([sys.executable, str(ROOT/"review_text.py"), *map(str,args)],
                            capture_output=True, text=True)
    assert (result.returncode==0) == ok, (result.returncode,result.stderr)
    return result.stdout


def main(pdfs):
    with TemporaryDirectory() as tmp:
        folder = Path(tmp)
        pdf = folder/"Field & notes #1.pdf"
        shutil.copyfile(ROOT/"examples/field-notes.pdf",pdf)
        before = pdf.read_bytes()
        out = folder/"review.html"
        lines = run(pdf,"--html",out,"--previews","2")
        assert lines == (ROOT/"examples/review.csv").read_text()
        doc = Report()
        doc.feed(out.read_text())
        assert sorted(doc.hrefs) == [pdf.name+f"#page={p}" for p in range(1,6)]
        assert len(doc.thumbnails) == 2 and "Page 4" in doc.thumbnails[1]
        report_hash = sha256(out.read_bytes()).digest()
        run(pdf,"--html",out,ok=False)
        run(pdf,"--html",pdf,ok=False)
        run(pdf,"--previews","-1",ok=False)
        assert pdf.read_bytes()==before and sha256(out.read_bytes()).digest()==report_hash
        damaged = folder/"broken.pdf"
        damaged.write_bytes(b"not a PDF")
        run(damaged,"--html",folder/"bad.html",ok=False)
        assert not (folder/"bad.html").exists()
    if pdfs is not None:
        rows = [json.loads(line) for line in (STUDY/"pages.jsonl").read_text().splitlines()]
        for series in sorted({r["series"] for r in rows}):
            src = pdfs/f"wsp{series}.pdf"
            actual = list(csv.DictReader(StringIO(run(src))))
            expected = [r for r in rows if r["series"]==series]
            assert len(actual)==len(expected)
            for r,ref in zip(actual, expected):
                text = ref["text"]
                turn = str(text["predicted"]) if text["accepted"] else ""
                assert int(r["page"]) == ref["page"] and r["clockwise"] == turn
                assert r["action"] == ("inspect" if turn=="" else ("keep" if turn=="0" else "turn"))
                assert [int(r[f"votes_{n}"]) for n in (0,90,180,270)] == text["votes"]
                assert r["agreement"] == (str(text["score"]) if text["score"] is not None else "")
        print(f"Matched the reader CSV against {len(rows)} studied pages.")
    print("Verified the five-page example, links, preview limit, input preservation and failure handling.")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("pdfs", nargs="?", type=Path)
    main(parser.parse_args().pdfs)