File size: 7,127 Bytes
76ee164 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | """Carry original invisible PDF text objects onto reviewed reading pages."""
from collections import Counter, defaultdict
import ctypes
from io import BytesIO
from contextlib import closing
import math
import pypdfium2 as pdfium
from pypdfium2 import raw
def displayed_matrix(page):
"""PDF user coordinates to the upright cropped page, with a bottom-left origin."""
left, bottom, right, top = page.get_bbox()
transforms = {
0: (1, 0, 0, 1, -left, -bottom),
90: (0, -1, 1, 0, -bottom, right),
180: (-1, 0, 0, -1, right, top),
270: (0, 1, -1, 0, top, -left),
}
return pdfium.PdfMatrix(*transforms[page.get_rotation()])
def destination(points, size, raster, decision):
width, height = size
if not all(
math.isfinite(x) and math.isfinite(y) and 0 <= x <= width and 0 <= y <= height
for x, y in points
):
return "outside_crop"
if decision["state"] == "whole":
return "whole"
# Match the raster cutter. A box within one raster pixel of the fold is ambiguous.
top, bottom = decision["top_x"], decision["bottom_x"]
differences = [
(x / width - (bottom + (top - bottom) * y / height)) * raster[0]
for x, y in points
]
tolerance = 0.5 + abs(top - bottom) * raster[0] / (2 * raster[1])
if max(differences) < -tolerance:
return "left"
if min(differences) > tolerance:
return "right"
return "at_cut"
def key(obj):
return ctypes.cast(obj, ctypes.c_void_p).value
def character_runs(page):
"""Actual decoded characters and their selection boxes, grouped by source text object."""
runs = defaultdict(list)
with closing(page.get_textpage()) as tp:
for i in range(tp.count_chars()):
if raw.FPDFText_IsGenerated(tp, i) == 1:
continue
obj = raw.FPDFText_GetTextObject(tp, i)
if obj:
runs[key(obj)].append(
(raw.FPDFText_GetUnicode(tp, i), tp.get_charbox(i))
)
return runs
def matches(expected, actual):
return (
bool(expected)
and len(expected) == len(actual)
and all(
a == b and max(abs(x - y) for x, y in zip(box_a, box_b)) <= 0.25
for (a, box_a), (b, box_b) in zip(expected, actual)
)
)
def checked_layer(output, scratch, index, expected, omitted):
"""Reopen serialized text before accepting its Unicode and placement."""
# Font widths, character spacing and TJ arrays may change when PDFium
# regenerates text. Checking live objects before serialization misses this.
with pdfium.PdfDocument.new() as clean:
clean.import_pages(scratch, pages=[index])
buffer = BytesIO()
clean.save(buffer)
for attempt in range(2):
buffer.seek(0)
with pdfium.PdfDocument(buffer) as serialized, closing(serialized[0]) as page:
objects = list(
page.get_objects(filter=[raw.FPDF_PAGEOBJ_TEXT], max_depth=1)
)
if len(objects) != len(expected):
break
runs = character_runs(page)
keep = [
matches(chars, runs[key(obj)]) for obj, chars in zip(objects, expected)
]
if all(keep):
output.import_pages(serialized, pages=[0])
return len(expected)
if attempt or not any(keep):
break
omitted["serialization_mismatch"] += keep.count(False)
for obj, ok in zip(objects, keep):
if not ok:
page.remove_obj(obj)
obj.close()
page.gen_content()
expected = [chars for chars, ok in zip(expected, keep) if ok]
buffer = BytesIO()
serialized.save(buffer)
omitted["serialization_mismatch"] += len(expected)
return 0
def append_searchable(
output, book, index, sides, raster, right_origin, unit, decision, append_image
):
# Copy the page so the caller's input and all shared font objects remain intact.
omitted = Counter()
kept = {}
with pdfium.PdfDocument.new() as scratch:
scratch.import_pages(book, pages=[index])
with closing(scratch[0]) as source:
size = source.get_size()
view = displayed_matrix(source)
runs = character_runs(source)
objects = {side: [] for side, _ in sides}
for obj in source.get_objects(filter=[raw.FPDF_PAGEOBJ_TEXT]):
if (
raw.FPDFTextObj_GetTextRenderMode(obj)
!= raw.FPDF_TEXTRENDERMODE_INVISIBLE
):
omitted["other_render_mode"] += 1
continue
if obj.level:
omitted["inside_form"] += 1
continue
if raw.FPDFClipPath_CountPaths(raw.FPDFPageObj_GetClipPath(obj)) > 0:
omitted["clipped"] += 1
continue
chars = runs[key(obj)]
if not chars:
omitted["unmapped"] += 1
continue
# Include the glyph selection boxes as well as the painted run bounds.
points = list(obj.get_quad_points())
for _, (left, bottom, right, top) in chars:
points.extend(
((left, bottom), (left, top), (right, top), (right, bottom))
)
side = destination(
[view.on_point(x, y) for x, y in points], size, raster, decision
)
if side in objects:
objects[side].append((obj, chars))
else:
omitted[side] += 1
for side, image in sides:
width_pt = size[0] * unit * image.width / raster[0]
height_pt = size[1] * unit
dx = (
-right_origin * size[0] * unit / raster[0] if side == "right" else 0
)
transform = view.scale(unit, unit).translate(dx, 0)
kept[side] = 0
if objects[side]:
expected = []
with closing(scratch.new_page(width_pt, height_pt)) as target:
for obj, chars in objects[side]:
source.remove_obj(obj)
obj.transform(transform)
target.insert_obj(obj)
expected.append(
[(code, transform.on_rect(*box)) for code, box in chars]
)
target.gen_content()
kept[side] = checked_layer(
output, scratch, len(scratch) - 1, expected, omitted
)
append_image(
output, image, width_pt, height_pt, use_last_page=bool(kept[side])
)
return {"retained_by_side": kept, "omitted_by_reason": dict(omitted)}
|