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). Deafault is "eng" (English). dpi: (int) resolution in dpi, default 72. full: (boo
(
page: Page,
flags: int = 0,
language: str = "eng",
dpi: int = 72,
full: bool = False,
tessdata: str = None,
)
| 608 | |
| 609 | |
| 610 | def get_textpage_ocr( |
| 611 | page: Page, |
| 612 | flags: int = 0, |
| 613 | language: str = "eng", |
| 614 | dpi: int = 72, |
| 615 | full: bool = False, |
| 616 | tessdata: str = None, |
| 617 | ) -> TextPage: |
| 618 | """Create a Textpage from combined results of normal and OCR text parsing. |
| 619 | |
| 620 | Args: |
| 621 | flags: (int) control content becoming part of the result. |
| 622 | language: (str) specify expected language(s). Deafault is "eng" (English). |
| 623 | dpi: (int) resolution in dpi, default 72. |
| 624 | full: (bool) whether to OCR the full page image, or only its images (default) |
| 625 | """ |
| 626 | CheckParent(page) |
| 627 | if not os.getenv("TESSDATA_PREFIX") and not tessdata: |
| 628 | raise RuntimeError("No OCR support: TESSDATA_PREFIX not set") |
| 629 | |
| 630 | def full_ocr(page, dpi, language, flags): |
| 631 | zoom = dpi / 72 |
| 632 | mat = Matrix(zoom, zoom) |
| 633 | pix = page.get_pixmap(matrix=mat) |
| 634 | ocr_pdf = Document( |
| 635 | "pdf", |
| 636 | pix.pdfocr_tobytes(compress=False, language=language, tessdata=tessdata), |
| 637 | ) |
| 638 | ocr_page = ocr_pdf.load_page(0) |
| 639 | unzoom = page.rect.width / ocr_page.rect.width |
| 640 | ctm = Matrix(unzoom, unzoom) * page.derotation_matrix |
| 641 | tpage = ocr_page.get_textpage(flags=flags, matrix=ctm) |
| 642 | ocr_pdf.close() |
| 643 | pix = None |
| 644 | tpage.parent = weakref.proxy(page) |
| 645 | return tpage |
| 646 | |
| 647 | # if OCR for the full page, OCR its pixmap @ desired dpi |
| 648 | if full is True: |
| 649 | return full_ocr(page, dpi, language, flags) |
| 650 | |
| 651 | # For partial OCR, make a normal textpage, then extend it with text that |
| 652 | # is OCRed from each image. |
| 653 | # Because of this, we need the images flag bit set ON. |
| 654 | tpage = page.get_textpage(flags=flags) |
| 655 | for block in page.get_text("dict", flags=TEXT_PRESERVE_IMAGES)["blocks"]: |
| 656 | if block["type"] != 1: # only look at images |
| 657 | continue |
| 658 | bbox = Rect(block["bbox"]) |
| 659 | if bbox.width <= 3 or bbox.height <= 3: # ignore tiny stuff |
| 660 | continue |
| 661 | try: |
| 662 | pix = Pixmap(block["image"]) # get image pixmap |
| 663 | if pix.n - pix.alpha != 3: # we need to convert this to RGB! |
| 664 | pix = Pixmap(csRGB, pix) |
| 665 | if pix.alpha: # must remove alpha channel |
| 666 | pix = Pixmap(pix, 0) |
| 667 | imgdoc = Document( |
nothing calls this directly
no test coverage detected
searching dependent graphs…