Add a local searchable-PDF orientation reader, a stale OCR example, and verified results on 343 USGS and 553 Bengali archive pages
88248d0 verified Download text-layer/text_angle.py from foliokestrel/folio-orient: direct link, hf CLI and curl.
- Browser
- Download file 1.36 kB
-
https://huggingface.co/foliokestrel/folio-orient/resolve/main/text-layer/text_angle.py
- Command line
-
hf download hf://foliokestrel/folio-orient/text-layer/text_angle.py
-
curl -L -o text_angle.py https://huggingface.co/foliokestrel/folio-orient/resolve/main/text-layer/text_angle.py
1.36 kB
| """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) | |