|
| 1 | +Default OCR Functions |
| 2 | +====================== |
| 3 | + |
| 4 | +PyMuPDF4LLM supports default OCR functions. They come in the form of plugins that are present in its `ocr` subpackage. They are based on currently 3 popular OCR engines, Tesseract OCR, RapidOCR and PaddleOCR. Some engines can be combined to make use of their strengths and mitigate their weaknesses. For example, Tesseract OCR is very good at **recognizing** text, while RapidOCR is better at **detecting** text bounding boxes in images with complex backgrounds. By combining the two engines, we can achieve better overall OCR results while at the samne time also reducing the overall OCR processing time. |
| 5 | + |
| 6 | +Here is an overview of the available default plugins: |
| 7 | + |
| 8 | +============== ========================= ================================================================================= |
| 9 | +Plugin Name Engines Description |
| 10 | +============== ========================= ================================================================================= |
| 11 | +rapidocr_api RapidOCR Uses RapidOCR for both text **detection** and text **recognition** |
| 12 | +paddleocr_api PaddleOCR Uses PaddleOCR for both text **detection** and text **recognition** |
| 13 | +tesseract_api Tesseract OCR Uses Tesseract OCR for both text **detection** and text **recognition** |
| 14 | +rapidtess_api RapidOCR + Tesseract OCR Uses RapidOCR for text **detection** and Tesseract OCR for text **recognition** |
| 15 | +paddletess_api PaddleOCR + Tesseract OCR Uses PaddleOCR for text **detection** and Tesseract OCR for text **recognition** |
| 16 | +============== ========================= ================================================================================= |
| 17 | + |
| 18 | +If not explicitely selected via the `ocr_function` parameter, PyMuPDF4LLM will check the availability of the three OCR engines and pick one of the above plugins in the following order of preference: |
| 19 | + |
| 20 | +1. `rapidtess_api` (if both RapidOCR and Tesseract OCR are available) |
| 21 | +2. `paddletess_api` (if both PaddleOCR and Tesseract OCR are available) |
| 22 | +3. `rapidocr_api` (if RapidOCR is available, but not Tesseract OCR) |
| 23 | +4. `paddleocr_api` (if PaddleOCR is available, but not Tesseract OCR) |
| 24 | +5. `tesseract_api` (if Tesseract OCR is available, but neither RapidOCR nor PaddleOCR are available) |
| 25 | + |
| 26 | +If none of these engines is available (and no own plugin is provided), no OCR will be performed at all. If the `force_ocr` parameter is ``True``, an error will be raised. Otherwise, the document will be processed without OCR and a warning will be displayed. |
| 27 | + |
| 28 | +The chosen plugin is displayed as an information message. |
| 29 | + |
| 30 | +How Default Plugins Work |
| 31 | +------------------------ |
| 32 | + |
| 33 | +The provided default plugins use the following **"hybrid"** OCR approach: |
| 34 | + |
| 35 | +1. Each page is cleaned from any existing standard text content. |
| 36 | +2. The remaining page is rendered as an image and passed to the OCR engine for text detection and recognition. |
| 37 | +3. Only the detected text is inserted back into the original page as standard text content. |
| 38 | + |
| 39 | +In this way, all original content (text and other elements) is preserved and only **augmented** with the newly recognized text. This allows for a more accurate and complete text extraction while also preserving the original document structure and formatting as much as possible. It also allows for a more efficient OCR processing since only the non-extractable text is processed by the OCR engine. This can significantly reduce the overall processing time. |
| 40 | + |
| 41 | +It also increases the chances for a successful layout detection, because other original content like vectors remains intact and is not rendered to pixels. |
| 42 | + |
| 43 | +Forcing the Choice of a Default Plugin |
| 44 | +--------------------------------------- |
| 45 | +The default plugins are designed to be used as is, without any need for configuration. However, if you want to use a specific plugin, you can do so by using the following approach (which enforces for instance using RapidOCR and skipping above selection process). Please note that all plugins have a function named `exec_ocr` that does the actual OCR:: |
| 46 | + |
| 47 | + import pymupdf4llm |
| 48 | + from pymupdf4llm.ocr import rapidocr_api |
| 49 | + |
| 50 | + my_ocr_function = rapidocr_api.exec_ocr |
| 51 | + |
| 52 | + # Use my_ocr_function as the OCR function in PyMuPDF4LLM |
| 53 | + md_text = pymupdf4llm.to_markdown("input.pdf", ocr_function=my_ocr_function) |
| 54 | + |
| 55 | + |
| 56 | +Providing your Own Plugin |
| 57 | +------------------------- |
| 58 | + |
| 59 | +If you want to use your own OCR function, you can do so as follows:: |
| 60 | + |
| 61 | + import pymupdf4llm |
| 62 | + |
| 63 | + def my_ocr_function(page, pixmap=None, dpi=300, language="eng"): |
| 64 | + # Your OCR implementation here |
| 65 | + return None |
| 66 | + |
| 67 | + # Use my_ocr_function as the OCR function in PyMuPDF4LLM |
| 68 | + md_text = pymupdf4llm.to_markdown("input.pdf", ocr_function=my_ocr_function) |
| 69 | + |
| 70 | +Your plugin must accept at least the ``page`` parameter which is a PyMuPDF Page object. The other parameters are optional. The plugin must create (or extend) the text of the passed-in page object by simply inserting text (using any of PyMuPDF's text insertion methods). No return values expected. |
| 71 | + |
| 72 | +Be prepared to accept ``None`` or a PyMuPDF Pixmap object as the `pixmap` parameter, which is the rendered image of the page if provided. Parameters ``dpi`` and ``language`` are passed thru from the respective function parameters. |
| 73 | + |
| 74 | + |
| 75 | +Selecting Pages for OCR |
| 76 | +------------------------ |
| 77 | + |
| 78 | +Usually in document processing, the vast majority of pages contain extractable text and do not require OCR. PyMuPDF4LLM contains logic that analyzes the content based on a number of criteria including (but not restricted to) the following: |
| 79 | + |
| 80 | +* Presence of extractable and legible (!) text |
| 81 | +* Presence of images that appear to contain text |
| 82 | +* Presence of vector graphics that simulate text |
| 83 | +* Presence of text generated by previous OCR activities |
| 84 | + |
| 85 | +The OCR decision is internally based on the results of the following function:: |
| 86 | + |
| 87 | + from pymupdf4llm.helpers.utils import analyze_page |
| 88 | + |
| 89 | + analysis = analyze_page(page) |
| 90 | + |
| 91 | +The result ``analysis`` is a dictionary with the following keys and values. The area-related float values are computed as fractions of the total covered area. |
| 92 | + |
| 93 | +* "covered": pymupdf.Rect, page area covered by content |
| 94 | +* "img_joins": float, fraction of area of the joined images |
| 95 | +* "img_area": float, fraction of **sum** of image area sizes |
| 96 | +* "txt_joins": float, fraction of area of the joined text spans |
| 97 | +* "txt_area": float, fraction of **sum** of text span bbox area sizes |
| 98 | +* "vec_joins": float, fraction of area of the joined vector characters |
| 99 | +* "vec_area": float, fraction of **sum** of vector character area sizes |
| 100 | +* "chars_total": int, count of visible characters |
| 101 | +* "chars_bad": int, count of Replacement Unicode characters |
| 102 | +* "ocr_spans": int, count: text spans with ignored text (render mode 3) |
| 103 | +* "img_var": float, area-weighted image variance |
| 104 | +* "img_edges": float, area-weighted image edge energy |
| 105 | +* "vec_suspicious": int, minimum number of suspected vector-based glyphs |
| 106 | +* "reason": str, reason for the OCR decision, else ``None`` |
| 107 | +* "needs_ocr": bool, OCR decision (recommendation) |
| 108 | + |
| 109 | +The reason is one of the following values: |
| 110 | +* "chars_bad": more than 10% of all characters are illegible (i.e. Replacement Unicode characters) |
| 111 | +* "ocr_spans": there exist text spans created from previous OCR executions (render mode 3) |
| 112 | +* "vec_text": there exist suspected vector-based glyphs |
| 113 | +* "img_text": there exist images which probably contains recognizable text |
| 114 | + |
| 115 | +Based on this analysis, PyMuPDF4LLM will decide whether to invoke or skip OCR for a page. This is done to optimize processing time and resource usage by only performing OCR when it is likely to yield additional text content that cannot be extracted by other means. |
| 116 | + |
| 117 | +You can override this logic in the following ways: |
| 118 | + |
| 119 | +1. By setting `force_ocr=True` in the output functions (`to_markdown`, `to_text`, `to_json`). All pages will then be OCRed with the selected or provided OCR function regardless of their content. This will obviously have a massive impact on your execution time: expect several seconds duration per each page. |
| 120 | + |
| 121 | +2. Do as before, but add your own selection logic to the OCR plugin:: |
| 122 | + |
| 123 | + import pymupdf4llm |
| 124 | + from pymupdf4llm.ocr import rapidocr_api |
| 125 | + from pymupdf4llm.helpers.utils import analyze_page |
| 126 | + |
| 127 | + def my_ocr_function(page, pixmap=None, dpi=300, language="eng"): |
| 128 | + # analyze the page content and perform OCR only if necessary |
| 129 | + analysis = analyze_page(page) |
| 130 | + if not analysis["needs_ocr"]: |
| 131 | + return None |
| 132 | + |
| 133 | + # if OCR is recommended, you can decide differently based on your own insights, e.g. |
| 134 | + if analysis["reason"] == "ocr_spans": |
| 135 | + # we might want to accept previous OCR: |
| 136 | + return None |
| 137 | + |
| 138 | + rapidocr_api.exec_ocr(page, pixmap=pixmap, dpi=dpi, language=language) |
| 139 | + return None |
| 140 | + |
| 141 | + md_text = pymupdf4llm.to_markdown("input.pdf", force_ocr=True, ocr_function=my_ocr_function, ...) |
| 142 | + |
0 commit comments