├── .gitignore ├── CHANGES.md ├── LICENSE ├── README.md ├── examples ├── GUI │ ├── README.md │ └── browser-app.py ├── README.md └── country-capitals │ ├── README.md │ ├── country-capitals.py │ └── national-capitals.pdf ├── pdf4llm ├── README.md ├── pdf4llm │ └── __init__.py └── setup.py ├── pymupdf4llm ├── README.md ├── pymupdf4llm │ ├── __init__.py │ ├── helpers │ │ ├── get_text_lines.py │ │ ├── multi_column.py │ │ ├── progress.py │ │ └── pymupdf_rag.py │ └── llama │ │ └── pdf_markdown_reader.py └── setup.py └── tests └── pymupdf4llm └── llama_index └── test_pdf_markdown_reader.py /.gitignore: -------------------------------------------------------------------------------- 1 | _build 2 | build 3 | *.egg-info 4 | __pycache__ 5 | .pytest_cache -------------------------------------------------------------------------------- /CHANGES.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | ## Changes in version 0.0.24 4 | 5 | ### Fixes: 6 | 7 | * Fixing "UnboundLocalError" 8 | 9 | ### Other Changes: 10 | 11 | 12 | 13 | ## Changes in version 0.0.23 14 | 15 | ### Fixes: 16 | 17 | * [265](https://github.com/pymupdf/RAG/issues/265) - Code error correction 18 | * [263](https://github.com/pymupdf/RAG/issues/263) - Table Strategy = None raises error 19 | * [261](https://github.com/pymupdf/RAG/issues/261) - wrong markdown in latest pymupdf versions 20 | 21 | ### Other Changes: 22 | 23 | * Highspeed vector graphics count: if `graphics_limit` is specified, drawings are no longer extracted for counting purposes. 24 | 25 | 26 | ## Changes in version 0.0.22 27 | 28 | ### Fixes: 29 | 30 | * [251](https://github.com/pymupdf/RAG/issues/251) - Images a little larger than the page size are being ignored 31 | * [255](https://github.com/pymupdf/RAG/issues/255) - Single-row/column tables are skipped 32 | * [258](https://github.com/pymupdf/RAG/issues/258) - Pymupdf4llm to_markdown crashes on some documents 33 | 34 | ### Other Changes: 35 | 36 | * Added class `TocHeaders` as an alternative way for identifying headers. 37 | 38 | 39 | ## Changes in version 0.0.21 40 | 41 | ### Fixes: 42 | 43 | * [116](https://github.com/pymupdf/RAG/issues/116) - Handling Graphical Images & Superscripts 44 | 45 | ### Other Changes: 46 | 47 | 48 | ## Changes in version 0.0.20 49 | 50 | ### Fixes: 51 | 52 | * [171](https://github.com/pymupdf/RAG/issues/171) - Text rects overlap with tables and images that should be excluded. 53 | * [189](https://github.com/pymupdf/RAG/issues/189) - The position of the extracted image is incorrect 54 | * [238](https://github.com/pymupdf/RAG/issues/238) - When text is laid out around the picture, text extraction is missing. 55 | 56 | ### Other Changes: 57 | 58 | * Added **_new parameter_** `ignore_images`: (bool) optional. `True` will not consider images in any way. May be useful for pages where a plethora of images prevents meaningful layout analysis. Typical examples are PowerPoint slides and derived / similar pages. 59 | 60 | * Added **_new parameter_** `ignore_graphics`: (bool), optional. `True` will not consider graphics except for table detection. May be useful for pages where a plethora of vector graphics prevents meaningful layout analysis. Typical examples are PowerPoint slides and derived / similar pages. 61 | 62 | * Added **_new parameter_** to class `IdentifyHeaders`: Use `max_levels` (integer <= 6) to limit the generation of header tag levels. e.g. `headers = pymupdf4llm.IdentifyHeaders(doc, max_level=3)` ensures that only up to 3 header levels will ever be generated. Any text with a font size less than the value of `###` will be body text. In this case, the markdown generation itself would be coded as `md = pymupdf4llm.to_markdown(doc, hdr_info=headers, ...)`. 63 | 64 | * Changed parameter `table_strategy`: When specifying `None`, no effort to detecting tables will be made. This can be useful when tables are of no interest or known to not exist in a given file. This will speed up processing significantly. Be prepared to see more changes and extensions here. 65 | 66 | 67 | ## Changes in version 0.0.19 68 | 69 | ### Fixes: 70 | The following list includes fixes made in version 0.0.18 already. 71 | 72 | * [158](https://github.com/pymupdf/RAG/issues/158) - Very long titles when converting to markdown. 73 | * [155](https://github.com/pymupdf/RAG/issues/155) - Inconsistent image extraction from image-only PDFs 74 | * [161](https://github.com/pymupdf/RAG/issues/161) - force_text param ignored. 75 | * [162](https://github.com/pymupdf/RAG/issues/162) - to_markdown isn't outputting all the pages but get_text is. 76 | * [173](https://github.com/pymupdf/RAG/issues/173) - First column of table is repeated before the actual table. 77 | * [187](https://github.com/pymupdf/RAG/issues/187) - Unsolicited Text Particles 78 | * [188](https://github.com/pymupdf/RAG/issues/188) - Takes lot of time to convert into markdown. 79 | * [191](https://github.com/pymupdf/RAG/issues/191) - Extraction of text stops in the middle while working fine with PyMuPDF. 80 | * [212](https://github.com/pymupdf/RAG/issues/212) - In pymupdf4llm, if a page has multiple images, only 1 image per-page is extracted. 81 | * [213](https://github.com/pymupdf/RAG/issues/213) - Many ���� after converting when using pymupdf4llm 82 | * [215](https://github.com/pymupdf/RAG/issues/215) - Spending too much time on identifying text bboxes 83 | * [218](https://github.com/pymupdf/RAG/issues/218) - IndexError in get_raw_lines when processing PDFs with formulas 84 | * [225](https://github.com/pymupdf/RAG/issues/225) - Text with background missing from output. 85 | * [229](https://github.com/pymupdf/RAG/issues/229) - Duplicated Table Content on pymuPDF4LLM. 86 | 87 | 88 | ### Other Changes: 89 | 90 | * Added **_new parameter_** `filename`: (str), optional. Overwrites or sets the filename for saved images. Useful when the document is opened from memory. 91 | 92 | * Added **_new parameter_** `use_glyphs`: (bool), optional. Request to use the glyph number (if possible) of a character if the font has no back-translation to the original Unicode value. The default is `False` which causes � symbols to be rendered in these cases. 93 | 94 | * Added **_strike-out support_**: We now detect and render ~~striked-out text.~~ 95 | 96 | * Improved **_background color_** detection: We have introduced a simple background color detection mechanism: If a page shows an identical color in all four corners, we assume this to be the background color. Text and vector graphics with this color will be ignored as invisible. 97 | 98 | * Improved **_invisible text detection_**: Text with an alpha value of 0 is now ignored. 99 | 100 | * Improved **_fake-bold_** detection: Text mimicking bold appearance is now treated like standard bold text in most cases. 101 | 102 | * Header handling changes: 103 | - Detection now happens based on the **_largest font size_** of the line. 104 | - Uniformly rendered: All spans of a header line will now be rendered with the same appearance. 105 | 106 | * Changed handling of parameter `graphics_limit`: We previously ignored a page completely if the vector graphics count exceeded the limit. We now only ignore vector graphics if their count **_outside table boundary boxes_** is too large. This should only suppress vector graphics on the page, while keeping images, text and table content extractable. 107 | 108 | * Changed the `margins` default to 0. The previous default `(0, 50, 0, 50)` ignored 50 points at the top and bottom of pages. This has turned out to cause confusion in too many cases. 109 | 110 | 111 | ## Changes in version 0.0.17 112 | 113 | ### Fixes: 114 | 115 | 116 | * [147](https://github.com/pymupdf/RAG/issues/147) - Error when page contains nothing but a table. 117 | * [81](https://github.com/pymupdf/RAG/issues/81) - Issues with bullet points in PDFs. 118 | * [78](https://github.com/pymupdf/RAG/issues/78) - multi column pdf file text extraction. 119 | 120 | 121 | ## Changes in version 0.0.15 122 | 123 | ### Fixes: 124 | 125 | 126 | * [138](https://github.com/pymupdf/RAG/issues/138) - Table is not extracted and some text order was wrong. 127 | * [135](https://github.com/pymupdf/RAG/issues/135) - Problem with multiple columns in simple text. 128 | * [134](https://github.com/pymupdf/RAG/issues/134) - Exclude images based on size threshold parameter. 129 | * [132](https://github.com/pymupdf/RAG/issues/132) - Optionally embed images as base64 string. 130 | * [128](https://github.com/pymupdf/RAG/issues/128) - Enhanced image embedding format. 131 | 132 | 133 | ### Improvements 134 | 135 | * New parameter `embed_images` (bool) **embeds** images and vector graphics in the markdown text as base64-encoded strings. Ignores `write_images` and `image_path` parameters. 136 | * New parameter `image_size_limit` which is a float between 0 and 1, default is 0.05 (5%). Causes images to be ignored if their width or height values are smaller than the corresponding fraction of the page's width or height. 137 | * The algorithm has been improved which determins the sequence of the text rectangles on multi-column pages. 138 | * Change of the header identification algorithm: If more than six header levels are required for a document, then all text with a font size larger than body text is assumed to be a header of level 6 (i.e. HTML "h6" = "###### "). 139 | 140 | 141 | ## Changes in version 0.0.13 142 | 143 | 144 | ### Fixes 145 | 146 | * [112](https://github.com/pymupdf/RAG/issues/112) - Invalid bandwriter header dimensions/setup. 147 | 148 | 149 | ### Improvements 150 | 151 | * New parameter `ignore_code` suppresses special formatting of text in mono-spaced fonts. 152 | * New parameter `extract_words` enforces `page_chunks=True` and adds a "words" list to each page dictionary. 153 | 154 | 155 | ## Changes in version 0.0.11 156 | 157 | 158 | ### Fixes 159 | 160 | * [90](https://github.com/pymupdf/RAG/issues/90) - 'Quad' object has no attribute 'tl'. 161 | * [88](https://github.com/pymupdf/RAG/issues/88) - Bug in `is_significant` function. 162 | 163 | 164 | ### Improvements 165 | 166 | * Extended the list of known bullet point characters. 167 | 168 | 169 | ## Changes in version 0.0.10 170 | 171 | 172 | ### Fixes 173 | 174 | * [73](https://github.com/pymupdf/RAG/issues/73) - bug in `to_markdown` internal function. 175 | * [74](https://github.com/pymupdf/RAG/issues/74) - minimum area for images & vector graphics. 176 | * [75](https://github.com/pymupdf/RAG/issues/75) - Poor Markdown Generation for Particular PDF. 177 | * [76](https://github.com/pymupdf/RAG/issues/76) - suggestion on useful api parameters. 178 | 179 | 180 | ### Improvements 181 | 182 | * Improved recognition of "insignificant" vector graphics. Graphics like text highlights or borders will be ignored. 183 | * The format of saved images can now be controlled via new parameter `image_format`. 184 | * Images can be stored in a specific folder via the new parameter `image_path`. 185 | * Images are **not stored if contained** in another image on same page. 186 | * Images are **not stored if too small:** if width or height are less than 5% of corresponding page dimension. 187 | * All text is always written. If `write_images=True`, text on images / graphics can be suppressed by setting `force_text=False`. 188 | 189 | 190 | ## Changes in version 0.0.9 191 | 192 | 193 | ### Fixes 194 | 195 | * [71](https://github.com/pymupdf/RAG/issues/71) - Unexpected results in pymupdf4llm but pymupdf works. 196 | * [68](https://github.com/pymupdf/RAG/issues/68) - Issue with text extraction near footer of page. 197 | 198 | 199 | ### Improvements 200 | 201 | * Improved identification of scattered text span particles. This should address most issues with out-of-sequence situations. 202 | * We now correctly process rotated pages (see [issue 68](https://github.com/pymupdf/RAG/issues/68)). 203 | 204 | 205 | ## Changes in version 0.0.8 206 | 207 | 208 | ### Fixes 209 | 210 | 211 | * [65](https://github.com/pymupdf/RAG/issues/65) - Fix typo in `pymupdf_rag.py`. 212 | 213 | 214 | ## Changes in version 0.0.7 215 | 216 | 217 | ### Fixes 218 | 219 | 220 | * [54](https://github.com/pymupdf/RAG/issues/54) - Mistakes in orchestrating sentences. Additional fix: text extraction no longer uses the `TEXT_DEHYPHENATE` flag bit. 221 | 222 | ### Improvements 223 | 224 | * Improved the algorithm dealing with vector graphics. Vector graphics are now more reliably classified as irrelevant: We now detect when "strokes" only exist in the neighborhood of the graphics boundary box border itself. This is quite often the case for code snippets. 225 | 226 | ## Changes in version 0.0.6 227 | 228 | 229 | ### Fixes 230 | 231 | 232 | * [55](https://github.com/pymupdf/RAG/issues/55) - Bug in helpers/multi_column.py - IndexError: list index out of range. 233 | * [54](https://github.com/pymupdf/RAG/issues/54) - Mistakes in orchestrating sentences. 234 | * [52](https://github.com/pymupdf/RAG/issues/52) - Chunking of text files. 235 | * Partial fix for [41](https://github.com/pymupdf/RAG/issues/41) / [40](https://github.com/pymupdf/RAG/issues/40) - Improved page column detection, but still no silver bullet for overly complex page layouts. 236 | 237 | ### Improvements 238 | 239 | * New parameter `dpi` to specify the resolution of images. 240 | * New parameters `page_width` / `page_height` for easily processing reflowable documents (Text, Office, e-books). 241 | * New parameter `graphics_limit` to avoid spending runtimes for value-less content. 242 | * New parameter `table_strategy` to directly control the table detection strategy. 243 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Using PyMuPDF in an RAG (Retrieval-Augmented Generation) Chatbot Environment 2 | 3 | This repository contains examples showing how PyMuPDF can be used as a data feed for RAG-based chatbots. 4 | 5 | Examples include scripts that start chatbots - either as simple CLI programs in REPL mode or browser-based GUIs. 6 | Chatbot scripts follow this general structure: 7 | 8 | 1. **Extract Text**: Use PyMuPDF to extract text from one or more pages from one or more PDFs. Depending on the specific requirement this may be all text or only text contained in tables, the Table of Contents, etc. 9 | This will generally be implemented as one or more Python functions called by any of the following events - which implement the actual chatbot functionality. 10 | 2. **Indexing the Extracted Text**: Index the extracted text for efficient retrieval. This index will act as the knowledge base for the chatbot. 11 | 3. **Query Processing**: When a user asks a question, process the query to determine the key information needed for a response. 12 | 4. **Retrieving Relevant Information**: Search your indexed knowledge base for the most relevant pieces of information related to the user's query. 13 | 5. **Generating a Response**: Use a generative model to generate a response based on the retrieved information. 14 | 15 | # Installation 16 | 17 | The Python package on PyPI [pymupdf4llm](https://pypi.org/project/pymupdf4llm/) (there also is an alias [pdf4llm](https://pypi.org/project/pdf4llm/)) is capable of converting PDF pages into **_text strings in Markdown format_** (GitHub compatible). This includes **standard text** as well as **table-based text** in a consistent and integrated view - a feature particularly important in RAG settings. 18 | 19 | ```bash 20 | $ pip install -U pymupdf4llm 21 | ``` 22 | 23 | > This command will automatically install [PyMuPDF](https://github.com/pymupdf/PyMuPDF) if required. 24 | 25 | Then in your script do 26 | 27 | ```python 28 | import pymupdf4llm 29 | 30 | md_text = pymupdf4llm.to_markdown("input.pdf") 31 | 32 | # now work with the markdown text, e.g. store as a UTF8-encoded file 33 | import pathlib 34 | pathlib.Path("output.md").write_bytes(md_text.encode()) 35 | ``` 36 | 37 | Instead of the filename string as above, one can also provide a PyMuPDF `Document`. By default, all pages in the PDF will be processed. If desired, the parameter `pages=[...]` can be used to provide a list of zero-based page numbers to consider. 38 | 39 | Markdown text creation now also processes **multi-column pages**. 40 | 41 | To create small **chunks of text** - as opposed to generating one large string for the whole document - the new (v0.0.2) option `page_chunks=True` can be used. The result of `.to_markdown("input.pdf", page_chunks=True)` will be a list of Python dictionaries, one for each page. 42 | 43 | Also new in version 0.0.2 is the optional **extraction of images** and vector graphics: use of parameter `write_images=True`. The will store PNG images in the document's folder, and the Markdown text will appropriately refer to them. The images are named like `"input.pdf-page_number-index.png"`. 44 | 45 | # Documentation and API 46 | 47 | [Documentation](https://pymupdf.readthedocs.io/en/latest/pymupdf4llm/index.html) 48 | 49 | [API](https://pymupdf.readthedocs.io/en/latest/pymupdf4llm/api.html#pymupdf4llm-api) 50 | 51 | # Document Support 52 | 53 | While PDF is by far the most important document format worldwide, it is worthwhile mentioning that all examples and helper scripts work in the same way and **_without change_** for [all supported file types](https://pymupdf.readthedocs.io/en/latest/how-to-open-a-file.html#supported-file-types). 54 | 55 | So for an XPS document or an eBook, simply provide the filename for instance as `"input.mobi"` and everything else will work as before. 56 | 57 | 58 | # About PyMuPDF 59 | **PyMuPDF** adds **Python** bindings and abstractions to [MuPDF](https://mupdf.com/), a lightweight **PDF**, **XPS**, and **eBook** viewer, renderer, and toolkit. Both **PyMuPDF** and **MuPDF** are maintained and developed by [Artifex Software, Inc](https://artifex.com). 60 | 61 | PyMuPDF's homepage is located on [GitHub](https://github.com/pymupdf/PyMuPDF). 62 | 63 | # Community 64 | Join us on **Discord** here: [#pymupdf](https://discord.gg/TSpYGBW4eq). 65 | 66 | # License and Copyright 67 | **PyMuPDF** is available under [open-source AGPL](https://www.gnu.org/licenses/agpl-3.0.html) and commercial license agreements. If you determine you cannot meet the requirements of the **AGPL**, please contact [Artifex](https://artifex.com/contact/pymupdf-inquiry.php) for more information regarding a commercial license. 68 | 69 | -------------------------------------------------------------------------------- /examples/GUI/README.md: -------------------------------------------------------------------------------- 1 | # Example of a Browser Application using Langchain and PyMuPDF 2 | 3 | ## Installation 4 | Please download this folder to your machine. 5 | 6 | Open a terminal and ensure that the required packages are on your system by executing the following commands. We also recommend to always update pip. 7 | 8 | ```bash 9 | pip install -U pip 10 | pip install -U langchain 11 | pip install -U langchain-community 12 | pip install -U langchain-openai 13 | pip install -U gradio 14 | pip install -U PyMuPDF 15 | ``` 16 | 17 | ## Launching the Application 18 | Launch the application by executing the following command in a terminal opened in the downloaded folder: 19 | 20 | ```bash 21 | python browser-app.py 22 | ``` 23 | 24 | After a few seconds the application will display instructions on how to start a session in your browser. -------------------------------------------------------------------------------- /examples/GUI/browser-app.py: -------------------------------------------------------------------------------- 1 | """ 2 | This code uses the PyMuPDF package. 3 | 4 | PyMuPDF is AGPL licensed, please refer to: 5 | https://pymupdf.readthedocs.io/en/latest/about.html#license-and-copyright 6 | """ 7 | 8 | """ 9 | Code below is based on an implementation by Sunil Kumar Dash: 10 | 11 | MIT License 12 | 13 | Copyright (c) 2023 Sunil Kumar Dash 14 | 15 | Permission is hereby granted, free of charge, to any person obtaining a copy 16 | of this software and associated documentation files (the "Software"), to deal 17 | in the Software without restriction, including without limitation the rights 18 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 19 | copies of the Software, and to permit persons to whom the Software is 20 | furnished to do so, subject to the following conditions: 21 | 22 | The above copyright notice and this permission notice shall be included in all 23 | copies or substantial portions of the Software. 24 | 25 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 26 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 27 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 28 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 29 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 30 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 31 | SOFTWARE. 32 | """ 33 | 34 | from typing import Any 35 | import gradio as gr 36 | from langchain_openai import OpenAIEmbeddings 37 | from langchain_community.vectorstores import Chroma 38 | 39 | from langchain.chains import ConversationalRetrievalChain 40 | from langchain_openai import ChatOpenAI 41 | 42 | from langchain_community.document_loaders import PyMuPDFLoader 43 | 44 | import pymupdf 45 | from PIL import Image 46 | import os 47 | import re 48 | import uuid 49 | 50 | enable_box = gr.Textbox( 51 | value=None, placeholder="Upload your OpenAI API key", interactive=True 52 | ) 53 | disable_box = gr.Textbox(value="OpenAI API key is set", interactive=False) 54 | 55 | 56 | def set_apikey(api_key: str): 57 | print("API Key set") 58 | app.OPENAI_API_KEY = api_key 59 | return disable_box 60 | 61 | 62 | def enable_api_box(): 63 | return enable_box 64 | 65 | 66 | def add_text(history, text: str): 67 | if not text: 68 | raise gr.Error("enter text") 69 | history = history + [(text, "")] 70 | return history 71 | 72 | 73 | class my_app: 74 | def __init__(self, OPENAI_API_KEY: str = None) -> None: 75 | self.OPENAI_API_KEY: str = OPENAI_API_KEY 76 | self.chain = None 77 | self.chat_history: list = [] 78 | self.N: int = 0 79 | self.count: int = 0 80 | 81 | def __call__(self, file: str) -> Any: 82 | if self.count == 0: 83 | self.chain = self.build_chain(file) 84 | self.count += 1 85 | return self.chain 86 | 87 | def process_file(self, file: str): 88 | loader = PyMuPDFLoader(file.name) 89 | documents = loader.load() 90 | pattern = r"/([^/]+)$" 91 | match = re.search(pattern, file.name) 92 | try: 93 | file_name = match.group(1) 94 | except: 95 | file_name = os.path.basename(file) 96 | 97 | return documents, file_name 98 | 99 | def build_chain(self, file: str): 100 | documents, file_name = self.process_file(file) 101 | # Load embeddings model 102 | embeddings = OpenAIEmbeddings(openai_api_key=self.OPENAI_API_KEY) 103 | pdfsearch = Chroma.from_documents( 104 | documents, 105 | embeddings, 106 | collection_name=file_name, 107 | ) 108 | chain = ConversationalRetrievalChain.from_llm( 109 | ChatOpenAI(temperature=0.0, openai_api_key=self.OPENAI_API_KEY), 110 | retriever=pdfsearch.as_retriever(search_kwargs={"k": 1}), 111 | return_source_documents=True, 112 | ) 113 | return chain 114 | 115 | 116 | def get_response(history, query, file): 117 | if not file: 118 | raise gr.Error(message="Upload a PDF") 119 | chain = app(file) 120 | result = chain( 121 | {"question": query, "chat_history": app.chat_history}, return_only_outputs=True 122 | ) 123 | app.chat_history += [(query, result["answer"])] 124 | app.N = list(result["source_documents"][0])[1][1]["page"] 125 | for char in result["answer"]: 126 | history[-1][-1] += char 127 | yield history, "" 128 | 129 | 130 | def render_file(file): 131 | doc = pymupdf.open(file.name) 132 | page = doc[app.N] 133 | # Render the page as a PNG image with a resolution of 150 DPI 134 | pix = page.get_pixmap(dpi=150) 135 | image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) 136 | return image 137 | 138 | 139 | def purge_chat_and_render_first(file): 140 | print("purge_chat_and_render_first") 141 | # Purges the previous chat session so that the bot has no concept of previous documents 142 | app.chat_history = [] 143 | app.count = 0 144 | 145 | # Use PyMuPDF to render the first page of the uploaded document 146 | doc = pymupdf.open(file.name) 147 | page = doc[0] 148 | # Render the page as a PNG image with a resolution of 150 DPI 149 | pix = page.get_pixmap(dpi=150) 150 | image = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) 151 | return image, [] 152 | 153 | app = my_app() 154 | 155 | with gr.Blocks() as demo: 156 | with gr.Column(): 157 | with gr.Row(): 158 | 159 | with gr.Column(scale=1): 160 | api_key = gr.Textbox( 161 | placeholder="Enter OpenAI API key and hit ", 162 | show_label=False, 163 | interactive=True 164 | ) 165 | 166 | with gr.Row(): 167 | with gr.Column(scale=2): 168 | with gr.Row(): 169 | chatbot = gr.Chatbot(value=[], elem_id="chatbot") 170 | with gr.Row(): 171 | txt = gr.Textbox( 172 | show_label=False, 173 | placeholder="Enter text and press submit", 174 | scale=2 175 | ) 176 | submit_btn = gr.Button("submit", scale=1) 177 | 178 | with gr.Column(scale=1): 179 | with gr.Row(): 180 | show_img = gr.Image(label="Upload PDF") 181 | with gr.Row(): 182 | btn = gr.UploadButton("📁 upload a PDF", file_types=[".pdf"]) 183 | 184 | api_key.submit( 185 | fn=set_apikey, 186 | inputs=[api_key], 187 | outputs=[ 188 | api_key, 189 | ], 190 | ) 191 | 192 | btn.upload( 193 | fn=purge_chat_and_render_first, 194 | inputs=[btn], 195 | outputs=[show_img, chatbot], 196 | ) 197 | 198 | submit_btn.click( 199 | fn=add_text, 200 | inputs=[chatbot, txt], 201 | outputs=[ 202 | chatbot, 203 | ], 204 | queue=False, 205 | ).success( 206 | fn=get_response, inputs=[chatbot, txt, btn], outputs=[chatbot, txt] 207 | ).success( 208 | fn=render_file, inputs=[btn], outputs=[show_img] 209 | ) 210 | 211 | demo.queue() 212 | demo.launch() 213 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Examples 2 | 3 | These examples are used to support tutorial blog posts as follows: 4 | 5 | 6 | ## country-capitals 7 | 8 | See: [Creating a RAG Chatbot with ChatGPT and PyMuPDF](https://artifex.com/blog/creating-a-rag-chatbot-with-chatgpt-and-pymupdf) 9 | 10 | 11 | 12 | ## GUI 13 | 14 | See: [Building a RAG Chatbot GUI with the ChatGPT API and PyMuPDF](https://artifex.com/blog/building-a-rag-chatbot-gui-with-the-chatgpt-api-and-pymupdf) 15 | 16 | -------------------------------------------------------------------------------- /examples/country-capitals/README.md: -------------------------------------------------------------------------------- 1 | # Demonstration of an RAG Chatbot Using PyMuPDF 2 | 3 | This script starts an OpenAI RAG (Retrieval Augmented Generation) chatbot. 4 | 5 | The data fed into to chatbot client are tabular data extracted from a 6-page 6 | PDF. 7 | 8 | ## How it Works 9 | The content of the data is a list of almost 200 countries, their capital 10 | cities, city population and its percentage of the country's total 11 | population. 12 | 13 | The script is started like any Python script and without parameters. Upon 14 | start, a function is invoked which calls PyMuPDF to read the PDF, extract the 15 | table data and return a CSV-like string containing the table's content. 16 | 17 | After the chatbot has finished interpreting the data, the user may start asking 18 | questions via Read-Evaluate-Print loop (REPL). 19 | 20 | ## Information Retrieved for Responses 21 | Remarkably, the chatbot "realizes" the geographic and demographic context 22 | established by the PDF's data. This enables it to access the right knowledge 23 | resources on the internet for completing the information required to answer the user 24 | questions. 25 | 26 | For example, it will understand it has to look up **cities** and **countries** when being 27 | asked for words that do not occur in the PDF. 28 | 29 | For instance, the country 30 | **Liechtenstein** is not in the PDF, but asking for it or its capital city, 31 | Vaduz will deliver correct information, including population numbers or 32 | short abstracts of city and country. 33 | 34 | ## Getting Started 35 | 36 | Execute all of the following commands in a terminal: 37 | 38 | ```bash 39 | python pip install -U pip 40 | python pip install -U pymupdf 41 | python pip install -U openai 42 | ``` 43 | 44 | Visit https://github.com/openai/openai-cookbook to learn how to register on 45 | OpenAI's website and request an API key. 46 | 47 | Copy this folder to your machine, then edit the script, type in your API key in this line `API_KEY = "your OpenAI API key goes here"` and save. Then open a terminal in the folder and execute the following command: 48 | 49 | ```bash 50 | python country-capitals.py 51 | ``` 52 | 53 | After a few seconds, the following should be displayed. 54 | 55 | ## Example Session 56 | Please note how the chatbot searches the internet for information required to answer the question whenever the loaded text is insufficient. 57 | 58 | ```bash 59 | Loaded 204 table rows from file 'national-capitals.pdf'. 60 | 61 | Ready - ask questions or exit with q/Q: 62 | ==> what is the capital of Germany? 63 | Response: 64 | 65 | The capital of Germany is Berlin. 66 | ---------- 67 | ==> Berlin's population, absolute and relative? 68 | Response: 69 | 70 | Berlin's population as of 2021 is 3,677,472. This makes up about 4.4% of the total population of Germany. 71 | ---------- 72 | ==> is Vaduz part of the text, and if not, do you know about it? 73 | Response: 74 | 75 | No, Vaduz is not part of the text. It is the capital of Liechtenstein. 76 | ---------- 77 | ==> the 10 smallest capital cities of the world? 78 | Response: 79 | 80 | 1. Vatican City (Vatican City) - 0.44 km² 81 | 2. Ngerulmud (Palau) - 0.57 km² 82 | 3. San Marino (San Marino) - 7.09 km² 83 | 4. Monaco (Monaco) - 2.02 km² 84 | 5. Gibraltar (Gibraltar) - 6 km² 85 | 6. Tuvalu (Funafuti) - 2.18 km² 86 | 7. Nauru (Yaren) - 21 km² 87 | 8. Malta (Valletta) - 0.8 km² 88 | 9. Andorra la Vella (Andorra) - 12.86 km² 89 | 10. 90 | ---------- 91 | ==> the 10 smallest capital cities in terms of population? 92 | Response: 93 | 94 | 1. Vatican City (Vatican City) - 453 95 | 2. Ngerulmud (Palau) - 271 96 | 3. Adamstown (Pitcairn Islands) - 40 97 | 4. Funafuti (Tuvalu) - 6,320 98 | 5. Alofi (Niue) - 597 99 | 6. Yaren (Nauru) - 747 100 | 7. South Tarawa (Kiribati) - 50,182 101 | 8. Stanley (Falkland Islands) - 2,460 102 | 9. Flying Fish Cove (Christmas Island) - 1,599 103 | 10. Roseau (Dominica) - 14,725 104 | ---------- 105 | ``` 106 | -------------------------------------------------------------------------------- /examples/country-capitals/country-capitals.py: -------------------------------------------------------------------------------- 1 | """ 2 | This script implements an RAG chatbot using OpenAI and PyMuPDF. 3 | 4 | It is intended as a simple example for demonstration purposes primarily. 5 | 6 | When the chatbot is started, it will call PyMuPDF to read a PDF that contains 7 | a list of countries, their capital cities and city populations. 8 | 9 | This call to PyMuPDF will happen only once. Thereafter, the user can start 10 | asking questions in a Read-Evaluate-Prompt loop - or end the session. 11 | 12 | Although the data in the PDF are of course limited, the user may ask questions 13 | that require accessing sources present in the internet and may refer to 14 | almost arbitrary geographic or demographic information. 15 | 16 | The chatbot is capable of integrating disparate information sources delivering 17 | a meaningful response. 18 | """ 19 | 20 | import pymupdf 21 | import textwrap 22 | from openai import OpenAI 23 | 24 | # Example for reading the OpenAI API key 25 | API_KEY = "your OpenAI API key goes here" 26 | 27 | # create an OpenAI client using the API key 28 | client = OpenAI(api_key=API_KEY) 29 | 30 | 31 | def extract_text_from_pdf(pdf_path): 32 | """Read table content only of all pages in the document. 33 | 34 | Chatbots typically have limitations on the amount of data that can 35 | can be passed in (number of tokens). 36 | 37 | We therefore only extract information on the PDF's pages that are 38 | contained in tables. 39 | As we even know that the PDF actually contains ONE logical table 40 | that has been segmented for reporting purposes, our approach 41 | is the following: 42 | * The cell contents of each table row are joined into one string 43 | separated by ";". 44 | * If table segment on the first page also has an external header row, 45 | join the column names separated by ";". Also ignore any subsequent 46 | table row that equals the header string. This deals with table 47 | header repeat situations. 48 | """ 49 | # open document 50 | doc = pymupdf.open(pdf_path) 51 | 52 | text = "" # we will return this string 53 | row_count = 0 # counts table rows 54 | header = "" # overall table header: output this only once! 55 | 56 | # iterate over the pages 57 | for page in doc: 58 | # only read the table rows on each page, ignore other content 59 | tables = page.find_tables() # a "TableFinder" object 60 | for table in tables: 61 | 62 | # on first page extract external column names if present 63 | if page.number == 0 and table.header.external: 64 | # build the overall table header string 65 | # technical note: incomplete / complex tables may have 66 | # "None" in some header cells. Just use empty string then. 67 | header = ( 68 | ";".join( 69 | [ 70 | name if name is not None else "" 71 | for name in table.header.names 72 | ] 73 | ) 74 | + "\n" 75 | ) 76 | text += header 77 | row_count += 1 # increase row counter 78 | 79 | # output the table body 80 | for row in table.extract(): # iterate over the table rows 81 | 82 | # again replace any "None" in cells by an empty string 83 | row_text = ( 84 | ";".join([cell if cell is not None else "" for cell in row]) + "\n" 85 | ) 86 | if row_text != header: # omit duplicates of header row 87 | text += row_text 88 | row_count += 1 # increase row counter 89 | doc.close() # close document 90 | print(f"Loaded {row_count} table rows from file '{doc.name}'.\n") 91 | return text 92 | 93 | 94 | # use model "gpt-3.5-turbo-instruct" for text 95 | def generate_response_with_chatgpt(prompt): 96 | response = client.completions.create( 97 | model="gpt-3.5-turbo-instruct", # Choose appropriate model 98 | prompt=prompt, 99 | max_tokens=150, 100 | n=1, 101 | stop=None, 102 | temperature=0.7, 103 | ) 104 | return response.choices[0].text.strip() 105 | 106 | 107 | filename = "national-capitals.pdf" 108 | pdf_text = extract_text_from_pdf(filename) 109 | 110 | print("Ready - ask questions or exit with q/Q:") 111 | while True: 112 | user_query = input("==> ") 113 | if user_query.lower().strip() == "q": 114 | break 115 | prompt = pdf_text + "\n\n" + user_query 116 | response = generate_response_with_chatgpt(prompt) 117 | print("Response:\n") 118 | for line in textwrap.wrap(response, width=70): 119 | print(line) 120 | print("-" * 10) 121 | -------------------------------------------------------------------------------- /examples/country-capitals/national-capitals.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pymupdf/RAG/1c796f4d72c6582491430de321823c63412ddb26/examples/country-capitals/national-capitals.pdf -------------------------------------------------------------------------------- /pdf4llm/README.md: -------------------------------------------------------------------------------- 1 | # Using PyMuPDF as Data Feeder in LLM / RAG Applications 2 | 3 | This package converts the pages of a PDF to text in Markdown format using [PyMuPDF](https://pypi.org/project/PyMuPDF/). 4 | 5 | Standard text and tables are detected, brought in the right reading sequence and then together converted to GitHub-compatible Markdown text. 6 | 7 | Header lines are identified via the font size and appropriately prefixed with one or more '#' tags. 8 | 9 | Bold, italic, mono-spaced text and code blocks are detected and formatted accordingly. Similar applies to ordered and unordered lists. 10 | 11 | By default, all document pages are processed. If desired, a subset of pages can be specified by providing a list of 0-based page numbers. 12 | 13 | 14 | # Installation 15 | 16 | ```bash 17 | $ pip install -U pdf4llm 18 | ``` 19 | 20 | > This command will automatically install [PyMuPDF](https://github.com/pymupdf/PyMuPDF) if required. 21 | 22 | Then in your script do: 23 | 24 | ```python 25 | import pdf4llm 26 | 27 | md_text = pdf4llm.to_markdown("input.pdf") 28 | 29 | # now work with the markdown text, e.g. store as a UTF8-encoded file 30 | import pathlib 31 | pathlib.Path("output.md").write_bytes(md_text.encode()) 32 | ``` 33 | 34 | Instead of the filename string as above, one can also provide a PyMuPDF `Document`. By default, all pages in the PDF will be processed. If desired, the parameter `pages=[...]` can be used to provide a list of zero-based page numbers to consider. 35 | 36 | **New features as of v0.0.8:** 37 | 38 | * Support for pages with **_multiple text columns_**. 39 | * Support for **_image and vector graphics extraction_**: 40 | 41 | 1. Specify `pdf4llm.to_markdown("input.pdf", write_images=True)`. Default is `False`. 42 | 2. Each image or vector graphic on the page will be extracted and stored as a PNG image named `"input.pdf-pno-index.png"` in the folder of `"input.pdf"`. Where `pno` is the 0-based page number and `index` is some sequence number. 43 | 3. The image files will have width and height equal to the values on the page. 44 | 4. Any text contained in the images or graphics will not be extracted, but become visible as image parts. 45 | 46 | * Support for **page chunks**: Instead of returning one large string for the whole document, a list of dictionaries can be generated: one for each page. Specify `data = pdf4llm.to_markdown("input.pdf", page_chunks=True)`. Then, for instance the first item, `data[0]` will contain a dictionary for the first page with the text and some metadata. 47 | 48 | * As a first example for directly supporting LLM / RAG consumers, this version can output **LlamaIndex documents**: 49 | 50 | ```python 51 | import pdf4llm 52 | 53 | md_read = pdf4llm.LlamaMarkdownReader() 54 | data = md_read.load_data("input.pdf") 55 | 56 | # The result 'data' is of type List[LlamaIndexDocument] 57 | # Every list item contains metadata and the markdown text of 1 page. 58 | ``` 59 | 60 | * A LlamaIndex document essentially corresponds to Python dictionary, where the markdown text of the page is one of the dictionary values. For instance the text of the first page is the the value of `data[0].to_dict().["text"]`. 61 | * For details, please consult LlamaIndex documentation. 62 | * Upon creation of the `LlamaMarkdownReader` all necessary LlamaIndex-related imports are executed. Required related package installations must have been done independently and will not be checked during pdf4llm installation. -------------------------------------------------------------------------------- /pdf4llm/pdf4llm/__init__.py: -------------------------------------------------------------------------------- 1 | import pymupdf4llm 2 | from pymupdf4llm import * 3 | 4 | 5 | __version__ = pymupdf4llm.__version__ 6 | version = pymupdf4llm.version 7 | version_tuple = pymupdf4llm.version_tuple 8 | 9 | 10 | def LlamaMarkdownReader(*args, **kwargs): 11 | from pymupdf4llm.llama import pdf_markdown_reader 12 | 13 | return pymupdf4llm.llama.pdf_markdown_reader.PDFMarkdownReader(*args, **kwargs) 14 | -------------------------------------------------------------------------------- /pdf4llm/setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import setuptools 4 | 5 | setup_py_cwd = os.path.dirname(__file__) 6 | with open(os.path.join(setup_py_cwd, "README.md"), encoding="utf-8") as f: 7 | readme = f.read() 8 | 9 | classifiers = [ 10 | "Development Status :: 5 - Production/Stable", 11 | "Environment :: Console", 12 | "Intended Audience :: Developers", 13 | "Programming Language :: Python :: 3", 14 | "Topic :: Utilities", 15 | ] 16 | requires = ["pymupdf4llm==0.0.24"] 17 | 18 | setuptools.setup( 19 | name="pdf4llm", 20 | version="0.0.24", 21 | author="Artifex", 22 | author_email="support@artifex.com", 23 | description="PyMuPDF Utilities for LLM/RAG", 24 | packages=setuptools.find_packages(), 25 | long_description=readme, 26 | long_description_content_type="text/markdown", 27 | install_requires=requires, 28 | license="GNU AFFERO GPL 3.0", 29 | url="https://github.com/pymupdf/RAG", 30 | classifiers=classifiers, 31 | package_data={ 32 | "pdf4llm": ["LICENSE"], 33 | }, 34 | project_urls={ 35 | "Documentation": "https://pymupdf.readthedocs.io/", 36 | "Source": "https://github.com/pymupdf/RAG/tree/main/pdf4llm/pdf4llm", 37 | "Tracker": "https://github.com/pymupdf/RAG/issues", 38 | "Changelog": "https://github.com/pymupdf/RAG/blob/main/CHANGES.md", 39 | }, 40 | ) 41 | -------------------------------------------------------------------------------- /pymupdf4llm/README.md: -------------------------------------------------------------------------------- 1 | # Using PyMuPDF as Data Feeder in LLM / RAG Applications 2 | 3 | This package converts the pages of a PDF to text in Markdown format using [PyMuPDF](https://pypi.org/project/PyMuPDF/). 4 | 5 | Standard text and tables are detected, brought in the right reading sequence and then together converted to GitHub-compatible Markdown text. 6 | 7 | Header lines are identified via the font size and appropriately prefixed with one or more '#' tags. 8 | 9 | Bold, italic, mono-spaced text and code blocks are detected and formatted accordingly. Similar applies to ordered and unordered lists. 10 | 11 | By default, all document pages are processed. If desired, a subset of pages can be specified by providing a list of 0-based page numbers. 12 | 13 | 14 | # Installation 15 | 16 | ```bash 17 | $ pip install -U pymupdf4llm 18 | ``` 19 | 20 | > This command will automatically install [PyMuPDF](https://github.com/pymupdf/PyMuPDF) if required. 21 | 22 | Then in your script do: 23 | 24 | ```python 25 | import pymupdf4llm 26 | 27 | md_text = pymupdf4llm.to_markdown("input.pdf") 28 | 29 | # now work with the markdown text, e.g. store as a UTF8-encoded file 30 | import pathlib 31 | pathlib.Path("output.md").write_bytes(md_text.encode()) 32 | ``` 33 | 34 | Instead of the filename string as above, one can also provide a PyMuPDF `Document`. By default, all pages in the PDF will be processed. If desired, the parameter `pages=[...]` can be used to provide a list of zero-based page numbers to consider. 35 | 36 | **Feature Overview:** 37 | 38 | * Support for pages with **_multiple text columns_**. 39 | * Support for **_image and vector graphics extraction_**: 40 | 41 | 1. Specify `pymupdf4llm.to_markdown("input.pdf", write_images=True)`. Default is `False`. 42 | 2. Each image or vector graphic on the page will be extracted and stored as an image named `"input.pdf-pno-index.extension"` in a folder of your choice. The image `extension` can be chosen to represent a PyMuPDF-supported image format (for instance "png" or "jpg"), `pno` is the 0-based page number and `index` is some sequence number. 43 | 3. The image files will have width and height equal to the values on the page. The desired resolution can be chosen via parameter `dpi` (default: `dpi=150`). 44 | 4. Any text contained in the images or graphics will be extracted and **also become visible as part of the generated image**. This behavior can be changed via `force_text=False` (text only apears as part of the image). 45 | 46 | * Support for **page chunks**: Instead of returning one large string for the whole document, a list of dictionaries can be generated: one for each page. Specify `data = pymupdf4llm.to_markdown("input.pdf", page_chunks=True)`. Then, for instance the first item, `data[0]` will contain a dictionary for the first page with the text and some metadata. 47 | 48 | * As a first example for directly supporting LLM / RAG consumers, this version can output **LlamaIndex documents**: 49 | 50 | ```python 51 | import pymupdf4llm 52 | 53 | md_read = pymupdf4llm.LlamaMarkdownReader() 54 | data = md_read.load_data("input.pdf") 55 | 56 | # The result 'data' is of type List[LlamaIndexDocument] 57 | # Every list item contains metadata and the markdown text of 1 page. 58 | ``` 59 | 60 | * A LlamaIndex document essentially corresponds to Python dictionary, where the markdown text of the page is one of the dictionary values. For instance the text of the first page is the the value of `data[0].to_dict().["text"]`. 61 | * For details, please consult LlamaIndex documentation. 62 | * Upon creation of the `LlamaMarkdownReader` all necessary LlamaIndex-related imports are executed. Required related package installations must have been done independently and will not be checked during pymupdf4llm installation. -------------------------------------------------------------------------------- /pymupdf4llm/pymupdf4llm/__init__.py: -------------------------------------------------------------------------------- 1 | from .helpers.pymupdf_rag import IdentifyHeaders, to_markdown 2 | 3 | __version__ = "0.0.24" 4 | version = __version__ 5 | version_tuple = tuple(map(int, version.split("."))) 6 | 7 | 8 | def LlamaMarkdownReader(*args, **kwargs): 9 | from .llama import pdf_markdown_reader 10 | 11 | return pdf_markdown_reader.PDFMarkdownReader(*args, **kwargs) 12 | -------------------------------------------------------------------------------- /pymupdf4llm/pymupdf4llm/helpers/get_text_lines.py: -------------------------------------------------------------------------------- 1 | """ 2 | This script accepts a PDF document filename and converts it to a text file. 3 | 4 | 5 | Dependencies 6 | ------------- 7 | PyMuPDF v1.24.2 or later 8 | 9 | Copyright and License 10 | ---------------------- 11 | Copyright 2024 Artifex Software, Inc. 12 | License GNU Affero GPL 3.0 13 | """ 14 | 15 | import string 16 | import sys 17 | 18 | import pymupdf 19 | 20 | WHITE = set(string.whitespace) 21 | 22 | 23 | def is_white(text): 24 | return WHITE.issuperset(text) 25 | 26 | 27 | def get_raw_lines( 28 | textpage, 29 | clip=None, 30 | tolerance=3, 31 | ignore_invisible=True, 32 | ): 33 | """Extract the text spans from a TextPage in natural reading sequence. 34 | 35 | All spans roughly on the same line are joined to generate an improved line. 36 | This copes with MuPDF's algorithm that generates new lines also for spans 37 | whose horizontal distance is larger than some threshold. 38 | 39 | Result is a sorted list of line objects that consist of the recomputed line 40 | boundary box and the sorted list of spans in that line. 41 | 42 | This result can then easily be converted e.g. to plain text and other 43 | formats like Markdown or JSON. 44 | 45 | Args: 46 | textpage: (mandatory) TextPage object 47 | clip: (Rect) specifies a sub-rectangle of the textpage rect (which in 48 | turn may be based on a sub-rectangle of the full page). 49 | tolerance: (float) put spans on the same line if their top or bottom 50 | coordinate differ by no more than this value. 51 | ignore_invisible: (bool) if True, invisible text is ignored. This may 52 | have been set to False for pages with OCR text. 53 | 54 | Returns: 55 | A sorted list of items (rect, [spans]), each representing one line. The 56 | spans are sorted left to right. Span dictionaries have been changed: 57 | - "bbox" has been converted to a Rect object 58 | - "line" (new) the line number in TextPage.extractDICT 59 | - "block" (new) the block number in TextPage.extractDICT 60 | This allows to detect where MuPDF has generated line breaks to indicate 61 | large inter-span distances. 62 | """ 63 | y_delta = tolerance # allowable vertical coordinate deviation 64 | 65 | def sanitize_spans(line): 66 | """Sort and join the spans in a re-synthesized line. 67 | 68 | The PDF may contain "broken" text with words cut into pieces. 69 | This funtion joins spans representing the particles and sorts them 70 | left to right. 71 | 72 | Arg: 73 | A list of spans - as drived from TextPage.extractDICT() 74 | Returns: 75 | A list of sorted, and potentially cleaned-up spans 76 | """ 77 | # sort ascending horizontally 78 | line.sort(key=lambda s: s["bbox"].x0) 79 | # join spans, delete duplicates 80 | for i in range(len(line) - 1, 0, -1): # iterate back to front 81 | s0 = line[i - 1] # preceding span 82 | s1 = line[i] # this span 83 | # "delta" depends on the font size. Spans will be joined if 84 | # no more than 10% of the font size separates them and important 85 | # attributes are the same. 86 | delta = s1["size"] * 0.1 87 | if s0["bbox"].x1 + delta < s1["bbox"].x0 or ( 88 | s0["flags"], 89 | s0["char_flags"], 90 | s0["size"], 91 | ) != (s1["flags"], s1["char_flags"], s1["size"]): 92 | continue # no joining 93 | # We need to join bbox and text of two consecutive spans 94 | # On occasion, spans may also be duplicated. 95 | if s0["text"] != s1["text"] or s0["bbox"] != s1["bbox"]: 96 | s0["text"] += s1["text"] 97 | s0["bbox"] |= s1["bbox"] # join boundary boxes 98 | del line[i] # delete the joined-in span 99 | line[i - 1] = s0 # update the span 100 | return line 101 | 102 | if clip is None: # use TextPage rect if not provided 103 | clip = textpage.rect 104 | # extract text blocks - if bbox is not empty 105 | blocks = [ 106 | b 107 | for b in textpage.extractDICT()["blocks"] 108 | if b["type"] == 0 and not pymupdf.Rect(b["bbox"]).is_empty 109 | ] 110 | spans = [] # all spans in TextPage here 111 | for bno, b in enumerate(blocks): # the numbered blocks 112 | for lno, line in enumerate(b["lines"]): # the numbered lines 113 | if abs(1 - line["dir"][0]) > 1e-3: # only accept horizontal text 114 | continue 115 | for sno, s in enumerate(line["spans"]): # the numered spans 116 | sbbox = pymupdf.Rect(s["bbox"]) # span bbox as a Rect 117 | if is_white(s["text"]): # ignore white text 118 | continue 119 | # ignore invisible text 120 | if s["alpha"] == 0 and ignore_invisible: 121 | continue 122 | if abs(sbbox & clip) < abs(sbbox) * 0.8: # if not in clip 123 | continue 124 | if s["flags"] & 1 == 1: # if a superscript, modify bbox 125 | # with that of the preceding or following span 126 | i = 1 if sno == 0 else sno - 1 127 | if len(line["spans"]) > i: 128 | neighbor = line["spans"][i] 129 | sbbox.y1 = neighbor["bbox"][3] 130 | s["text"] = f"[{s['text']}]" 131 | s["bbox"] = sbbox # update with the Rect version 132 | # include line/block numbers to facilitate separator insertion 133 | s["line"] = lno 134 | s["block"] = bno 135 | spans.append(s) 136 | 137 | if not spans: # no text at all 138 | return [] 139 | 140 | spans.sort(key=lambda s: s["bbox"].y1) # sort spans by bottom coord 141 | nlines = [] # final result 142 | line = [spans[0]] # collects spans with fitting vertical coordinates 143 | lrect = spans[0]["bbox"] # rectangle joined from span rectangles 144 | 145 | for s in spans[1:]: # walk through the spans 146 | sbbox = s["bbox"] # this bbox 147 | sbbox0 = line[-1]["bbox"] # previous bbox 148 | # if any of top or bottom coordinates are close enough, join... 149 | if abs(sbbox.y1 - sbbox0.y1) <= y_delta or abs(sbbox.y0 - sbbox0.y0) <= y_delta: 150 | line.append(s) # append to this line 151 | lrect |= sbbox # extend line rectangle 152 | continue 153 | 154 | # end of current line, sort its spans from left to right 155 | line = sanitize_spans(line) 156 | 157 | # append line rect and its spans to final output 158 | nlines.append([lrect, line]) 159 | 160 | line = [s] # start next line 161 | lrect = sbbox # initialize its rectangle 162 | 163 | # need to append last line in the same way 164 | line = sanitize_spans(line) 165 | nlines.append([lrect, line]) 166 | 167 | return nlines 168 | 169 | 170 | def get_text_lines(page, *, textpage=None, clip=None, sep="\t", tolerance=3, ocr=False): 171 | """Extract text by line keeping natural reading sequence. 172 | 173 | Notes: 174 | Internally uses "dict" to select lines and their spans. 175 | Returns plain text. If originally separate MuPDF lines in fact have 176 | (approximatly) the same baseline, they are joined into one line using 177 | the 'sep' character(s). 178 | This method can be used to extract text in reading sequence - even in 179 | cases of text replaced by way of redaction annotations. 180 | 181 | Args: 182 | page: (pymupdf.Page) 183 | textpage: (TextPage) if None a temporary one is created. 184 | clip: (rect-like) only consider spans inside this area 185 | sep: (str) use this string when joining multiple MuPDF lines. 186 | Returns: 187 | String of plain text in reading sequence. 188 | """ 189 | textflags = pymupdf.TEXT_MEDIABOX_CLIP 190 | page.remove_rotation() 191 | prect = page.rect if not clip else pymupdf.Rect(clip) # area to consider 192 | 193 | xsep = sep if sep == "|" else "" 194 | 195 | # make a TextPage if required 196 | if textpage is None: 197 | if ocr is False: 198 | tp = page.get_textpage(clip=prect, flags=textflags) 199 | else: 200 | tp = page.get_textpage_ocr(dpi=300, full=True) 201 | else: 202 | tp = textpage 203 | 204 | lines = get_raw_lines(tp, clip=prect, tolerance=tolerance) 205 | 206 | if not textpage: # delete temp TextPage 207 | tp = None 208 | 209 | if not lines: 210 | return "" 211 | 212 | # Compose final text 213 | alltext = "" 214 | 215 | if not ocr: 216 | prev_bno = -1 # number of previous text block 217 | for lrect, line in lines: # iterate through lines 218 | # insert extra line break if a different block 219 | bno = line[0]["block"] # block number of this line 220 | if bno != prev_bno: 221 | alltext += "\n" 222 | prev_bno = bno 223 | 224 | line_no = line[0]["line"] # store the line number of previous span 225 | for s in line: # walk over the spans in the line 226 | lno = s["line"] 227 | stext = s["text"] 228 | if line_no == lno: 229 | alltext += stext 230 | else: 231 | alltext += sep + stext 232 | line_no = lno 233 | alltext += "\n" # append line break after a line 234 | alltext += "\n" # append line break at end of block 235 | return alltext 236 | 237 | """ 238 | For OCR output, we try a rudimentary table recognition. 239 | """ 240 | rows = [] 241 | xvalues = [] 242 | for lrect, line in lines: 243 | # if only 1 span in line and no columns identified yet... 244 | if len(line) == 1 and not xvalues: 245 | alltext += line[0]["text"] + "\n\n\n" 246 | continue 247 | # multiple spans in line and no columns identified yet 248 | elif not xvalues: # define column borders 249 | xvalues = [s["bbox"].x0 for s in line] + [line[-1]["bbox"].x1] 250 | col_count = len(line) # number of columns 251 | row = [""] * col_count 252 | for r, l in line: 253 | for i in range(len(xvalues) - 1): 254 | x0, x1 = xvalues[i], xvalues[i + 1] 255 | if abs(r.x0 - x0) <= 3 or abs(r.x1 - x1) <= 3: 256 | row[i] = l 257 | rows.append(row) 258 | if rows: 259 | row = "|" + "|".join(rows[0]) + "|\n" 260 | alltext += row 261 | alltext += "|---" * len(rows[0]) + "|\n" 262 | for row in rows[1:]: 263 | alltext += "|" + "|".join(row) + "|\n" 264 | alltext += "\n" 265 | return alltext 266 | 267 | 268 | if __name__ == "__main__": 269 | import pathlib 270 | 271 | filename = sys.argv[1] 272 | doc = pymupdf.open(filename) 273 | text = "" 274 | for page in doc: 275 | text += get_text_lines(page, sep=" ") + "\n" + chr(12) + "\n" 276 | pathlib.Path(f"{doc.name}.txt").write_bytes(text.encode()) 277 | -------------------------------------------------------------------------------- /pymupdf4llm/pymupdf4llm/helpers/multi_column.py: -------------------------------------------------------------------------------- 1 | """ 2 | This is an advanced PyMuPDF utility for detecting multi-column pages. 3 | It can be used in a shell script, or its main function can be imported and 4 | invoked as descript below. 5 | 6 | Features 7 | --------- 8 | - Identify text belonging to (a variable number of) columns on the page. 9 | - Text with different background color is handled separately, allowing for 10 | easier treatment of side remarks, comment boxes, etc. 11 | - Uses text block detection capability to identify text blocks and 12 | uses the block bboxes as primary structuring principle. 13 | - Supports ignoring footers via a footer margin parameter. 14 | - Returns re-created text boundary boxes (integer coordinates), sorted ascending 15 | by the top, then by the left coordinates. 16 | 17 | Restrictions 18 | ------------- 19 | - Only supporting horizontal, left-to-right text 20 | - Returns a list of text boundary boxes - not the text itself. The caller is 21 | expected to extract text from within the returned boxes. 22 | - Text written above images is ignored altogether (option). 23 | - This utility works as expected in most cases. The following situation cannot 24 | be handled correctly: 25 | * overlapping (non-disjoint) text blocks 26 | * image captions are not recognized and are handled like normal text 27 | 28 | Usage 29 | ------ 30 | - As a CLI shell command use 31 | 32 | python multi_column.py input.pdf footer_margin header_margin 33 | 34 | Where margins are the height of the bottom / top stripes to ignore on each 35 | page. 36 | This code is intended to be modified according to your need. 37 | 38 | - Use in a Python script as follows: 39 | 40 | ---------------------------------------------------------------------------------- 41 | from multi_column import column_boxes 42 | 43 | # for each page execute 44 | bboxes = column_boxes(page, footer_margin=50, no_image_text=True) 45 | 46 | bboxes is a list of pymupdf.IRect objects, that are sorted ascending by their 47 | y0, then x0 coordinates. Their text content can be extracted by all PyMuPDF 48 | get_text() variants, like for instance the following: 49 | for rect in bboxes: 50 | print(page.get_text(clip=rect, sort=True)) 51 | ---------------------------------------------------------------------------------- 52 | 53 | Dependencies 54 | ------------- 55 | PyMuPDF v1.24.2 or later 56 | 57 | Copyright and License 58 | ---------------------- 59 | Copyright 2024 Artifex Software, Inc. 60 | License GNU Affero GPL 3.0 61 | """ 62 | 63 | import string 64 | 65 | import pymupdf 66 | 67 | pymupdf.TOOLS.unset_quad_corrections(True) 68 | 69 | 70 | def column_boxes( 71 | page, 72 | *, 73 | footer_margin=50, 74 | header_margin=50, 75 | no_image_text=True, 76 | textpage=None, 77 | paths=None, 78 | avoid=None, 79 | ignore_images=False, 80 | ): 81 | """Determine bboxes which wrap a column on the page. 82 | 83 | Args: 84 | footer_margin: ignore text if distance from bottom is less 85 | header_margin: ignore text if distance from top is less 86 | no_image_text: ignore text inside image bboxes 87 | textpage: use this textpage instead of creating one 88 | paths: use these drawings instead of extracting here 89 | avoid: ignore text in any of these areas 90 | """ 91 | WHITE = set(string.whitespace) 92 | 93 | def is_white(text): 94 | """Check for relevant text.""" 95 | return WHITE.issuperset(text) 96 | 97 | def in_bbox(bb, bboxes): 98 | """Return 1-based number if a bbox contains bb, else return 0.""" 99 | for i, bbox in enumerate(bboxes, start=1): 100 | if bb in bbox: 101 | return i 102 | return 0 103 | 104 | def in_bbox_using_cache(bb, bboxes, cache): 105 | """Return 1-based number if a bbox contains bb, else return 0.""" 106 | """Results are stored in the cache for speedup.""" 107 | cache_key = f"{id(bb)}_{id(bboxes)}" 108 | cached = cache.get(cache_key) 109 | if cached is not None: 110 | return cached 111 | 112 | index = 0 113 | for i, bbox in enumerate(bboxes, start=1): 114 | if bb in bbox: 115 | index = i 116 | break 117 | 118 | cache[cache_key] = index 119 | return index 120 | 121 | def intersects_bboxes(bb, bboxes): 122 | """Return True if a bbox touches bb, else return False.""" 123 | for bbox in bboxes: 124 | if not (bb & bbox).is_valid: 125 | return True 126 | return False 127 | 128 | def can_extend(temp, bb, bboxlist, vert_bboxes): 129 | """Determines whether rectangle 'temp' can be extended by 'bb' 130 | without intersecting any of the rectangles contained in 'bboxlist' 131 | or 'vert_bboxes'. 132 | 133 | Items of bboxlist may be None if they have been removed. 134 | 135 | Returns: 136 | True if 'temp' has no intersections with items of 'bboxlist'. 137 | """ 138 | for b in bboxlist: 139 | if not intersects_bboxes(temp, vert_bboxes) and ( 140 | b is None or b == bb or (temp & b).is_empty 141 | ): 142 | continue 143 | return False 144 | 145 | return True 146 | 147 | def clean_nblocks(nblocks): 148 | """Do some elementary cleaning.""" 149 | 150 | # 1. remove any duplicate blocks. 151 | blen = len(nblocks) 152 | if blen < 2: 153 | return nblocks 154 | start = blen - 1 155 | for i in range(start, -1, -1): 156 | bb1 = nblocks[i] 157 | bb0 = nblocks[i - 1] 158 | if bb0 == bb1: 159 | del nblocks[i] 160 | 161 | if len(nblocks) == 0: 162 | return nblocks 163 | 164 | # 2. repair sequence in special cases: 165 | # consecutive bboxes with almost same bottom value are sorted ascending 166 | # by x-coordinate. 167 | y1 = nblocks[0].y1 # first bottom coordinate 168 | i0 = 0 # its index 169 | i1 = -1 # index of last bbox with same bottom 170 | 171 | # Iterate over bboxes, identifying segments with approx. same bottom value. 172 | # Replace every segment by its sorted version. 173 | for i in range(1, len(nblocks)): 174 | b1 = nblocks[i] 175 | if abs(b1.y1 - y1) > 3: # different bottom 176 | if i1 > i0: # segment length > 1? Sort it! 177 | nblocks[i0 : i1 + 1] = sorted( 178 | nblocks[i0 : i1 + 1], key=lambda b: b.x0 179 | ) 180 | y1 = b1.y1 # store new bottom value 181 | i0 = i # store its start index 182 | i1 = i # store current index 183 | if i1 > i0: # segment waiting to be sorted 184 | nblocks[i0 : i1 + 1] = sorted(nblocks[i0 : i1 + 1], key=lambda b: b.x0) 185 | return nblocks 186 | 187 | def join_rects_phase1(bboxes): 188 | """Postprocess identified text blocks, phase 1. 189 | 190 | Joins any rectangles that "touch" each other. 191 | This means that their intersection is valid (but may be empty). 192 | To prefer vertical joins, we will ignore small gaps. 193 | """ 194 | delta = (0, 0, 0, 10) # allow this gap below 195 | prects = bboxes[:] 196 | new_rects = [] 197 | while prects: 198 | prect0 = prects[0] 199 | repeat = True 200 | while repeat: 201 | repeat = False 202 | for i in range(len(prects) - 1, 0, -1): 203 | if ((prect0 + delta) & prects[i]).is_valid: 204 | prect0 |= prects[i] 205 | del prects[i] 206 | repeat = True 207 | new_rects.append(prect0) 208 | del prects[0] 209 | return new_rects 210 | 211 | def join_rects_phase2(bboxes): 212 | """Postprocess identified text blocks, phase 2. 213 | 214 | Increase the width of each text block so that small left or right 215 | border differences are removed. Then try to join even more text 216 | rectangles. 217 | """ 218 | prects = bboxes[:] # copy of argument list 219 | for i in range(len(prects)): 220 | b = prects[i] 221 | # go left and right somewhat 222 | x0 = min([bb.x0 for bb in prects if abs(bb.x0 - b.x0) <= 3]) 223 | x1 = max([bb.x1 for bb in prects if abs(bb.x1 - b.x1) <= 3]) 224 | b.x0 = x0 # store new left / right border 225 | b.x1 = x1 226 | prects[i] = b 227 | 228 | # sort by left, top 229 | prects.sort(key=lambda b: (b.x0, b.y0)) 230 | new_rects = [prects[0]] # initialize with first item 231 | 232 | # walk through the rest, top to bottom, then left to right 233 | for r in prects[1:]: 234 | r0 = new_rects[-1] # previous bbox 235 | 236 | # join if we have similar borders and are not too far down 237 | if ( 238 | abs(r.x0 - r0.x0) <= 3 239 | and abs(r.x1 - r0.x1) <= 3 240 | and abs(r0.y1 - r.y0) <= 10 241 | ): 242 | r0 |= r 243 | new_rects[-1] = r0 244 | continue 245 | # else append this as new text block 246 | new_rects.append(r) 247 | return new_rects 248 | 249 | def join_rects_phase3(bboxes, path_rects, cache): 250 | prects = bboxes[:] 251 | new_rects = [] 252 | 253 | while prects: 254 | prect0 = prects[0] 255 | repeat = True 256 | while repeat: 257 | repeat = False 258 | for i in range(len(prects) - 1, 0, -1): 259 | prect1 = prects[i] 260 | # do not join across columns 261 | if prect1.x0 > prect0.x1 or prect1.x1 < prect0.x0: 262 | continue 263 | 264 | # do not join different backgrounds 265 | if in_bbox_using_cache( 266 | prect0, path_rects, cache 267 | ) != in_bbox_using_cache(prect1, path_rects, cache): 268 | continue 269 | temp = prect0 | prect1 270 | test = set( 271 | [tuple(b) for b in prects + new_rects if b.intersects(temp)] 272 | ) 273 | if test == set((tuple(prect0), tuple(prect1))): 274 | prect0 |= prect1 275 | prects[0] = prect0 276 | del prects[i] 277 | repeat = True 278 | new_rects.append(prect0) 279 | del prects[0] 280 | 281 | """ 282 | Hopefully the most reasonable sorting sequence: 283 | At this point we have finished identifying blocks that wrap text. 284 | We now need to determine the SEQUENCE by which text extraction from 285 | these blocks should take place. This is hardly possible with 100% 286 | certainty. Our sorting approach is guided by the following thought: 287 | 1. Extraction should start with the block whose top-left corner is the 288 | left-most and top-most. 289 | 2. Any blocks further to the right should be extracted later - even if 290 | their top-left corner is higher up on the page. 291 | 3. Sorting the identified rectangles must therefore happen using a 292 | tuple (y, x) as key, where y is not smaller (= higher up) than that 293 | of the left-most block with a non-empty vertical overlap. 294 | 4. To continue "left block" with "next is ...", its sort key must be 295 | Q +---------+ tuple (P.y, Q.x). 296 | | next is | 297 | P +-------+ | this | 298 | | left | | block | 299 | | block | +---------+ 300 | +-------+ 301 | """ 302 | sort_rects = [] # copy of "new_rects" with a computed sort key 303 | for box in new_rects: 304 | # search for the left-most rect that overlaps like "P" above 305 | # candidates must have the same background 306 | background = in_bbox(box, path_rects) # this background 307 | left_rects = sorted( 308 | [ 309 | r 310 | for r in new_rects 311 | if r.x1 < box.x0 312 | and (box.y0 <= r.y0 <= box.y1 or box.y0 <= r.y1 <= box.y1) 313 | # and in_bbox(r, path_rects) == background 314 | ], 315 | key=lambda r: r.x1, 316 | ) 317 | if left_rects: # if a "P" rectangle was found ... 318 | key = (left_rects[-1].y0, box.x0) # use this key 319 | else: 320 | key = (box.y0, box.x0) # else use the original (Q.y, Q.x). 321 | sort_rects.append((box, key)) 322 | sort_rects.sort(key=lambda sr: sr[1]) # by computed key 323 | new_rects = [sr[0] for sr in sort_rects] # extract sorted rectangles 324 | 325 | # move text rects with background color into a separate list 326 | shadow_rects = [] 327 | # for i in range(len(new_rects) - 1, 0, -1): 328 | # r = +new_rects[i] 329 | # if in_bbox(r, path_rects): # text with shaded background 330 | # shadow_rects.insert(0, r) # put in front to keep sequence 331 | # del new_rects[i] 332 | return new_rects + shadow_rects 333 | 334 | # compute relevant page area 335 | clip = +page.rect 336 | clip.y1 -= footer_margin # Remove footer area 337 | clip.y0 += header_margin # Remove header area 338 | 339 | if paths is None: 340 | paths = [ 341 | p 342 | for p in page.get_drawings() 343 | if p["rect"].width < clip.width and p["rect"].height < clip.height 344 | ] 345 | 346 | if textpage is None: 347 | textpage = page.get_textpage(clip=clip, flags=pymupdf.TEXT_ACCURATE_BBOXES) 348 | 349 | bboxes = [] 350 | 351 | # image bboxes 352 | img_bboxes = [] 353 | if avoid is not None: 354 | img_bboxes.extend(avoid) 355 | 356 | # non-horizontal text boxes, avoid when expanding other text boxes 357 | vert_bboxes = [] 358 | 359 | # path rectangles 360 | path_rects = [] 361 | for p in paths: 362 | # give empty path rectangles some small width or height 363 | prect = p["rect"] 364 | lwidth = 0.5 if (_ := p["width"]) is None else _ * 0.5 365 | 366 | if prect.width == 0: 367 | prect.x0 -= lwidth 368 | prect.x1 += lwidth 369 | if prect.height == 0: 370 | prect.y0 -= lwidth 371 | prect.y1 += lwidth 372 | path_rects.append(prect) 373 | 374 | # sort path bboxes by ascending top, then left coordinates 375 | path_rects.sort(key=lambda b: (b.y0, b.x0)) 376 | 377 | # bboxes of images on page, no need to sort them 378 | if ignore_images is False: 379 | for item in page.get_images(): 380 | img_bboxes.extend(page.get_image_rects(item[0])) 381 | 382 | # blocks of text on page 383 | blocks = textpage.extractDICT()["blocks"] 384 | 385 | # Make block rectangles, ignoring non-horizontal text 386 | for b in blocks: 387 | bbox = pymupdf.Rect(b["bbox"]) # bbox of the block 388 | 389 | # ignore text written upon images 390 | if no_image_text and in_bbox(bbox, img_bboxes): 391 | continue 392 | 393 | # confirm first line to be horizontal 394 | try: 395 | line0 = b["lines"][0] # get first line 396 | except IndexError: 397 | continue 398 | 399 | if abs(1 - line0["dir"][0]) > 1e-3: # only (almost) horizontal text 400 | vert_bboxes.append(bbox) # a block with non-horizontal text 401 | continue 402 | 403 | srect = pymupdf.EMPTY_RECT() 404 | for line in b["lines"]: 405 | lbbox = pymupdf.Rect(line["bbox"]) 406 | text = "".join([s["text"] for s in line["spans"]]) 407 | if not is_white(text): 408 | srect |= lbbox 409 | bbox = +srect 410 | 411 | if not bbox.is_empty: 412 | bboxes.append(bbox) 413 | 414 | # Sort text bboxes by ascending background, top, then left coordinates 415 | bboxes.sort(key=lambda k: (in_bbox(k, path_rects), k.y0, k.x0)) 416 | 417 | # immediately return of no text found 418 | if bboxes == []: 419 | return [] 420 | # -------------------------------------------------------------------- 421 | # Join bboxes to establish some column structure 422 | # -------------------------------------------------------------------- 423 | # the final block bboxes on page 424 | nblocks = [bboxes[0]] # pre-fill with first bbox 425 | bboxes = bboxes[1:] # remaining old bboxes 426 | cache = {} 427 | 428 | for i, bb in enumerate(bboxes): # iterate old bboxes 429 | check = False # indicates unwanted joins 430 | 431 | # check if bb can extend one of the new blocks 432 | for j in range(len(nblocks)): 433 | nbb = nblocks[j] # a new block 434 | 435 | # never join across columns 436 | if bb is None or nbb.x1 < bb.x0 or bb.x1 < nbb.x0: 437 | continue 438 | 439 | # never join across different background colors 440 | if in_bbox_using_cache(nbb, path_rects, cache) != in_bbox_using_cache( 441 | bb, path_rects, cache 442 | ): 443 | continue 444 | 445 | temp = bb | nbb # temporary extension of new block 446 | check = can_extend(temp, nbb, nblocks, vert_bboxes) 447 | if check is True: 448 | break 449 | 450 | if not check: # bb cannot be used to extend any of the new bboxes 451 | nblocks.append(bb) # so add it to the list 452 | j = len(nblocks) - 1 # index of it 453 | temp = nblocks[j] # new bbox added 454 | 455 | # check if some remaining bbox is contained in temp 456 | check = can_extend(temp, bb, bboxes, vert_bboxes) 457 | if check is False: 458 | nblocks.append(bb) 459 | else: 460 | nblocks[j] = temp 461 | bboxes[i] = None 462 | 463 | # do some elementary cleaning 464 | nblocks = clean_nblocks(nblocks) 465 | if len(nblocks) == 0: 466 | return nblocks 467 | 468 | # several phases of rectangle joining 469 | # TODO: disabled for now as too aggressive: 470 | # nblocks = join_rects_phase1(nblocks) 471 | nblocks = join_rects_phase2(nblocks) 472 | nblocks = join_rects_phase3(nblocks, path_rects, cache) 473 | 474 | # return identified text bboxes 475 | return nblocks 476 | 477 | 478 | if __name__ == "__main__": 479 | """Only for debugging purposes, currently. 480 | 481 | Draw red borders around the returned text bboxes and insert 482 | the bbox number. 483 | Then save the file under the name "input-blocks.pdf". 484 | """ 485 | import sys 486 | 487 | RED = pymupdf.pdfcolor["red"] 488 | # get the file name 489 | filename = sys.argv[1] 490 | 491 | # check if footer margin is given 492 | if len(sys.argv) > 2: 493 | footer_margin = int(sys.argv[2]) 494 | else: 495 | footer_margin = 0 496 | 497 | # check if header margin is given 498 | if len(sys.argv) > 3: 499 | header_margin = int(sys.argv[3]) 500 | else: 501 | header_margin = 0 502 | 503 | # open document 504 | doc = pymupdf.open(filename) 505 | 506 | # iterate over the pages 507 | for page in doc: 508 | # get the text bboxes 509 | bboxes = column_boxes( 510 | page, footer_margin=footer_margin, header_margin=header_margin 511 | ) 512 | 513 | # prepare a canvas to draw rectangles and text 514 | shape = page.new_shape() 515 | 516 | # iterate over the bboxes 517 | for i, rect in enumerate(bboxes): 518 | shape.draw_rect(rect) # draw a border 519 | 520 | # write sequence number 521 | shape.insert_text(rect.tl + (5, 15), str(i), color=RED) 522 | 523 | # finish drawing / text with color red 524 | shape.finish(color=RED) 525 | shape.commit() # store to the page 526 | 527 | # save document with text bboxes 528 | doc.ez_save(filename.replace(".pdf", "-blocks.pdf")) 529 | -------------------------------------------------------------------------------- /pymupdf4llm/pymupdf4llm/helpers/progress.py: -------------------------------------------------------------------------------- 1 | """ 2 | This script defines a text-based progress bar to allow watching the advancement 3 | of Markdown conversion of document pages. 4 | 5 | Dependencies 6 | ------------- 7 | None 8 | 9 | Copyright and License 10 | ---------------------- 11 | Copyright 2024 Artifex Software, Inc. 12 | License GNU Affero GPL 3.0 13 | """ 14 | 15 | import sys 16 | from typing import Any, List 17 | 18 | 19 | class _ProgressBar: 20 | def __init__(self, items: List[Any], progress_width: int = 40): 21 | self._len = len(items) 22 | self._iter = iter(items) 23 | self._len_digits = len(str(self._len)) 24 | self._progress_width = progress_width 25 | self._progress_bar = 0 26 | self._current_index = 0 27 | 28 | # Calculate the increment for each item based on the list length and the progress width 29 | self._increment = self._progress_width / self._len if self._len else 1 30 | 31 | # Init progress bar 32 | sys.stdout.write( 33 | "[%s] (0/%d)" % (" " * self._progress_width, self._len) 34 | ) 35 | sys.stdout.flush() 36 | sys.stdout.write( 37 | "\b" * (self._progress_width + len(str(self._len)) + 6) 38 | ) 39 | 40 | def __iter__(self): 41 | return self 42 | 43 | def __next__(self): 44 | try: 45 | result = next(self._iter) 46 | except StopIteration as e: 47 | # End progress on StopIteration 48 | sys.stdout.write("]\n") 49 | raise e 50 | 51 | # Update the current index 52 | self._current_index += 1 53 | 54 | # Add the increment to the progress bar and calculate how many "=" to add 55 | self._progress_bar += self._increment 56 | while self._progress_bar >= 1: 57 | sys.stdout.write("=") 58 | sys.stdout.flush() 59 | self._progress_bar -= 1 60 | 61 | # Update the numerical progress 62 | padded_index = str(self._current_index).rjust(self._len_digits) 63 | progress_info = f" ({padded_index}/{self._len})" 64 | sys.stdout.write( 65 | "\b" * (self._progress_width + len(progress_info) + 1) 66 | ) 67 | sys.stdout.write("[") 68 | sys.stdout.write( 69 | "=" * int(self._current_index * self._progress_width / self._len) 70 | ) 71 | sys.stdout.write( 72 | " " 73 | * ( 74 | self._progress_width 75 | - int(self._current_index * self._progress_width / self._len) 76 | ) 77 | ) 78 | sys.stdout.write("]" + progress_info) 79 | sys.stdout.flush() 80 | sys.stdout.write( 81 | "\b" 82 | * ( 83 | self._progress_width 84 | - int(self._current_index * self._progress_width / self._len) 85 | + len(progress_info) 86 | + 1 87 | ) 88 | ) 89 | 90 | return result 91 | 92 | 93 | def ProgressBar(list: List[Any], progress_width: int = 40): 94 | return iter(_ProgressBar(list, progress_width)) 95 | -------------------------------------------------------------------------------- /pymupdf4llm/pymupdf4llm/helpers/pymupdf_rag.py: -------------------------------------------------------------------------------- 1 | """ 2 | This script accepts a PDF document filename and converts it to a text file 3 | in Markdown format, compatible with the GitHub standard. 4 | 5 | It must be invoked with the filename like this: 6 | 7 | python pymupdf_rag.py input.pdf [-pages PAGES] 8 | 9 | The "PAGES" parameter is a string (containing no spaces) of comma-separated 10 | page numbers to consider. Each item is either a single page number or a 11 | number range "m-n". Use "N" to address the document's last page number. 12 | Example: "-pages 2-15,40,43-N" 13 | 14 | It will produce a markdown text file called "input.md". 15 | 16 | Text will be sorted in Western reading order. Any table will be included in 17 | the text in markdwn format as well. 18 | 19 | Dependencies 20 | ------------- 21 | PyMuPDF v1.25.5 or later 22 | 23 | Copyright and License 24 | ---------------------- 25 | Copyright (C) 2024-2025 Artifex Software, Inc. 26 | 27 | PyMuPDF4LLM is free software: you can redistribute it and/or modify it under the 28 | terms of the GNU Affero General Public License as published by the Free 29 | Software Foundation, either version 3 of the License, or (at your option) 30 | any later version. 31 | 32 | Alternative licensing terms are available from the licensor. 33 | For commercial licensing, see or contact 34 | Artifex Software, Inc., 39 Mesa Street, Suite 108A, San Francisco, 35 | CA 94129, USA, for further information. 36 | """ 37 | 38 | import os 39 | import string 40 | from binascii import b2a_base64 41 | import pymupdf 42 | from pymupdf import mupdf 43 | from pymupdf4llm.helpers.get_text_lines import get_raw_lines, is_white 44 | from pymupdf4llm.helpers.multi_column import column_boxes 45 | from pymupdf4llm.helpers.progress import ProgressBar 46 | from dataclasses import dataclass 47 | from collections import defaultdict 48 | 49 | pymupdf.TOOLS.unset_quad_corrections(True) 50 | 51 | # Characters recognized as bullets when starting a line. 52 | bullet = tuple( 53 | [ 54 | "- ", 55 | "* ", 56 | "> ", 57 | chr(0xB6), 58 | chr(0xB7), 59 | chr(8224), 60 | chr(8225), 61 | chr(8226), 62 | chr(0xF0A7), 63 | chr(0xF0B7), 64 | ] 65 | + list(map(chr, range(9632, 9680))) 66 | ) 67 | 68 | GRAPHICS_TEXT = "\n![](%s)\n" 69 | 70 | 71 | class IdentifyHeaders: 72 | """Compute data for identifying header text. 73 | 74 | All non-white text from all selected pages is extracted and its font size 75 | noted as a rounded value. 76 | The most frequent font size (and all smaller ones) is taken as body text 77 | font size. 78 | Larger font sizes are mapped to strings of multiples of '#', the header 79 | tag in Markdown, which in turn is Markdown's representation of HTML's 80 | header tags

