mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-05 12:24:28 +01:00
93 lines
4.1 KiB
Python
Executable File
93 lines
4.1 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""The OCR lane's proof: a page of known text, as a PDF written here, read by the lane at the URL given (its front, or the proxy
|
|
with the box's key in OCR_KEY_FILE), and the words it must give back. Standard library only; exit 0 when every word came back.
|
|
|
|
ocr-check.py http://127.0.0.1:30032
|
|
|
|
The PDF is written here with no library: one A4 page, Helvetica, three lines. The lane draws it in its own container (pdfium),
|
|
reads it with its model, and answers its Markdown: what is checked is that the words of each line are there, in order, whatever
|
|
the model made of the layout (a heading, a paragraph, a table)."""
|
|
import base64
|
|
import json
|
|
import os
|
|
import re
|
|
import sys
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
LINES = ["Alzeo reads this page", "Invoice 4271 dated 12 March 2026", "Total due 1 234,56 EUR"]
|
|
WANT = [["alzeo", "reads", "this", "page"], ["invoice", "4271", "12", "march", "2026"], ["total", "due", "234,56", "eur"]]
|
|
|
|
|
|
def pdf() -> bytes:
|
|
"""One A4 page with LINES in Helvetica 26, its cross-reference table counted byte by byte."""
|
|
text = "BT /F1 26 Tf 72 760 Td " + " 0 -52 Td ".join(f"({x}) Tj" for x in LINES) + " ET"
|
|
objects = ["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
|
|
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>",
|
|
f"<< /Length {len(text)} >>\nstream\n{text}\nendstream", "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"]
|
|
out, offsets = b"%PDF-1.4\n", []
|
|
for i, o in enumerate(objects, 1):
|
|
offsets.append(len(out))
|
|
out += f"{i} 0 obj\n{o}\nendobj\n".encode()
|
|
xref = len(out)
|
|
out += f"xref\n0 {len(objects) + 1}\n0000000000 65535 f \n".encode()
|
|
out += b"".join(f"{o:010d} 00000 n \n".encode() for o in offsets)
|
|
out += f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n".encode()
|
|
return out
|
|
|
|
|
|
def words(markdown: str) -> list:
|
|
"""The words of an answer, lower-cased, Markdown's marks and table bars dropped, a number's comma kept."""
|
|
return re.findall(r"[0-9]+(?:,[0-9]+)?|[a-zà-ÿ]+", markdown.lower())
|
|
|
|
|
|
def found(markdown: str) -> list:
|
|
"""For each line, the words of it the answer lacks, or that it gives out of order."""
|
|
have, out = words(markdown), []
|
|
for want in WANT:
|
|
at, lacks = 0, []
|
|
for w in want:
|
|
try:
|
|
at = have.index(w, at) + 1
|
|
except ValueError:
|
|
lacks.append(w)
|
|
out.append(lacks)
|
|
return out
|
|
|
|
|
|
def main():
|
|
base = (sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:30032").rstrip("/")
|
|
body = json.dumps({"document": {"type": "document_url", "document_url": "data:application/pdf;base64," + base64.b64encode(pdf()).decode(),
|
|
"document_name": "ocr-check.pdf"}, "mode": "markdown"}).encode()
|
|
headers = {"Content-Type": "application/json"}
|
|
key_file = os.environ.get("OCR_KEY_FILE")
|
|
if key_file:
|
|
with open(key_file) as f:
|
|
headers["Authorization"] = "Bearer " + f.readline().strip()
|
|
t0 = time.monotonic()
|
|
try:
|
|
with urllib.request.urlopen(urllib.request.Request(base + "/v1/ocr", data=body, headers=headers), timeout=600) as r:
|
|
doc = json.load(r)
|
|
except urllib.error.HTTPError as e:
|
|
print(f"ocr-check: the lane answered {e.code}: {e.read()[:400].decode('utf-8', 'replace')}")
|
|
return 1
|
|
except OSError as e:
|
|
print(f"ocr-check: the lane did not answer ({e})")
|
|
return 1
|
|
pages = doc.get("pages") or []
|
|
md = "\n".join(p.get("markdown") or "" for p in pages)
|
|
lacks = found(md)
|
|
print(f"ocr-check: {len(pages)} page(s) in {time.monotonic() - t0:.1f} s, model {doc.get('model')!r}: {md[:300]!r}")
|
|
if len(pages) != 1 or any(lacks):
|
|
for line, miss in zip(LINES, lacks):
|
|
if miss:
|
|
print(f"ocr-check: the line {line!r} came back without {', '.join(miss)} (or not in that order)")
|
|
return 1
|
|
print("ocr-check: every word of the page came back, in order")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|