Image Classification
ONNX
onnxruntime
document-orientation
deskew
ocr
image-preprocessing
cpu
folio-orient / text-layer /study /scan_tables.py
foliokestrel's picture
Add a local searchable-PDF orientation reader, a stale OCR example, and verified results on 343 USGS and 553 Bengali archive pages
88248d0 verified
Raw History Blame Contribute Delete
6.42 kB
"""Rank PDF pages for visual inspection of sideways text and tables."""
import argparse
from base64 import b64encode
from contextlib import closing
import csv
from html import escape
from io import BytesIO
import os
from pathlib import Path
import sys
from tempfile import NamedTemporaryFile
from urllib.parse import quote
import numpy as np
import pypdfium2 as pdfium
def render(document, page_number):
with closing(document[page_number-1]) as page:
scale = min(3, 720 / max(page.get_size()))
with closing(page.render(scale=scale)) as bitmap:
return bitmap.to_pil().convert("RGB")
def variation(profile):
return np.mean([np.abs(profile[lag:] - profile[:-lag]).mean() for lag in (1, 2, 4)])
def measure(image):
gray = np.asarray(image.convert("L"))
h, w = gray.shape
gray = gray[h//10:h-h//10, w//10:w-w//10]
if min(gray.shape) <= 4:
return None, None
threshold = min(196, max(70, int(np.percentile(gray, 85)) - 48))
ink = gray < threshold
columns = variation(ink.mean(axis=0))
rows = variation(ink.mean(axis=1))
return float(ink.mean()), float(np.log((columns + .001) / (rows + .001)))
def screen(document, sample_pages=None):
n = len(document)
if sample_pages and sample_pages < n:
positions = np.linspace(0,n-1,sample_pages).round().astype(int) + 1
else:
positions = range(1,n+1)
records = []
for page in positions:
fraction, score = measure(render(document, int(page)))
records.append(dict(page=int(page), ink=fraction, score=score))
return records
def exclusion_reason(record):
ink = record["ink"]
if ink is None:
return "thumbnail too small"
if ink < .01:
return "less than 1% ink"
if ink > .55:
return "more than 55% ink"
return None
def ranked(records, limit):
eligible = [r for r in records if exclusion_reason(r) is None]
return sorted(eligible, key=lambda r: (-r["score"], r["page"]))[:limit]
def write_report(path, source, document, selected, records):
# Quotes and fragments in filenames must not change the target page link.
relative = os.path.relpath(source.resolve(), path.parent.resolve())
href = escape(quote(Path(relative).as_posix()), quote=True)
cards = []
for rank, record in enumerate(selected, 1):
page = record["page"]
img = render(document, page)
img.thumbnail((420, 420))
data = BytesIO()
img.save(data, "JPEG", quality=85)
encoded = b64encode(data.getvalue()).decode("ascii")
cards.append(f'<li><a href="{href}#page={page}"><img src="data:image/jpeg;base64,{encoded}" alt="Preview of page {page}">'
f'<strong>Page {page}</strong></a><span>Rank {rank} 路 score {record["score"]:.3f}</span></li>')
excluded = []
for record in records:
reason = exclusion_reason(record)
if reason is not None:
number = record["page"]
excluded.append(f'<li><a href="{href}#page={number}">Page {number}</a> 路 {reason}</li>')
exclusions = ""
if excluded:
exclusions = (f'<details><summary>{len(excluded)} inspected pages excluded from ranking</summary>'
f'<ul>{"".join(excluded)}</ul></details>')
inspected = len(records)
title = escape(source.name)
message = (f'{len(selected)} pages to review from {inspected} inspected. Open a thumbnail to read the original PDF page.'
if selected else f'No page met the ink-density filter among the {inspected} pages inspected.')
html = f'''<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Sideways-page review 路 {title}</title>
<style>
* {{box-sizing:border-box}} body {{margin:2rem auto;padding:0 1.25rem;max-width:80rem;color:#19313b;background:#faf8f1;font:1rem/1.5 "Source Sans 3",system-ui,sans-serif}}
h1 {{font:normal clamp(1.8rem,4vw,3rem)/1.2 Georgia,serif;overflow-wrap:anywhere}}
ol {{list-style:none;display:grid;padding:0;grid-template-columns:repeat(auto-fit,minmax(min(16rem,100%),1fr));gap:1.4rem}}
ol > li {{padding:.8rem;background:white;border:1px solid #c8cec9}} a {{color:#70301e}} img {{display:block;width:100%;height:18rem;object-fit:contain;background:#edece6}}
strong,span {{display:block;margin-top:.35rem}} span {{color:#42565e}}
</style><main><h1>{title}</h1><p>{message}</p>
<p>Pages are ordered by vertical alignment of dark marks. Upright columns, rules and illustrations can also rank highly.</p>
<ol>{"".join(cards)}</ol>{exclusions}</main></html>'''
temporary = None
try:
with NamedTemporaryFile("w", encoding="utf-8", dir=path.parent, delete=False) as output:
temporary = Path(output.name)
output.write(html)
os.link(temporary, path)
finally:
if temporary is not None:
temporary.unlink(missing_ok=True)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("pdf", type=Path)
parser.add_argument("--limit", type=int, default=12, help="Maximum number of review candidates (default 12)")
parser.add_argument("--sample-pages", type=int, help="Inspect up to this many evenly spaced pages (default all)")
parser.add_argument("--html", type=Path, help="Write a new local thumbnail report linking to physical PDF pages")
args = parser.parse_args()
if args.limit < 1 or (args.sample_pages is not None and args.sample_pages < 1):
parser.error("--limit and --sample-pages must be positive")
if args.html and args.html.exists():
parser.error("Report already exists; choose a new filename")
try:
with pdfium.PdfDocument(args.pdf) as document:
records = screen(document, args.sample_pages)
selected = ranked(records, args.limit)
if args.html:
write_report(args.html, args.pdf, document, selected, records)
writer = csv.writer(sys.stdout, lineterminator="\n")
writer.writerow(["rank", "physical_page", "vertical_score", "ink_fraction"])
for pos, row in enumerate(selected, 1):
writer.writerow([pos, row["page"], f"{row['score']:.6f}", f"{row['ink']:.6f}"])
except (OSError, pdfium.PdfiumError, ValueError) as exc:
parser.exit(1, f"{parser.prog}: {exc}\n")
if __name__ == "__main__":
main()