"""Read quarter-turn votes from alphanumeric glyphs in a PDF text layer.""" from contextlib import closing import math import pypdfium2.raw as pdfium def estimate(page): rotation = page.get_rotation() votes = [0] * 4 off_axis = 0 with closing(page.get_textpage()) as text: for index in range(text.count_chars()): code = pdfium.FPDFText_GetUnicode(text, index) if code > 0x10ffff or not chr(code).isalnum(): continue angle = pdfium.FPDFText_GetCharAngle(text, index) if not math.isfinite(angle) or angle < 0: continue # PDFium reports the glyph angle clockwise. A clockwise correction # cancels both that angle and the existing physical page rotation. degrees = -math.degrees(angle) - rotation nearest = round(degrees / 90) if abs(degrees - 90 * nearest) <= 15: votes[nearest % 4] += 1 else: off_axis += 1 total = sum(votes) direction = votes.index(max(votes)) if total else None agreement = max(votes)/total if total else None return dict(predicted=90*direction if total else None, score=agreement, accepted=total >= 24 and agreement >= .8, votes=votes, off_axis=off_axis, page_rotation=rotation)