Redo OCR: disallow in cases that will damage the output PDF

This commit is contained in:
James R. Barlow
2018-10-20 01:14:33 -07:00
parent 6182b1f53e
commit d11c428407
2 changed files with 25 additions and 6 deletions
+13 -4
View File
@@ -251,9 +251,18 @@ def is_ocr_required(pageinfo, log, options):
log.info(msg.format(page,
"rasterizing text and running OCR anyway"))
ocr_required = True
elif options.redo_ocr and pageinfo.only_ocr_text:
log.info(msg.format(page,
"redoing OCR"))
elif options.redo_ocr:
if pageinfo.only_ocr_text:
log.info(msg.format(page,
"redoing OCR"))
else:
log.error(
("%4d: page has both printable and hidden text, so "
"--redo-ocr is not currently possible for this file. "
"Try --force-ocr."),
page
)
raise PriorOcrFoundError()
ocr_required = True
elif options.skip_text:
log.info(msg.format(page,
@@ -590,7 +599,7 @@ def select_ocr_image(
Decimal(bbox[1]) / Decimal(72) * yres,
Decimal(bbox[2]) / Decimal(72) * xres,
Decimal(bbox[3]) / Decimal(72) * yres]
pixcoords = [int(c) for c in pixcoords]
pixcoords = [int(round(c)) for c in pixcoords]
log.debug('blanking %r', pixcoords)
draw.rectangle(pixcoords, fill=white)
#draw.rectangle(pixcoords, outline=pink)
+12 -2
View File
@@ -43,20 +43,29 @@ def _update_page_resources(*, page, font, font_key, procset):
resources['/ProcSet'] = procset
def _strip_old_text(pdf, page):
def _strip_old_invisible_text(pdf, page, log):
stream = []
in_text_obj = False
render_mode = 0
text_objects = []
page.page_contents_coalesce()
for operands, operator in pikepdf.parse_content_stream(page, ''):
if not in_text_obj:
if operator == pikepdf.Operator('BT'):
in_text_obj = True
render_mode = 0
else:
stream.append((operands, operator))
else:
if operator == pikepdf.Operator('Tr'):
render_mode = operands[0]
text_objects.append((operands, operator))
if operator == pikepdf.Operator('ET'):
in_text_obj = False
if render_mode != 3:
stream.extend(text_objects)
text_objects.clear()
def convert(op):
try:
@@ -141,7 +150,7 @@ def _weave_layers_graft(
new_text_layer = pikepdf.Stream(pdf_base, pdf_text_contents)
if strip_old_text:
_strip_old_text(pdf_base, base_page)
_strip_old_invisible_text(pdf_base, base_page, log)
base_page.page_contents_add(new_text_layer, prepend=True)
@@ -370,6 +379,7 @@ def weave_layers(
if text and font:
# Graft the text layer onto this page, whether new or old
# strip_old = context.get_options().redo_ocr
strip_old = (context.get_options().redo_ocr
and pdfinfo[page_num - 1].only_ocr_text)
_weave_layers_graft(