to

. 81 | Larger font sizes than body text but smaller than the
font size are 82 | represented as
. 83 | """ 84 | 85 | def __init__( 86 | self, 87 | doc: str, 88 | pages: list = None, 89 | body_limit: float = 12, # force this to be body text 90 | max_levels: int = 6, # accept this many header levels 91 | ): 92 | """Read all text and make a dictionary of fontsizes. 93 | 94 | Args: 95 | doc: PDF document or filename 96 | pages: consider these page numbers only 97 | body_limit: treat text with larger font size as a header 98 | """ 99 | if not isinstance(max_levels, int) or max_levels not in range(1, 7): 100 | raise ValueError("max_levels must be an integer between 1 and 6") 101 | if isinstance(doc, pymupdf.Document): 102 | mydoc = doc 103 | else: 104 | mydoc = pymupdf.open(doc) 105 | 106 | if pages is None: # use all pages if omitted 107 | pages = range(mydoc.page_count) 108 | 109 | fontsizes = defaultdict(int) 110 | for pno in pages: 111 | page = mydoc.load_page(pno) 112 | blocks = page.get_text("dict", flags=pymupdf.TEXTFLAGS_TEXT)["blocks"] 113 | for span in [ # look at all non-empty horizontal spans 114 | s 115 | for b in blocks 116 | for l in b["lines"] 117 | for s in l["spans"] 118 | if not is_white(s["text"]) 119 | ]: 120 | fontsz = round(span["size"]) # # compute rounded fontsize 121 | fontsizes[fontsz] += len(span["text"].strip()) # add character count 122 | 123 | if mydoc != doc: 124 | # if opened here, close it now 125 | mydoc.close() 126 | 127 | # maps a fontsize to a string of multiple # header tag characters 128 | self.header_id = {} 129 | 130 | # If not provided, choose the most frequent font size as body text. 131 | # If no text at all on all pages, just use body_limit. 132 | # In any case all fonts not exceeding 133 | temp = sorted( 134 | [(k, v) for k, v in fontsizes.items()], key=lambda i: (i[1], i[0]) 135 | ) 136 | if temp: 137 | # most frequent font size 138 | self.body_limit = max(body_limit, temp[-1][0]) 139 | else: 140 | self.body_limit = body_limit 141 | 142 | # identify up to 6 font sizes as header candidates 143 | sizes = sorted( 144 | [f for f in fontsizes.keys() if f > self.body_limit], 145 | reverse=True, 146 | )[:max_levels] 147 | 148 | # make the header tag dictionary 149 | for i, size in enumerate(sizes, start=1): 150 | self.header_id[size] = "#" * i + " " 151 | if self.header_id.keys(): 152 | self.body_limit = min(self.header_id.keys()) - 1 153 | 154 | def get_header_id(self, span: dict, page=None) -> str: 155 | """Return appropriate markdown header prefix. 156 | 157 | Given a text span from a "dict"/"rawdict" extraction, determine the 158 | markdown header prefix string of 0 to n concatenated '#' characters. 159 | """ 160 | fontsize = round(span["size"]) # compute fontsize 161 | if fontsize <= self.body_limit: 162 | return "" 163 | hdr_id = self.header_id.get(fontsize, "") 164 | return hdr_id 165 | 166 | 167 | class TocHeaders: 168 | """Compute data for identifying header text. 169 | 170 | This is an alternative to IdentifyHeaders. Instead of running through the 171 | full document to identify font sizes, it uses the document's Table Of 172 | Contents (TOC) to identify headers on pages. 173 | Like IdentifyHeaders, this also is no guarantee to find headers, but it 174 | is a good change for appropriately build documents. In such cases, this 175 | method can be very much faster and more accurate, because we can use the 176 | hierarchy level of TOC items directly to ientify the header level. 177 | Examples where this approach works very well are the Adobe PDF documents. 178 | """ 179 | 180 | def __init__(self, doc: str): 181 | """Read and store the TOC of the document.""" 182 | if isinstance(doc, pymupdf.Document): 183 | mydoc = doc 184 | else: 185 | mydoc = pymupdf.open(doc) 186 | 187 | self.TOC = doc.get_toc() 188 | if mydoc != doc: 189 | # if opened here, close it now 190 | mydoc.close() 191 | 192 | def get_header_id(self, span: dict, page=None) -> str: 193 | """Return appropriate markdown header prefix. 194 | 195 | Given a text span from a "dict"/"rawdict" extraction, determine the 196 | markdown header prefix string of 0 to n concatenated '#' characters. 197 | """ 198 | if page is None: 199 | return "" 200 | # check if this page has TOC entries with an actual title 201 | my_toc = [t for t in self.TOC if t[1] and t[-1] == page.number + 1] 202 | if not my_toc: 203 | return "" 204 | # check if the span matches a TOC entry 205 | text = span["text"].strip() 206 | for t in my_toc: 207 | title = t[1].strip() # title of TOC entry 208 | lvl = t[0] # level of TOC entry 209 | if text.startswith(title) or title.startswith(text): 210 | # found a match: return the header tag 211 | return "#" * lvl + " " 212 | return "" 213 | 214 | 215 | # store relevant parameters here 216 | @dataclass 217 | class Parameters: 218 | pass 219 | 220 | 221 | def refine_boxes(boxes, enlarge=0): 222 | """Join any rectangles with a pairwise non-empty overlap. 223 | 224 | Accepts and returns a list of Rect items. 225 | Note that rectangles that only "touch" each other (common point or edge) 226 | are not considered as overlapping. 227 | Use a positive "enlarge" parameter to enlarge rectangle by these many 228 | points in every direction. 229 | 230 | TODO: Consider using a sweeping line algorithm for this. 231 | """ 232 | delta = (-enlarge, -enlarge, enlarge, enlarge) 233 | new_rects = [] 234 | # list of all vector graphic rectangles 235 | prects = boxes[:] 236 | 237 | while prects: # the algorithm will empty this list 238 | r = +prects[0] + delta # copy of first rectangle 239 | repeat = True # initialize condition 240 | while repeat: 241 | repeat = False # set false as default 242 | for i in range(len(prects) - 1, 0, -1): # from back to front 243 | if r.intersects(prects[i].irect): # enlarge first rect with this 244 | r |= prects[i] 245 | del prects[i] # delete this rect 246 | repeat = True # indicate must try again 247 | 248 | # first rect now includes all overlaps 249 | new_rects.append(r) 250 | del prects[0] 251 | 252 | new_rects = sorted(set(new_rects), key=lambda r: (r.x0, r.y0)) 253 | return new_rects 254 | 255 | 256 | def is_significant(box, paths): 257 | """Check whether the rectangle "box" contains 'signifiant' drawings. 258 | 259 | This means that some path is contained in the "interior" of box. 260 | To this end, we build a sub-box of 90% of the original box and check 261 | whether this still contains drawing paths. 262 | """ 263 | if box.width > box.height: 264 | d = box.width * 0.025 265 | else: 266 | d = box.height * 0.025 267 | nbox = box + (d, d, -d, -d) # nbox covers 90% of box interior 268 | # paths contained in, but not equal to box: 269 | my_paths = [p for p in paths if p["rect"] in box and p["rect"] != box] 270 | for p in my_paths: 271 | rect = p["rect"] 272 | if ( 273 | not (rect & nbox).is_empty and not p["rect"].is_empty 274 | ): # intersects interior: significant! 275 | return True 276 | # Remaining case: a horizontal or vertical line 277 | # horizontal line: 278 | if ( 279 | 1 280 | and rect.y0 == rect.y1 281 | and nbox.y0 <= rect.y0 <= nbox.y1 282 | and rect.x0 < nbox.x1 283 | and rect.x1 > nbox.x0 284 | ): 285 | pass # return True 286 | # vertical line 287 | if ( 288 | 1 289 | and rect.x0 == rect.x1 290 | and nbox.x0 <= rect.x0 <= nbox.x1 291 | and rect.y0 < nbox.y1 292 | and rect.y1 > nbox.y0 293 | ): 294 | pass # return True 295 | return False 296 | 297 | 298 | def to_markdown( 299 | doc, 300 | *, 301 | pages=None, 302 | hdr_info=None, 303 | write_images=False, 304 | embed_images=False, 305 | ignore_images=False, 306 | ignore_graphics=False, 307 | image_path="", 308 | image_format="png", 309 | image_size_limit=0.05, 310 | filename=None, 311 | force_text=True, 312 | page_chunks=False, 313 | margins=0, 314 | dpi=150, 315 | page_width=612, 316 | page_height=None, 317 | table_strategy="lines_strict", 318 | graphics_limit=None, 319 | fontsize_limit=3, 320 | ignore_code=False, 321 | extract_words=False, 322 | show_progress=False, 323 | use_glyphs=False, 324 | ) -> str: 325 | """Process the document and return the text of the selected pages. 326 | 327 | Args: 328 | doc: pymupdf.Document or string. 329 | pages: list of page numbers to consider (0-based). 330 | hdr_info: callable or object having method 'get_hdr_info'. 331 | write_images: (bool) save images / graphics as files. 332 | embed_images: (bool) embed images in markdown text (base64 encoded) 333 | image_path: (str) store images in this folder. 334 | image_format: (str) use this image format. Choose a supported one. 335 | force_text: (bool) output text despite of image background. 336 | page_chunks: (bool) whether to segment output by page. 337 | margins: omit content overlapping margin areas. 338 | dpi: (int) desired resolution for generated images. 339 | page_width: (float) assumption if page layout is variable. 340 | page_height: (float) assumption if page layout is variable. 341 | table_strategy: choose table detection strategy 342 | graphics_limit: (int) if vector graphics count exceeds this, ignore all. 343 | ignore_code: (bool) suppress code-like formatting (mono-space fonts) 344 | extract_words: (bool) include "words"-like output in page chunks 345 | show_progress: (bool) print progress as each page is processed. 346 | use_glyphs: (bool) replace the Invalid Unicode by glyph numbers. 347 | 348 | """ 349 | if write_images is False and embed_images is False and force_text is False: 350 | raise ValueError("Image and text on images cannot both be suppressed.") 351 | if embed_images is True: 352 | write_images = False 353 | image_path = "" 354 | if not 0 <= image_size_limit < 1: 355 | raise ValueError("'image_size_limit' must be non-negative and less than 1.") 356 | DPI = dpi 357 | IGNORE_CODE = ignore_code 358 | IMG_EXTENSION = image_format 359 | EXTRACT_WORDS = extract_words 360 | if EXTRACT_WORDS is True: 361 | page_chunks = True 362 | ignore_code = True 363 | IMG_PATH = image_path 364 | if IMG_PATH and write_images is True and not os.path.exists(IMG_PATH): 365 | os.mkdir(IMG_PATH) 366 | 367 | if not isinstance(doc, pymupdf.Document): 368 | doc = pymupdf.open(doc) 369 | 370 | FILENAME = doc.name if filename is None else filename 371 | GRAPHICS_LIMIT = graphics_limit 372 | FONTSIZE_LIMIT = fontsize_limit 373 | IGNORE_IMAGES = ignore_images 374 | IGNORE_GRAPHICS = ignore_graphics 375 | 376 | # for reflowable documents allow making 1 page for the whole document 377 | if doc.is_reflowable: 378 | if hasattr(page_height, "__float__"): 379 | # accept user page dimensions 380 | doc.layout(width=page_width, height=page_height) 381 | else: 382 | # no page height limit given: make 1 page for whole document 383 | doc.layout(width=page_width, height=792) 384 | page_count = doc.page_count 385 | height = 792 * page_count # height that covers full document 386 | doc.layout(width=page_width, height=height) 387 | 388 | if pages is None: # use all pages if no selection given 389 | pages = list(range(doc.page_count)) 390 | 391 | if hasattr(margins, "__float__"): 392 | margins = [margins] * 4 393 | if len(margins) == 2: 394 | margins = (0, margins[0], 0, margins[1]) 395 | if len(margins) != 4: 396 | raise ValueError("margins must be one, two or four floats") 397 | elif not all([hasattr(m, "__float__") for m in margins]): 398 | raise ValueError("margin values must be floats") 399 | 400 | # If "hdr_info" is not an object with a method "get_header_id", scan the 401 | # document and use font sizes as header level indicators. 402 | if callable(hdr_info): 403 | get_header_id = hdr_info 404 | elif hasattr(hdr_info, "get_header_id") and callable(hdr_info.get_header_id): 405 | get_header_id = hdr_info.get_header_id 406 | elif hdr_info is False: 407 | get_header_id = lambda s, page=None: "" 408 | else: 409 | hdr_info = IdentifyHeaders(doc) 410 | get_header_id = hdr_info.get_header_id 411 | 412 | def max_header_id(spans, page): 413 | hdr_ids = sorted( 414 | [l for l in set([len(get_header_id(s, page=page)) for s in spans]) if l > 0] 415 | ) 416 | if not hdr_ids: 417 | return "" 418 | return "#" * (hdr_ids[0] - 1) + " " 419 | 420 | def resolve_links(links, span): 421 | """Accept a span and return a markdown link string. 422 | 423 | Args: 424 | links: a list as returned by page.get_links() 425 | span: a span dictionary as returned by page.get_text("dict") 426 | 427 | Returns: 428 | None or a string representing the link in MD format. 429 | """ 430 | bbox = pymupdf.Rect(span["bbox"]) # span bbox 431 | # a link should overlap at least 70% of the span 432 | for link in links: 433 | hot = link["from"] # the hot area of the link 434 | middle = (hot.tl + hot.br) / 2 # middle point of hot area 435 | if not middle in bbox: 436 | continue # does not touch the bbox 437 | text = f'[{span["text"].strip()}]({link["uri"]})' 438 | return text 439 | 440 | def save_image(parms, rect, i): 441 | """Optionally render the rect part of a page. 442 | 443 | We will ignore images that are empty or that have an edge smaller 444 | than x% of the corresponding page edge.""" 445 | page = parms.page 446 | if ( 447 | rect.width < page.rect.width * image_size_limit 448 | or rect.height < page.rect.height * image_size_limit 449 | ): 450 | return "" 451 | if write_images is True or embed_images is True: 452 | pix = page.get_pixmap(clip=rect, dpi=DPI) 453 | else: 454 | return "" 455 | if pix.height <= 0 or pix.width <= 0: 456 | return "" 457 | 458 | if write_images is True: 459 | filename = os.path.basename(parms.filename).replace(" ", "-") 460 | image_filename = os.path.join( 461 | IMG_PATH, f"{filename}-{page.number}-{i}.{IMG_EXTENSION}" 462 | ) 463 | pix.save(image_filename) 464 | return image_filename.replace("\\", "/") 465 | elif embed_images is True: 466 | # make a base64 encoded string of the image 467 | data = b2a_base64(pix.tobytes(IMG_EXTENSION)).decode() 468 | data = f"data:image/{IMG_EXTENSION};base64," + data 469 | return data 470 | return "" 471 | 472 | def write_text( 473 | parms, 474 | clip: pymupdf.Rect, 475 | tables=True, 476 | images=True, 477 | force_text=force_text, 478 | ): 479 | """Output the text found inside the given clip. 480 | 481 | This is an alternative for plain text in that it outputs 482 | text enriched with markdown styling. 483 | The logic is capable of recognizing headers, body text, code blocks, 484 | inline code, bold, italic and bold-italic styling. 485 | There is also some effort for list supported (ordered / unordered) in 486 | that typical characters are replaced by respective markdown characters. 487 | 488 | 'tables'/'images' indicate whether this execution should output these 489 | objects. 490 | """ 491 | 492 | if clip is None: 493 | clip = parms.clip 494 | out_string = "" 495 | 496 | # This is a list of tuples (linerect, spanlist) 497 | nlines = get_raw_lines( 498 | parms.textpage, 499 | clip=clip, 500 | tolerance=3, 501 | ignore_invisible=not parms.accept_invisible, 502 | ) 503 | nlines = [ 504 | l for l in nlines if not intersects_rects(l[0], parms.tab_rects.values()) 505 | ] 506 | 507 | parms.line_rects.extend([l[0] for l in nlines]) # store line rectangles 508 | 509 | prev_lrect = None # previous line rectangle 510 | prev_bno = -1 # previous block number of line 511 | code = False # mode indicator: outputting code 512 | prev_hdr_string = None 513 | 514 | for lrect, spans in nlines: 515 | # there may be tables or images inside the text block: skip them 516 | if intersects_rects(lrect, parms.img_rects): 517 | continue 518 | 519 | # ------------------------------------------------------------ 520 | # Pick up tables ABOVE this text block 521 | # ------------------------------------------------------------ 522 | if tables: 523 | tab_candidates = [ 524 | (i, tab_rect) 525 | for i, tab_rect in parms.tab_rects.items() 526 | if tab_rect.y1 <= lrect.y0 527 | and i not in parms.written_tables 528 | and ( 529 | 0 530 | or lrect.x0 <= tab_rect.x0 < lrect.x1 531 | or lrect.x0 < tab_rect.x1 <= lrect.x1 532 | or tab_rect.x0 <= lrect.x0 < lrect.x1 <= tab_rect.x1 533 | ) 534 | ] 535 | for i, _ in tab_candidates: 536 | out_string += "\n" + parms.tabs[i].to_markdown(clean=False) + "\n" 537 | if EXTRACT_WORDS: 538 | # for "words" extraction, add table cells as line rects 539 | cells = sorted( 540 | set( 541 | [ 542 | pymupdf.Rect(c) 543 | for c in parms.tabs[i].header.cells 544 | + parms.tabs[i].cells 545 | if c is not None 546 | ] 547 | ), 548 | key=lambda c: (c.y1, c.x0), 549 | ) 550 | parms.line_rects.extend(cells) 551 | parms.written_tables.append(i) 552 | 553 | # ------------------------------------------------------------ 554 | # Pick up images / graphics ABOVE this text block 555 | # ------------------------------------------------------------ 556 | if images: 557 | for i in range(len(parms.img_rects)): 558 | if i in parms.written_images: 559 | continue 560 | r = parms.img_rects[i] 561 | if r.y1 <= lrect.y0 and ( 562 | 0 563 | or lrect.x0 <= r.x0 < lrect.x1 564 | or lrect.x0 < r.x1 <= lrect.x1 565 | or r.x0 <= lrect.x0 < lrect.x1 <= r.x1 566 | ): 567 | pathname = save_image(parms, r, i) 568 | if pathname: 569 | out_string += GRAPHICS_TEXT % pathname 570 | 571 | # recursive invocation 572 | if force_text is True: 573 | img_txt = write_text( 574 | parms, 575 | r, 576 | tables=False, 577 | images=False, 578 | force_text=True, 579 | ) 580 | 581 | if not is_white(img_txt): 582 | out_string += img_txt 583 | parms.written_images.append(i) 584 | 585 | parms.line_rects.append(lrect) 586 | 587 | # make text string for the full line 588 | text = " ".join([s["text"] for s in spans]) 589 | 590 | # if line is a header, this will return multiple "#" characters, 591 | # otherwise an empty string 592 | hdr_string = max_header_id(spans, page=parms.page) # a header? 593 | 594 | # full line strikeout? 595 | all_strikeout = all([s["char_flags"] & 1 for s in spans]) 596 | # full line italic? 597 | all_italic = all([s["flags"] & 2 for s in spans]) 598 | # full line bold? 599 | all_bold = all([s["flags"] & 16 or s["char_flags"] & 8 for s in spans]) 600 | 601 | # full line mono-spaced? 602 | if not IGNORE_CODE: 603 | all_mono = all([s["flags"] & 8 for s in spans]) 604 | else: 605 | all_mono = False 606 | 607 | if all_mono and not hdr_string: 608 | if not code: # if not already in code output mode: 609 | out_string += "```\n" # switch on "code" mode 610 | code = True 611 | # compute approx. distance from left - assuming a width 612 | # of 0.5*fontsize. 613 | delta = int((lrect.x0 - clip.x0) / (spans[0]["size"] * 0.5)) 614 | indent = " " * delta 615 | 616 | out_string += indent + text + "\n" 617 | continue # done with this line 618 | 619 | if hdr_string: # if a header line skip the rest 620 | if all_mono: 621 | text = "`" + text + "`" 622 | if all_strikeout: 623 | text = "~~" + text + "~~" 624 | if all_italic: 625 | text = "*" + text + "*" 626 | if all_bold: 627 | text = "**" + text + "**" 628 | if hdr_string != prev_hdr_string: 629 | out_string += hdr_string + text + "\n" 630 | else: 631 | # intercept if header text has been broken in multiple lines 632 | while out_string.endswith("\n"): 633 | out_string = out_string[:-1] 634 | out_string += " " + text + "\n" 635 | prev_hdr_string = hdr_string 636 | continue 637 | 638 | prev_hdr_string = hdr_string 639 | 640 | span0 = spans[0] 641 | bno = span0["block"] # block number of line 642 | if bno != prev_bno: 643 | out_string += "\n" 644 | prev_bno = bno 645 | 646 | if ( # check if we need another line break 647 | prev_lrect 648 | and lrect.y1 - prev_lrect.y1 > lrect.height * 1.5 649 | or span0["text"].startswith("[") 650 | or span0["text"].startswith(bullet) 651 | or span0["flags"] & 1 # superscript? 652 | ): 653 | out_string += "\n" 654 | prev_lrect = lrect 655 | 656 | # this line is not all-mono, so switch off "code" mode 657 | if code: # in code output mode? 658 | out_string += "```\n" # switch of code mode 659 | code = False 660 | 661 | for i, s in enumerate(spans): # iterate spans of the line 662 | # decode font properties 663 | mono = s["flags"] & 8 and IGNORE_CODE is False 664 | bold = s["flags"] & 16 or s["char_flags"] & 8 665 | italic = s["flags"] & 2 666 | strikeout = s["char_flags"] & 1 667 | 668 | if mono: 669 | # this is text in some monospaced font 670 | out_string += f"`{s['text'].strip()}` " 671 | continue 672 | 673 | prefix = "" 674 | suffix = "" 675 | if bold: 676 | prefix = "**" + prefix 677 | suffix += "**" 678 | if italic: 679 | prefix = "*" + prefix 680 | suffix += "*" 681 | if strikeout: 682 | prefix = "~~" + prefix 683 | suffix += "~~" 684 | if mono: 685 | prefix = "`" + prefix 686 | suffix += "`" 687 | 688 | # convert intersecting link to markdown syntax 689 | ltext = resolve_links(parms.links, s) 690 | if ltext: 691 | text = f"{hdr_string}{prefix}{ltext}{suffix} " 692 | else: 693 | text = f"{hdr_string}{prefix}{s['text'].strip()}{suffix} " 694 | if text.startswith(bullet): 695 | text = "- " + text[1:] 696 | text = text.replace(" ", " ") 697 | dist = span0["bbox"][0] - clip.x0 698 | cwidth = (span0["bbox"][2] - span0["bbox"][0]) / len(span0["text"]) 699 | if cwidth == 0.0: 700 | cwidth = span0["size"] * 0.5 701 | text = " " * int(round(dist / cwidth)) + text 702 | 703 | out_string += text 704 | if not code: 705 | out_string += "\n" 706 | out_string += "\n" 707 | if code: 708 | out_string += "```\n" # switch of code mode 709 | code = False 710 | 711 | return ( 712 | out_string.replace(" \n", "\n").replace(" ", " ").replace("\n\n\n", "\n\n") 713 | ) 714 | 715 | def is_in_rects(rect, rect_list): 716 | """Check if rect is contained in a rect of the list.""" 717 | for i, r in enumerate(rect_list, start=1): 718 | if rect in r: 719 | return i 720 | return 0 721 | 722 | def intersects_rects(rect, rect_list): 723 | """Check if middle of rect is contained in a rect of the list.""" 724 | delta = (-1, -1, 1, 1) # enlarge rect_list members somewhat by this 725 | enlarged = rect + delta 726 | abs_enlarged = abs(enlarged) * 0.5 727 | for i, r in enumerate(rect_list, start=1): 728 | if abs(enlarged & r) > abs_enlarged: 729 | return i 730 | return 0 731 | 732 | def output_tables(parms, text_rect): 733 | """Output tables above given text rectangle.""" 734 | this_md = "" # markdown string for table(s) content 735 | if text_rect is not None: # select tables above the text block 736 | for i, trect in sorted( 737 | [j for j in parms.tab_rects.items() if j[1].y1 <= text_rect.y0], 738 | key=lambda j: (j[1].y1, j[1].x0), 739 | ): 740 | if i in parms.written_tables: 741 | continue 742 | this_md += parms.tabs[i].to_markdown(clean=False) 743 | if EXTRACT_WORDS: 744 | # for "words" extraction, add table cells as line rects 745 | cells = sorted( 746 | set( 747 | [ 748 | pymupdf.Rect(c) 749 | for c in parms.tabs[i].header.cells 750 | + parms.tabs[i].cells 751 | if c is not None 752 | ] 753 | ), 754 | key=lambda c: (c.y1, c.x0), 755 | ) 756 | parms.line_rects.extend(cells) 757 | parms.written_tables.append(i) # do not touch this table twice 758 | 759 | else: # output all remaining tables 760 | for i, trect in parms.tab_rects.items(): 761 | if i in parms.written_tables: 762 | continue 763 | this_md += parms.tabs[i].to_markdown(clean=False) 764 | if EXTRACT_WORDS: 765 | # for "words" extraction, add table cells as line rects 766 | cells = sorted( 767 | set( 768 | [ 769 | pymupdf.Rect(c) 770 | for c in parms.tabs[i].header.cells 771 | + parms.tabs[i].cells 772 | if c is not None 773 | ] 774 | ), 775 | key=lambda c: (c.y1, c.x0), 776 | ) 777 | parms.line_rects.extend(cells) 778 | parms.written_tables.append(i) # do not touch this table twice 779 | return this_md 780 | 781 | def output_images(parms, text_rect, force_text): 782 | """Output images and graphics above text rectangle.""" 783 | if not parms.img_rects: 784 | return "" 785 | this_md = "" # markdown string 786 | if text_rect is not None: # select images above the text block 787 | for i, img_rect in enumerate(parms.img_rects): 788 | if img_rect.y0 > text_rect.y0: 789 | continue 790 | if img_rect.x0 >= text_rect.x1 or img_rect.x1 <= text_rect.x0: 791 | continue 792 | if i in parms.written_images: 793 | continue 794 | pathname = save_image(parms, img_rect, i) 795 | parms.written_images.append(i) # do not touch this image twice 796 | if pathname: 797 | this_md += GRAPHICS_TEXT % pathname 798 | if force_text: 799 | img_txt = write_text( 800 | parms, 801 | img_rect, 802 | tables=False, # we have no tables here 803 | images=False, # we have no other images here 804 | force_text=True, 805 | ) 806 | if not is_white(img_txt): # was there text at all? 807 | this_md += img_txt 808 | else: # output all remaining images 809 | for i, img_rect in enumerate(parms.img_rects): 810 | if i in parms.written_images: 811 | continue 812 | pathname = save_image(parms, img_rect, i) 813 | parms.written_images.append(i) # do not touch this image twice 814 | if pathname: 815 | this_md += GRAPHICS_TEXT % pathname 816 | if force_text: 817 | img_txt = write_text( 818 | parms, 819 | img_rect, 820 | tables=False, # we have no tables here 821 | images=False, # we have no other images here 822 | force_text=True, 823 | ) 824 | if not is_white(img_txt): 825 | this_md += img_txt 826 | 827 | return this_md 828 | 829 | def page_is_ocr(page): 830 | """Check if page exclusivley contains OCR text. 831 | 832 | For this to be true, all text must be written as "ignore-text". 833 | """ 834 | text_types = set([b[0] for b in page.get_bboxlog() if "text" in b[0]]) 835 | if text_types == {"ignore-text"}: 836 | return True 837 | return False 838 | 839 | def get_bg_color(page): 840 | """Determine the background color of the page. 841 | 842 | The function returns a PDF RGB color triple or None. 843 | We check the color of 10 x 10 pixel areas in the four corners of the 844 | page. If they are unicolor and of the same color, we assume this to 845 | be the background color. 846 | """ 847 | pix = page.get_pixmap( 848 | clip=(page.rect.x0, page.rect.y0, page.rect.x0 + 10, page.rect.y0 + 10) 849 | ) 850 | if not pix.samples or not pix.is_unicolor: 851 | return None 852 | pixel_ul = pix.pixel(0, 0) # upper left color 853 | pix = page.get_pixmap( 854 | clip=(page.rect.x1 - 10, page.rect.y0, page.rect.x1, page.rect.y0 + 10) 855 | ) 856 | if not pix.samples or not pix.is_unicolor: 857 | return None 858 | pixel_ur = pix.pixel(0, 0) # upper right color 859 | if not pixel_ul == pixel_ur: 860 | return None 861 | pix = page.get_pixmap( 862 | clip=(page.rect.x0, page.rect.y1 - 10, page.rect.x0 + 10, page.rect.y1) 863 | ) 864 | if not pix.samples or not pix.is_unicolor: 865 | return None 866 | pixel_ll = pix.pixel(0, 0) # lower left color 867 | if not pixel_ul == pixel_ll: 868 | return None 869 | pix = page.get_pixmap( 870 | clip=(page.rect.x1 - 10, page.rect.y1 - 10, page.rect.x1, page.rect.y1) 871 | ) 872 | if not pix.samples or not pix.is_unicolor: 873 | return None 874 | pixel_lr = pix.pixel(0, 0) # lower right color 875 | if not pixel_ul == pixel_lr: 876 | return None 877 | return (pixel_ul[0] / 255, pixel_ul[1] / 255, pixel_ul[2] / 255) 878 | 879 | def get_metadata(doc, pno): 880 | meta = doc.metadata.copy() 881 | meta["file_path"] = FILENAME 882 | meta["page_count"] = doc.page_count 883 | meta["page"] = pno + 1 884 | return meta 885 | 886 | def sort_words(words: list) -> list: 887 | """Reorder words in lines. 888 | 889 | The argument list must be presorted by bottom, then left coordinates. 890 | 891 | Words with similar top / bottom coordinates are assumed to belong to 892 | the same line and will be sorted left to right within that line. 893 | """ 894 | if not words: 895 | return [] 896 | nwords = [] 897 | line = [words[0]] 898 | lrect = pymupdf.Rect(words[0][:4]) 899 | for w in words[1:]: 900 | if abs(w[1] - lrect.y0) <= 3 or abs(w[3] - lrect.y1) <= 3: 901 | line.append(w) 902 | lrect |= w[:4] 903 | else: 904 | line.sort(key=lambda w: w[0]) 905 | nwords.extend(line) 906 | line = [w] 907 | lrect = pymupdf.Rect(w[:4]) 908 | line.sort(key=lambda w: w[0]) 909 | nwords.extend(line) 910 | return nwords 911 | 912 | def get_page_output( 913 | doc, pno, margins, textflags, FILENAME, IGNORE_IMAGES, IGNORE_GRAPHICS 914 | ): 915 | """Process one page. 916 | 917 | Args: 918 | doc: pymupdf.Document 919 | pno: 0-based page number 920 | textflags: text extraction flag bits 921 | 922 | Returns: 923 | Markdown string of page content and image, table and vector 924 | graphics information. 925 | """ 926 | page = doc[pno] 927 | page.remove_rotation() # make sure we work on rotation=0 928 | parms = Parameters() # all page information 929 | parms.page = page 930 | parms.filename = FILENAME 931 | parms.md_string = "" 932 | parms.images = [] 933 | parms.tables = [] 934 | parms.graphics = [] 935 | parms.words = [] 936 | parms.line_rects = [] 937 | parms.accept_invisible = page_is_ocr(page) # accept invisible text 938 | 939 | # determine background color 940 | parms.bg_color = get_bg_color(page) 941 | 942 | left, top, right, bottom = margins 943 | parms.clip = page.rect + (left, top, -right, -bottom) 944 | 945 | # extract external links on page 946 | parms.links = [l for l in page.get_links() if l["kind"] == pymupdf.LINK_URI] 947 | 948 | # extract annotation rectangles on page 949 | parms.annot_rects = [a.rect for a in page.annots()] 950 | 951 | # make a TextPage for all later extractions 952 | parms.textpage = page.get_textpage(flags=textflags, clip=parms.clip) 953 | 954 | # extract images on page 955 | if not IGNORE_IMAGES: 956 | img_info = page.get_image_info() 957 | else: 958 | img_info = [] 959 | for i in range(len(img_info)): 960 | img_info[i]["bbox"] = pymupdf.Rect(img_info[i]["bbox"]) 961 | img_info = [ 962 | i 963 | for i in img_info 964 | if i["bbox"].width >= image_size_limit * parms.clip.width 965 | and i["bbox"].height >= image_size_limit * parms.clip.height 966 | and i["bbox"].intersects(parms.clip) 967 | and i["bbox"].width > 3 968 | and i["bbox"].height > 3 969 | ] 970 | # sort descending by image area size 971 | img_info.sort(key=lambda i: abs(i["bbox"]), reverse=True) 972 | img_info = img_info[:30] # only accept the largest up to 30 images 973 | # run from back to front (= small to large) 974 | for i in range(len(img_info) - 1, 0, -1): 975 | r = img_info[i]["bbox"] 976 | if r.is_empty: 977 | del img_info[i] 978 | continue 979 | for j in range(i): # image areas larger than r 980 | if r in img_info[j]["bbox"]: 981 | del img_info[i] # contained in some larger image 982 | break 983 | parms.images = img_info 984 | 985 | parms.img_rects = [i["bbox"] for i in parms.images] 986 | 987 | # catch too-many-graphics situation 988 | graphics_count = len([b for b in page.get_bboxlog() if "path" in b[0]]) 989 | if GRAPHICS_LIMIT and graphics_count > GRAPHICS_LIMIT: 990 | IGNORE_GRAPHICS = True 991 | 992 | # Locate all tables on page 993 | parms.written_tables = [] # stores already written tables 994 | omitted_table_rects = [] 995 | if IGNORE_GRAPHICS or not table_strategy: 996 | # do not try to extract tables 997 | parms.tabs = None 998 | else: 999 | parms.tabs = page.find_tables(clip=parms.clip, strategy=table_strategy) 1000 | # remove tables with too few rows or columns 1001 | for i in range(len(parms.tabs.tables) - 1, -1, -1): 1002 | t = parms.tabs.tables[i] 1003 | if t.row_count < 2 or t.col_count < 2: 1004 | omitted_table_rects.append(pymupdf.Rect(t.bbox)) 1005 | del parms.tabs.tables[i] 1006 | parms.tabs.tables.sort(key=lambda t: (t.bbox[0], t.bbox[1])) 1007 | 1008 | # Make a list of table boundary boxes. 1009 | # Must include the header bbox (which may exist outside tab.bbox) 1010 | tab_rects = {} 1011 | if parms.tabs is not None: 1012 | for i, t in enumerate(parms.tabs.tables): 1013 | tab_rects[i] = pymupdf.Rect(t.bbox) | pymupdf.Rect(t.header.bbox) 1014 | tab_dict = { 1015 | "bbox": tuple(tab_rects[i]), 1016 | "rows": t.row_count, 1017 | "columns": t.col_count, 1018 | } 1019 | parms.tables.append(tab_dict) 1020 | parms.tab_rects = tab_rects 1021 | # list of table rectangles 1022 | parms.tab_rects0 = list(tab_rects.values()) 1023 | 1024 | # Select paths not intersecting any table. 1025 | # Ignore full page graphics. 1026 | # Ignore fill paths having the background color. 1027 | if not IGNORE_GRAPHICS: 1028 | paths = [ 1029 | p 1030 | for p in page.get_drawings() 1031 | if p["rect"] in parms.clip 1032 | and p["rect"].width < parms.clip.width 1033 | and p["rect"].height < parms.clip.height 1034 | and (p["rect"].width > 3 or p["rect"].height > 3) 1035 | and not (p["fill"] == parms.bg_color and p["fill"] != None) 1036 | and not intersects_rects( 1037 | p["rect"], parms.tab_rects0 + omitted_table_rects 1038 | ) 1039 | and not intersects_rects(p["rect"], parms.annot_rects) 1040 | ] 1041 | else: 1042 | paths = [] 1043 | 1044 | # catch too-many-graphics situation 1045 | if GRAPHICS_LIMIT and len(paths) > GRAPHICS_LIMIT: 1046 | paths = [] 1047 | 1048 | # We also ignore vector graphics that only represent 1049 | # "text emphasizing sugar". 1050 | vg_clusters0 = [] # worthwhile vector graphics go here 1051 | 1052 | # walk through all vector graphics outside any table 1053 | clusters = page.cluster_drawings(drawings=paths) 1054 | for bbox in clusters: 1055 | if is_significant(bbox, paths): 1056 | vg_clusters0.append(bbox) 1057 | 1058 | # remove paths that are not in some relevant graphic 1059 | parms.actual_paths = [p for p in paths if is_in_rects(p["rect"], vg_clusters0)] 1060 | 1061 | # also add image rectangles to the list and vice versa 1062 | vg_clusters0.extend(parms.img_rects) 1063 | parms.img_rects.extend(vg_clusters0) 1064 | parms.img_rects = sorted(set(parms.img_rects), key=lambda r: (r.y1, r.x0)) 1065 | parms.written_images = [] 1066 | # these may no longer be pairwise disjoint: 1067 | # remove area overlaps by joining into larger rects 1068 | parms.vg_clusters0 = refine_boxes(vg_clusters0) 1069 | 1070 | parms.vg_clusters = dict((i, r) for i, r in enumerate(parms.vg_clusters0)) 1071 | # identify text bboxes on page, avoiding tables, images and graphics 1072 | text_rects = column_boxes( 1073 | parms.page, 1074 | paths=parms.actual_paths, 1075 | no_image_text=not force_text, 1076 | textpage=parms.textpage, 1077 | avoid=parms.tab_rects0 + parms.vg_clusters0, 1078 | footer_margin=margins[3], 1079 | header_margin=margins[1], 1080 | ignore_images=IGNORE_IMAGES, 1081 | ) 1082 | 1083 | """ 1084 | ------------------------------------------------------------------ 1085 | Extract markdown text iterating over text rectangles. 1086 | We also output any tables. They may live above, below or inside 1087 | the text rectangles. 1088 | ------------------------------------------------------------------ 1089 | """ 1090 | for text_rect in text_rects: 1091 | # output tables above this rectangle 1092 | parms.md_string += output_tables(parms, text_rect) 1093 | parms.md_string += output_images(parms, text_rect, force_text) 1094 | 1095 | # output text inside this rectangle 1096 | parms.md_string += write_text( 1097 | parms, 1098 | text_rect, 1099 | force_text=force_text, 1100 | images=True, 1101 | tables=True, 1102 | ) 1103 | 1104 | parms.md_string = parms.md_string.replace(" ,", ",").replace("-\n", "") 1105 | 1106 | # write any remaining tables and images 1107 | parms.md_string += output_tables(parms, None) 1108 | parms.md_string += output_images(parms, None, force_text) 1109 | 1110 | while parms.md_string.startswith("\n"): 1111 | parms.md_string = parms.md_string[1:] 1112 | parms.md_string = parms.md_string.replace(chr(0), chr(0xFFFD)) 1113 | 1114 | if EXTRACT_WORDS is True: 1115 | # output words in sequence compliant with Markdown text 1116 | rawwords = parms.textpage.extractWORDS() 1117 | rawwords.sort(key=lambda w: (w[3], w[0])) 1118 | 1119 | words = [] 1120 | for lrect in parms.line_rects: 1121 | lwords = [] 1122 | for w in rawwords: 1123 | wrect = pymupdf.Rect(w[:4]) 1124 | if wrect in lrect: 1125 | lwords.append(w) 1126 | words.extend(sort_words(lwords)) 1127 | 1128 | # remove word duplicates without spoiling the sequence 1129 | # duplicates may occur for multiple reasons 1130 | nwords = [] # words w/o duplicates 1131 | for w in words: 1132 | if w not in nwords: 1133 | nwords.append(w) 1134 | words = nwords 1135 | 1136 | else: 1137 | words = [] 1138 | parms.words = words 1139 | return parms 1140 | 1141 | if page_chunks is False: 1142 | document_output = "" 1143 | else: 1144 | document_output = [] 1145 | 1146 | # read the Table of Contents 1147 | toc = doc.get_toc() 1148 | 1149 | # Text extraction flags: 1150 | # omit clipped text, collect styles, use accurate bounding boxes 1151 | textflags = ( 1152 | 0 1153 | | mupdf.FZ_STEXT_CLIP 1154 | | mupdf.FZ_STEXT_ACCURATE_BBOXES 1155 | | mupdf.FZ_STEXT_IGNORE_ACTUALTEXT 1156 | | 32768 # mupdf.FZ_STEXT_COLLECT_STYLES 1157 | ) 1158 | # optionally replace 0xFFFD by glyph number 1159 | if use_glyphs: 1160 | textflags |= mupdf.FZ_STEXT_USE_GID_FOR_UNKNOWN_UNICODE 1161 | 1162 | if show_progress: 1163 | print(f"Processing {FILENAME}...") 1164 | pages = ProgressBar(pages) 1165 | for pno in pages: 1166 | parms = get_page_output( 1167 | doc, pno, margins, textflags, FILENAME, IGNORE_IMAGES, IGNORE_GRAPHICS 1168 | ) 1169 | if page_chunks is False: 1170 | document_output += parms.md_string 1171 | else: 1172 | # build subet of TOC for this page 1173 | page_tocs = [t for t in toc if t[-1] == pno + 1] 1174 | 1175 | metadata = get_metadata(doc, pno) 1176 | document_output.append( 1177 | { 1178 | "metadata": metadata, 1179 | "toc_items": page_tocs, 1180 | "tables": parms.tables, 1181 | "images": parms.images, 1182 | "graphics": parms.graphics, 1183 | "text": parms.md_string, 1184 | "words": parms.words, 1185 | } 1186 | ) 1187 | del parms 1188 | 1189 | return document_output 1190 | 1191 | 1192 | def extract_images_on_page_simple(page, parms, image_size_limit): 1193 | # extract images on page 1194 | # ignore images contained in some other one (simplified mechanism) 1195 | img_info = page.get_image_info() 1196 | for i in range(len(img_info)): 1197 | item = img_info[i] 1198 | item["bbox"] = pymupdf.Rect(item["bbox"]) & parms.clip 1199 | img_info[i] = item 1200 | 1201 | # sort descending by image area size 1202 | img_info.sort(key=lambda i: abs(i["bbox"]), reverse=True) 1203 | # run from back to front (= small to large) 1204 | for i in range(len(img_info) - 1, 0, -1): 1205 | r = img_info[i]["bbox"] 1206 | if r.is_empty: 1207 | del img_info[i] 1208 | continue 1209 | for j in range(i): # image areas larger than r 1210 | if r in img_info[j]["bbox"]: 1211 | del img_info[i] # contained in some larger image 1212 | break 1213 | 1214 | return img_info 1215 | 1216 | 1217 | def filter_small_images(page, parms, image_size_limit): 1218 | img_info = [] 1219 | for item in page.get_image_info(): 1220 | r = pymupdf.Rect(item["bbox"]) & parms.clip 1221 | if r.is_empty or ( 1222 | max(r.width / page.rect.width, r.height / page.rect.height) 1223 | < image_size_limit 1224 | ): 1225 | continue 1226 | item["bbox"] = r 1227 | img_info.append(item) 1228 | return img_info 1229 | 1230 | 1231 | def extract_images_on_page_simple_drop(page, parms, image_size_limit): 1232 | img_info = filter_small_images(page, parms, image_size_limit) 1233 | 1234 | # sort descending by image area size 1235 | img_info.sort(key=lambda i: abs(i["bbox"]), reverse=True) 1236 | # run from back to front (= small to large) 1237 | for i in range(len(img_info) - 1, 0, -1): 1238 | r = img_info[i]["bbox"] 1239 | if r.is_empty: 1240 | del img_info[i] 1241 | continue 1242 | for j in range(i): # image areas larger than r 1243 | if r in img_info[j]["bbox"]: 1244 | del img_info[i] # contained in some larger image 1245 | break 1246 | 1247 | return img_info 1248 | 1249 | 1250 | if __name__ == "__main__": 1251 | import pathlib 1252 | import sys 1253 | import time 1254 | 1255 | try: 1256 | filename = "sample_document.pdf" 1257 | except IndexError: 1258 | print(f"Usage:\npython {os.path.basename(__file__)} input.pdf") 1259 | sys.exit() 1260 | 1261 | t0 = time.perf_counter() # start a time 1262 | 1263 | doc = pymupdf.open(filename) # open input file 1264 | parms = sys.argv[2:] # contains ["-pages", "PAGES"] or empty list 1265 | pages = range(doc.page_count) # default page range 1266 | if len(parms) == 2 and parms[0] == "-pages": # page sub-selection given 1267 | pages = [] # list of desired page numbers 1268 | 1269 | # replace any variable "N" by page count 1270 | pages_spec = parms[1].replace("N", f"{doc.page_count}") 1271 | for spec in pages_spec.split(","): 1272 | if "-" in spec: 1273 | start, end = map(int, spec.split("-")) 1274 | pages.extend(range(start - 1, end)) 1275 | else: 1276 | pages.append(int(spec) - 1) 1277 | 1278 | # make a set of invalid page numbers 1279 | wrong_pages = set([n + 1 for n in pages if n >= doc.page_count][:4]) 1280 | if wrong_pages != set(): # if any invalid numbers given, exit. 1281 | sys.exit(f"Page number(s) {wrong_pages} not in '{doc}'.") 1282 | 1283 | # get the markdown string 1284 | md_string = to_markdown( 1285 | doc, 1286 | pages=pages, 1287 | # write_images=True, 1288 | force_text=True, 1289 | ignore_images=True, 1290 | ignore_graphics=True, 1291 | table_strategy=None, 1292 | ) 1293 | FILENAME = doc.name 1294 | # output to a text file with extension ".md" 1295 | outname = FILENAME + ".md" 1296 | pathlib.Path(outname).write_bytes(md_string.encode()) 1297 | t1 = time.perf_counter() # stop timer 1298 | print(f"Markdown creation time for {FILENAME=} {round(t1-t0,2)} sec.") 1299 | -------------------------------------------------------------------------------- /pymupdf4llm/pymupdf4llm/llama/pdf_markdown_reader.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | from typing import Any, Callable, Dict, List, Optional, Union 3 | 4 | import pymupdf 5 | from pymupdf import Document as FitzDocument 6 | from pymupdf4llm import IdentifyHeaders, to_markdown 7 | 8 | try: 9 | from llama_index.core.readers.base import BaseReader 10 | from llama_index.core.schema import Document as LlamaIndexDocument 11 | 12 | print("Successfully imported LlamaIndex") 13 | except ImportError: 14 | raise NotImplementedError("Please install 'llama_index'.") 15 | 16 | 17 | class PDFMarkdownReader(BaseReader): 18 | """Read PDF files using PyMuPDF library.""" 19 | 20 | meta_filter: Optional[Callable[[Dict[str, Any]], Dict[str, Any]]] = None 21 | 22 | def __init__( 23 | self, 24 | meta_filter: Optional[ 25 | Callable[[Dict[str, Any]], Dict[str, Any]] 26 | ] = None, 27 | ): 28 | self.meta_filter = meta_filter 29 | 30 | def load_data( 31 | self, 32 | file_path: Union[Path, str], 33 | extra_info: Optional[Dict] = None, 34 | **load_kwargs: Any, 35 | ) -> List[LlamaIndexDocument]: 36 | """Loads list of documents from PDF file and also accepts extra information in dict format. 37 | 38 | Args: 39 | file_path (Union[Path, str]): The path to the PDF file. 40 | extra_info (Optional[Dict], optional): A dictionary containing extra information. Defaults to None. 41 | **load_kwargs (Any): Additional keyword arguments to be passed to the load method. 42 | 43 | Returns: 44 | List[LlamaIndexDocument]: A list of LlamaIndexDocument objects. 45 | """ 46 | if not isinstance(file_path, str) and not isinstance(file_path, Path): 47 | raise TypeError("file_path must be a string or Path.") 48 | 49 | if not extra_info: 50 | extra_info = {} 51 | 52 | if extra_info and not isinstance(extra_info, dict): 53 | raise TypeError("extra_info must be a dictionary.") 54 | 55 | # extract text header information 56 | hdr_info = IdentifyHeaders(file_path) 57 | 58 | doc: FitzDocument = pymupdf.open(file_path) 59 | docs = [] 60 | 61 | for page in doc: 62 | docs.append( 63 | self._process_doc_page( 64 | doc, extra_info, file_path, page.number, hdr_info, **load_kwargs 65 | ) 66 | ) 67 | return docs 68 | 69 | # Helpers 70 | # --- 71 | 72 | def _process_doc_page( 73 | self, 74 | doc: FitzDocument, 75 | extra_info: Dict[str, Any], 76 | file_path: str, 77 | page_number: int, 78 | hdr_info: IdentifyHeaders, 79 | **load_kwargs: Any, 80 | ): 81 | """Processes a single page of a PDF document.""" 82 | extra_info = self._process_doc_meta( 83 | doc, file_path, page_number, extra_info 84 | ) 85 | 86 | if self.meta_filter: 87 | extra_info = self.meta_filter(extra_info) 88 | 89 | text = to_markdown( 90 | doc, pages=[page_number], 91 | hdr_info=hdr_info, 92 | **load_kwargs, 93 | ) 94 | return LlamaIndexDocument(text=text, extra_info=extra_info) 95 | 96 | def _process_doc_meta( 97 | self, 98 | doc: FitzDocument, 99 | file_path: Union[Path, str], 100 | page_number: int, 101 | extra_info: Optional[Dict] = None, 102 | ): 103 | """Processes metas of a PDF document.""" 104 | extra_info.update(doc.metadata) 105 | extra_info["page"] = page_number + 1 106 | extra_info["total_pages"] = len(doc) 107 | extra_info["file_path"] = str(file_path) 108 | 109 | return extra_info 110 | -------------------------------------------------------------------------------- /pymupdf4llm/setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import setuptools 4 | 5 | setup_py_cwd = os.path.dirname(__file__) 6 | with open(os.path.join(setup_py_cwd, "README.md"), encoding="utf-8") as f: 7 | readme = f.read() 8 | 9 | classifiers = [ 10 | "Development Status :: 5 - Production/Stable", 11 | "Environment :: Console", 12 | "Intended Audience :: Developers", 13 | "Programming Language :: Python :: 3", 14 | "Topic :: Utilities", 15 | ] 16 | requires = ["pymupdf>=1.25.5"] 17 | 18 | setuptools.setup( 19 | name="pymupdf4llm", 20 | version="0.0.24", 21 | author="Artifex", 22 | author_email="support@artifex.com", 23 | description="PyMuPDF Utilities for LLM/RAG", 24 | packages=setuptools.find_packages(), 25 | long_description=readme, 26 | long_description_content_type="text/markdown", 27 | install_requires=requires, 28 | license="GNU AFFERO GPL 3.0", 29 | url="https://github.com/pymupdf/RAG", 30 | classifiers=classifiers, 31 | package_data={ 32 | "pymupdf4llm": ["LICENSE", "helpers/*.py", "llama/*.py"], 33 | }, 34 | project_urls={ 35 | "Documentation": "https://pymupdf.readthedocs.io/", 36 | "Source": "https://github.com/pymupdf/RAG/tree/main/pymupdf4llm/pymupdf4llm", 37 | "Tracker": "https://github.com/pymupdf/RAG/issues", 38 | "Changelog": "https://github.com/pymupdf/RAG/blob/main/CHANGES.md", 39 | }, 40 | ) 41 | -------------------------------------------------------------------------------- /tests/pymupdf4llm/llama_index/test_pdf_markdown_reader.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import pytest 4 | from llama_index.core.schema import Document as LlamaIndexDocument 5 | 6 | try: 7 | from llama_index.core.readers.base import BaseReader 8 | from llama_index.core.schema import Document as LlamaIndexDocument 9 | 10 | print("All imports are successful.") 11 | except ImportError: 12 | raise NotImplementedError("Please install 'llama_index' is needed.") 13 | 14 | 15 | from pymupdf4llm.pymupdf4llm.llama_index.pdf_markdown_reader import PDFMarkdownReader 16 | 17 | PDF = "input.pdf" 18 | 19 | 20 | def _get_test_file_path(file_name: str, __file__: str = __file__) -> str: 21 | file_path = os.path.join( 22 | os.path.dirname(os.path.abspath(__file__)), 23 | "..", 24 | "..", 25 | ".." "helpers", 26 | file_name, 27 | ) 28 | file_path = os.path.normpath(file_path) 29 | return file_path 30 | 31 | 32 | def test_load_data(): 33 | # Arrange 34 | # --- 35 | pdf_reader = PDFMarkdownReader() 36 | path = _get_test_file_path(PDF, __file__) 37 | extra_info = {"test_key": "test_value"} 38 | 39 | # Act 40 | # --- 41 | documents = pdf_reader.load_data(path, extra_info) 42 | 43 | # Assert 44 | # --- 45 | assert isinstance(documents, list) 46 | for doc in documents: 47 | assert isinstance(doc, LlamaIndexDocument) 48 | 49 | 50 | def test_load_data_with_invalid_file_path(): 51 | # Arrange 52 | # --- 53 | pdf_reader = PDFMarkdownReader() 54 | extra_info = {"test_key": "test_value"} 55 | path = "fake/path" 56 | 57 | # Act & Assert 58 | # --- 59 | with pytest.raises(Exception): 60 | pdf_reader.load_data(path, extra_info) 61 | 62 | 63 | def test_load_data_with_invalid_extra_info(): 64 | # Arrange 65 | # --- 66 | pdf_reader = PDFMarkdownReader() 67 | extra_info = "invalid_extra_info" 68 | path = _get_test_file_path(PDF, __file__) 69 | 70 | # Act & Assert 71 | # --- 72 | with pytest.raises(TypeError): 73 | pdf_reader.load_data(path, extra_info) 74 | 75 | 76 | @pytest.mark.asyncio 77 | async def test_aload_data_with_invalid_file_path(): 78 | # Arrange 79 | # --- 80 | pdf_reader = PDFMarkdownReader() 81 | extra_info = {"test_key": "test_value"} 82 | 83 | # Act 84 | # --- 85 | path = "Fake/path" 86 | 87 | # Assert 88 | # --- 89 | with pytest.raises(Exception): 90 | await pdf_reader.aload_data(path, extra_info) 91 | 92 | 93 | @pytest.mark.asyncio 94 | async def test_aload_data_with_invalid_extra_info(): 95 | # Arrange 96 | # --- 97 | pdf_reader = PDFMarkdownReader() 98 | extra_info = "invalid_extra_info" 99 | 100 | # Act 101 | # --- 102 | path = _get_test_file_path(PDF, __file__) 103 | 104 | # Assert 105 | # --- 106 | with pytest.raises(TypeError): 107 | await pdf_reader.aload_data(path, extra_info) 108 | --------------------------------------------------------------------------------