"""Exercise the text-layer policy with independently specified PDF glyph and display rotations.""" from contextlib import closing from io import BytesIO import math import json from pypdf import PdfWriter from pypdf.generic import DictionaryObject, NameObject, DecodedStreamObject import pypdfium2 from pathlib import Path import sys sys.path.insert(0, str(Path(__file__).resolve().parents[1])) from text_angle import estimate def make_pdf(cases): writer = PdfWriter() font = DictionaryObject({NameObject("/Type"):NameObject("/Font"), NameObject("/Subtype"):NameObject("/Type1"), NameObject("/BaseFont"):NameObject("/Helvetica")}) for rotation, fragments, hidden, _, _ in cases: page = writer.add_blank_page(600, 600) page.rotate(rotation) page[NameObject("/Resources")] = DictionaryObject({NameObject("/Font"):DictionaryObject({NameObject("/F"):font})}) lines = [] for row, (angle, text) in enumerate(fragments): ca, sa = math.cos(math.radians(angle)), math.sin(math.radians(angle)) lines.append(f'BT /F 8 Tf {3 if hidden else 0} Tr {ca:.8f} {sa:.8f} {-sa:.8f} {ca:.8f} 300 {190+row*40} Tm ({text}) Tj ET') content = DecodedStreamObject() content.set_data("\n".join(lines).encode()) page[NameObject("/Contents")] = writer._add_object(content) buf = BytesIO() writer.write(buf) return buf.getvalue() def main(): sample = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" cases = [(rotation, [(angle, sample)], hidden, (angle-rotation)%360, True) for hidden in (True,False) for rotation in range(0,360,90) for angle in range(0,360,90)] cases += [(0, [], False, None, False), (0,[(90,"ABC")],False,90,False), (0,[(30,sample)],False,None,False), (0,[(0,sample),(90,sample)],True,0,False), (0,[(90,sample),(0,"ABCDE")],True,90,True), (0,[(0,"123456789012345678901234")],True,0,True)] with pypdfium2.PdfDocument(make_pdf(cases)) as doc: for i, spec in enumerate(cases): with closing(doc[i]) as page: action = estimate(page) assert (action["predicted"], action["accepted"]) == spec[3:], (spec,action) print(json.dumps(dict(passed=len(cases), covered="glyph orientations, page rotations, visible and invisible text, off-axis, sparse and mixed evidence"))) if __name__ == "__main__": main()