{title}
{message}
Pages are ordered by vertical alignment of dark marks. Upright columns, rules and illustrations can also rank highly.
- {"".join(cards)}
"""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'
{message}
Pages are ordered by vertical alignment of dark marks. Upright columns, rules and illustrations can also rank highly.