MCPcopy Index your code
hub / github.com/pymupdf/PyMuPDF / get_textpage_ocr

Function get_textpage_ocr

src/utils.py:317–398  ·  view source on GitHub ↗

Create a Textpage from combined results of normal and OCR text parsing. Args: flags: (int) control content becoming part of the result. language: (str) specify expected language(s). Default is "eng" (English). dpi: (int) resolution in dpi, default 72. full: (bool

(
    page: pymupdf.Page,
    flags: int = 0,
    language: str = "eng",
    dpi: int = 72,
    full: bool = False,
    tessdata: str = None,
)

Source from the content-addressed store, hash-verified

315
316
317def get_textpage_ocr(
318 page: pymupdf.Page,
319 flags: int = 0,
320 language: str = "eng",
321 dpi: int = 72,
322 full: bool = False,
323 tessdata: str = None,
324) -> pymupdf.TextPage:
325 """Create a Textpage from combined results of normal and OCR text parsing.
326
327 Args:
328 flags: (int) control content becoming part of the result.
329 language: (str) specify expected language(s). Default is "eng" (English).
330 dpi: (int) resolution in dpi, default 72.
331 full: (bool) whether to OCR the full page image, or only its images (default)
332 """
333 pymupdf.CheckParent(page)
334 tessdata = pymupdf.get_tessdata(tessdata)
335
336 def full_ocr(page, dpi, language, flags):
337 zoom = dpi / 72
338 mat = pymupdf.Matrix(zoom, zoom)
339 pix = page.get_pixmap(matrix=mat)
340 ocr_pdf = pymupdf.Document(
341 "pdf",
342 pix.pdfocr_tobytes(
343 compress=False,
344 language=language,
345 tessdata=tessdata,
346 ),
347 )
348 ocr_page = ocr_pdf.load_page(0)
349 unzoom = page.rect.width / ocr_page.rect.width
350 ctm = pymupdf.Matrix(unzoom, unzoom) * page.derotation_matrix
351 tpage = ocr_page.get_textpage(flags=flags, matrix=ctm)
352 ocr_pdf.close()
353 pix = None
354 tpage.parent = weakref.proxy(page)
355 return tpage
356
357 # if OCR for the full page, OCR its pixmap @ desired dpi
358 if full:
359 return full_ocr(page, dpi, language, flags)
360
361 # For partial OCR, make a normal textpage, then extend it with text that
362 # is OCRed from each image.
363 # Because of this, we need the images flag bit set ON.
364 tpage = page.get_textpage(flags=flags)
365 for block in page.get_text("dict", flags=pymupdf.TEXT_PRESERVE_IMAGES)["blocks"]:
366 if block["type"] != 1: # only look at images
367 continue
368 bbox = pymupdf.Rect(block["bbox"])
369 if bbox.width <= 3 or bbox.height <= 3: # ignore tiny stuff
370 continue
371 try:
372 pix = pymupdf.Pixmap(block["image"]) # get image pixmap
373 if pix.n - pix.alpha != 3: # we need to convert this to RGB!
374 pix = pymupdf.Pixmap(pymupdf.csRGB, pix)

Callers

nothing calls this directly

Calls 7

pdfocr_tobytesMethod · 0.95
load_pageMethod · 0.95
closeMethod · 0.95
extend_textpageMethod · 0.80
full_ocrFunction · 0.70
get_textpageMethod · 0.45
get_textMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…