mistocr 0.0.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mistocr-0.0.3/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2022, fastai
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,5 @@
1
+ include settings.ini
2
+ include LICENSE
3
+ include CONTRIBUTING.md
4
+ include README.md
5
+ recursive-exclude * __pycache__
mistocr-0.0.3/PKG-INFO ADDED
@@ -0,0 +1,178 @@
1
+ Metadata-Version: 2.4
2
+ Name: mistocr
3
+ Version: 0.0.3
4
+ Summary: Simple batch OCR for PDFs using Mistral's state-of-the-art vision model
5
+ Home-page: https://github.com/franckalbinet/mistocr
6
+ Author: Solveit
7
+ Author-email: nobody@fast.ai
8
+ License: Apache Software License 2.0
9
+ Keywords: nbdev jupyter notebook python
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Natural Language :: English
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: License :: OSI Approved :: Apache Software License
18
+ Requires-Python: >=3.9
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: fastcore
22
+ Requires-Dist: mistralai
23
+ Requires-Dist: pillow
24
+ Requires-Dist: dotenv
25
+ Provides-Extra: dev
26
+ Dynamic: author
27
+ Dynamic: author-email
28
+ Dynamic: classifier
29
+ Dynamic: description
30
+ Dynamic: description-content-type
31
+ Dynamic: home-page
32
+ Dynamic: keywords
33
+ Dynamic: license
34
+ Dynamic: license-file
35
+ Dynamic: provides-extra
36
+ Dynamic: requires-dist
37
+ Dynamic: requires-python
38
+ Dynamic: summary
39
+
40
+ # mistocr
41
+
42
+
43
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
44
+
45
+ ## Why mistocr?
46
+
47
+ **Performance**: Mistral’s OCR delivers state-of-the-art accuracy on
48
+ complex documents including tables, charts, and multi-column layouts.
49
+
50
+ **Scale**: Process entire folders of PDFs in a single batch job. Upload
51
+ once, process asynchronously, and retrieve results when ready - perfect
52
+ for large document sets.
53
+
54
+ **Cost savings**: Batch OCR mode reduces costs from \$1/1000 pages to
55
+ \$0.50/1000 pages - a 50% reduction compared to synchronous processing.
56
+
57
+ **Simplicity**: A single `ocr()` function handles everything -
58
+ uploading, batch submission, polling for completion, and saving results
59
+ as markdown with extracted images. Process one PDF or an entire folder
60
+ with the same simple interface.
61
+
62
+ **Organized output**: Each PDF is automatically saved to its own folder
63
+ with pages as separate markdown files and images in an `img` subfolder,
64
+ making results easy to navigate and process further.
65
+
66
+ ## Installation
67
+
68
+ Install latest from the GitHub
69
+ [repository](https://github.com/franckalbinet/mistocr):
70
+
71
+ ``` sh
72
+ $ pip install git+https://github.com/franckalbinet/mistocr.git
73
+ ```
74
+
75
+ or from [pypi](https://pypi.org/project/mistocr/)
76
+
77
+ ``` sh
78
+ $ pip install mistocr
79
+ ```
80
+
81
+ ## How to use
82
+
83
+ ``` python
84
+ from mistocr.core import ocr
85
+ ```
86
+
87
+ - **Process a single PDF:**
88
+
89
+ <!-- -->
90
+
91
+ fname = 'files/test/attention-is-all-you-need.pdf'
92
+ result = ocr(fname)
93
+
94
+ ``` python
95
+ ```
96
+
97
+ files/test/md/attention-is-all-you-need:
98
+ img/ page_11.md page_14.md page_3.md page_6.md page_9.md
99
+ page_1.md page_12.md page_15.md page_4.md page_7.md
100
+ page_10.md page_13.md page_2.md page_5.md page_8.md
101
+
102
+ files/test/md/attention-is-all-you-need/img:
103
+ img-0.jpeg img-1.jpeg img-2.jpeg img-3.jpeg img-4.jpeg
104
+
105
+ - **Or process an entire folder:**
106
+
107
+ ``` python
108
+ results = ocr('files/test')
109
+ ```
110
+
111
+ ``` python
112
+ ```
113
+
114
+ files/test/md:
115
+ attention-is-all-you-need/ resnet/
116
+
117
+ files/test/md/attention-is-all-you-need:
118
+ img/ page_11.md page_14.md page_3.md page_6.md page_9.md
119
+ page_1.md page_12.md page_15.md page_4.md page_7.md
120
+ page_10.md page_13.md page_2.md page_5.md page_8.md
121
+
122
+ files/test/md/attention-is-all-you-need/img:
123
+ img-0.jpeg img-1.jpeg img-2.jpeg img-3.jpeg img-4.jpeg
124
+
125
+ files/test/md/resnet:
126
+ img/ page_10.md page_12.md page_3.md page_5.md page_7.md page_9.md
127
+ page_1.md page_11.md page_2.md page_4.md page_6.md page_8.md
128
+
129
+ files/test/md/resnet/img:
130
+ img-0.jpeg img-2.jpeg img-4.jpeg img-6.jpeg
131
+ img-1.jpeg img-3.jpeg img-5.jpeg
132
+
133
+ - **Customize the output:**
134
+
135
+ ``` python
136
+ results = ocr('files/test', out_dir='output', inc_img=False, poll_interval=5)
137
+ ```
138
+
139
+ **Parameters:**
140
+
141
+ - **`path`**: A single PDF file or folder containing multiple PDFs
142
+ - **`out_dir`**: Directory name for saving markdown output (default:
143
+ `'md'`)
144
+ - **`inc_img`**: Include extracted images in the output (default:
145
+ `True`)
146
+ - **`key`**: Your Mistral API key (uses `MISTRAL_API_KEY` environment
147
+ variable if not provided)
148
+ - **`poll_interval`**: Seconds between batch job status checks (default:
149
+ `2`)
150
+
151
+ **Returns:** List of paths to the generated markdown files
152
+
153
+ ## Developer Guide
154
+
155
+ If you are new to using `nbdev` here are some useful pointers to get you
156
+ started.
157
+
158
+ ### Install mistocr in Development mode
159
+
160
+ ``` sh
161
+ # make sure mistocr package is installed in development mode
162
+ $ pip install -e .
163
+
164
+ # make changes under nbs/ directory
165
+ # ...
166
+
167
+ # compile to have changes apply to mistocr
168
+ $ nbdev_prepare
169
+ ```
170
+
171
+ ### Documentation
172
+
173
+ Documentation can be found hosted on this GitHub
174
+ [repository](https://github.com/franckalbinet/mistocr)’s
175
+ [pages](https://franckalbinet.github.io/mistocr/). Additionally you can
176
+ find package manager specific guidelines on
177
+ [conda](https://anaconda.org/franckalbinet/mistocr) and
178
+ [pypi](https://pypi.org/project/mistocr/) respectively.
@@ -0,0 +1,139 @@
1
+ # mistocr
2
+
3
+
4
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
5
+
6
+ ## Why mistocr?
7
+
8
+ **Performance**: Mistral’s OCR delivers state-of-the-art accuracy on
9
+ complex documents including tables, charts, and multi-column layouts.
10
+
11
+ **Scale**: Process entire folders of PDFs in a single batch job. Upload
12
+ once, process asynchronously, and retrieve results when ready - perfect
13
+ for large document sets.
14
+
15
+ **Cost savings**: Batch OCR mode reduces costs from \$1/1000 pages to
16
+ \$0.50/1000 pages - a 50% reduction compared to synchronous processing.
17
+
18
+ **Simplicity**: A single `ocr()` function handles everything -
19
+ uploading, batch submission, polling for completion, and saving results
20
+ as markdown with extracted images. Process one PDF or an entire folder
21
+ with the same simple interface.
22
+
23
+ **Organized output**: Each PDF is automatically saved to its own folder
24
+ with pages as separate markdown files and images in an `img` subfolder,
25
+ making results easy to navigate and process further.
26
+
27
+ ## Installation
28
+
29
+ Install latest from the GitHub
30
+ [repository](https://github.com/franckalbinet/mistocr):
31
+
32
+ ``` sh
33
+ $ pip install git+https://github.com/franckalbinet/mistocr.git
34
+ ```
35
+
36
+ or from [pypi](https://pypi.org/project/mistocr/)
37
+
38
+ ``` sh
39
+ $ pip install mistocr
40
+ ```
41
+
42
+ ## How to use
43
+
44
+ ``` python
45
+ from mistocr.core import ocr
46
+ ```
47
+
48
+ - **Process a single PDF:**
49
+
50
+ <!-- -->
51
+
52
+ fname = 'files/test/attention-is-all-you-need.pdf'
53
+ result = ocr(fname)
54
+
55
+ ``` python
56
+ ```
57
+
58
+ files/test/md/attention-is-all-you-need:
59
+ img/ page_11.md page_14.md page_3.md page_6.md page_9.md
60
+ page_1.md page_12.md page_15.md page_4.md page_7.md
61
+ page_10.md page_13.md page_2.md page_5.md page_8.md
62
+
63
+ files/test/md/attention-is-all-you-need/img:
64
+ img-0.jpeg img-1.jpeg img-2.jpeg img-3.jpeg img-4.jpeg
65
+
66
+ - **Or process an entire folder:**
67
+
68
+ ``` python
69
+ results = ocr('files/test')
70
+ ```
71
+
72
+ ``` python
73
+ ```
74
+
75
+ files/test/md:
76
+ attention-is-all-you-need/ resnet/
77
+
78
+ files/test/md/attention-is-all-you-need:
79
+ img/ page_11.md page_14.md page_3.md page_6.md page_9.md
80
+ page_1.md page_12.md page_15.md page_4.md page_7.md
81
+ page_10.md page_13.md page_2.md page_5.md page_8.md
82
+
83
+ files/test/md/attention-is-all-you-need/img:
84
+ img-0.jpeg img-1.jpeg img-2.jpeg img-3.jpeg img-4.jpeg
85
+
86
+ files/test/md/resnet:
87
+ img/ page_10.md page_12.md page_3.md page_5.md page_7.md page_9.md
88
+ page_1.md page_11.md page_2.md page_4.md page_6.md page_8.md
89
+
90
+ files/test/md/resnet/img:
91
+ img-0.jpeg img-2.jpeg img-4.jpeg img-6.jpeg
92
+ img-1.jpeg img-3.jpeg img-5.jpeg
93
+
94
+ - **Customize the output:**
95
+
96
+ ``` python
97
+ results = ocr('files/test', out_dir='output', inc_img=False, poll_interval=5)
98
+ ```
99
+
100
+ **Parameters:**
101
+
102
+ - **`path`**: A single PDF file or folder containing multiple PDFs
103
+ - **`out_dir`**: Directory name for saving markdown output (default:
104
+ `'md'`)
105
+ - **`inc_img`**: Include extracted images in the output (default:
106
+ `True`)
107
+ - **`key`**: Your Mistral API key (uses `MISTRAL_API_KEY` environment
108
+ variable if not provided)
109
+ - **`poll_interval`**: Seconds between batch job status checks (default:
110
+ `2`)
111
+
112
+ **Returns:** List of paths to the generated markdown files
113
+
114
+ ## Developer Guide
115
+
116
+ If you are new to using `nbdev` here are some useful pointers to get you
117
+ started.
118
+
119
+ ### Install mistocr in Development mode
120
+
121
+ ``` sh
122
+ # make sure mistocr package is installed in development mode
123
+ $ pip install -e .
124
+
125
+ # make changes under nbs/ directory
126
+ # ...
127
+
128
+ # compile to have changes apply to mistocr
129
+ $ nbdev_prepare
130
+ ```
131
+
132
+ ### Documentation
133
+
134
+ Documentation can be found hosted on this GitHub
135
+ [repository](https://github.com/franckalbinet/mistocr)’s
136
+ [pages](https://franckalbinet.github.io/mistocr/). Additionally you can
137
+ find package manager specific guidelines on
138
+ [conda](https://anaconda.org/franckalbinet/mistocr) and
139
+ [pypi](https://pypi.org/project/mistocr/) respectively.
@@ -0,0 +1 @@
1
+ __version__ = "0.0.3"
@@ -0,0 +1,21 @@
1
+ # Autogenerated by nbdev
2
+
3
+ d = { 'settings': { 'branch': 'main',
4
+ 'doc_baseurl': '/mistocr',
5
+ 'doc_host': 'https://franckalbinet.github.io',
6
+ 'git_url': 'https://github.com/franckalbinet/mistocr',
7
+ 'lib_path': 'mistocr'},
8
+ 'syms': { 'mistocr.core': { 'mistocr.core._get_paths': ('core.html#_get_paths', 'mistocr/core.py'),
9
+ 'mistocr.core._prep_batch': ('core.html#_prep_batch', 'mistocr/core.py'),
10
+ 'mistocr.core._run_batch': ('core.html#_run_batch', 'mistocr/core.py'),
11
+ 'mistocr.core.create_batch_entry': ('core.html#create_batch_entry', 'mistocr/core.py'),
12
+ 'mistocr.core.download_results': ('core.html#download_results', 'mistocr/core.py'),
13
+ 'mistocr.core.get_api_key': ('core.html#get_api_key', 'mistocr/core.py'),
14
+ 'mistocr.core.ocr': ('core.html#ocr', 'mistocr/core.py'),
15
+ 'mistocr.core.prep_pdf_batch': ('core.html#prep_pdf_batch', 'mistocr/core.py'),
16
+ 'mistocr.core.save_images': ('core.html#save_images', 'mistocr/core.py'),
17
+ 'mistocr.core.save_page': ('core.html#save_page', 'mistocr/core.py'),
18
+ 'mistocr.core.save_pages': ('core.html#save_pages', 'mistocr/core.py'),
19
+ 'mistocr.core.submit_batch': ('core.html#submit_batch', 'mistocr/core.py'),
20
+ 'mistocr.core.upload_pdf': ('core.html#upload_pdf', 'mistocr/core.py'),
21
+ 'mistocr.core.wait_for_job': ('core.html#wait_for_job', 'mistocr/core.py')}}}
@@ -0,0 +1,179 @@
1
+ """Batch OCR for PDFs using Mistral API"""
2
+
3
+ # AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_core.ipynb.
4
+
5
+ # %% auto 0
6
+ __all__ = ['ocr_model', 'ocr_endpoint', 'get_api_key', 'upload_pdf', 'create_batch_entry', 'prep_pdf_batch', 'submit_batch',
7
+ 'wait_for_job', 'download_results', 'save_images', 'save_page', 'save_pages', 'ocr']
8
+
9
+ # %% ../nbs/00_core.ipynb 3
10
+ from fastcore.all import *
11
+ from dotenv import load_dotenv
12
+ import os, json, time, base64, tempfile
13
+ from io import BytesIO
14
+ from pathlib import Path
15
+ from PIL import Image
16
+ from mistralai import Mistral
17
+
18
+ # %% ../nbs/00_core.ipynb 6
19
+ load_dotenv()
20
+
21
+ # %% ../nbs/00_core.ipynb 7
22
+ def get_api_key(
23
+ key:str=None # Mistral API key
24
+ ):
25
+ "Get Mistral API key from parameter or environment"
26
+ key = key or os.getenv("MISTRAL_API_KEY")
27
+ if not key: raise ValueError("MISTRAL_API_KEY not found")
28
+ return key
29
+
30
+ # %% ../nbs/00_core.ipynb 8
31
+ ocr_model = "mistral-ocr-latest"
32
+ ocr_endpoint = "/v1/ocr"
33
+
34
+ # %% ../nbs/00_core.ipynb 11
35
+ def upload_pdf(
36
+ path:str, # Path to PDF file
37
+ key:str=None # Mistral API key
38
+ ) -> tuple[str, Mistral]: # Mistral pdf signed url and client
39
+ "Upload PDF to Mistral and return signed URL"
40
+ c = Mistral(api_key=get_api_key(key))
41
+ path = Path(path)
42
+ uploaded = c.files.upload(file=dict(file_name=path.stem, content=path.read_bytes()), purpose="ocr")
43
+ return c.files.get_signed_url(file_id=uploaded.id).url, c
44
+
45
+ # %% ../nbs/00_core.ipynb 16
46
+ def create_batch_entry(
47
+ path:str, # Path to PDF file,
48
+ url:str, # Mistral signed URL
49
+ cid:str=None, # Custom ID (by default using the file name without extention)
50
+ inc_img:bool=True # Include image in response
51
+ ) -> dict[str, str | dict[str, str | bool]]: # Batch entry dict
52
+ "Create a batch entry dict for OCR"
53
+ path = Path(path)
54
+ if not cid: cid = path.stem
55
+ return dict(custom_id=cid, body=dict(document=dict(type="document_url", document_url=url), include_image_base64=inc_img))
56
+
57
+ # %% ../nbs/00_core.ipynb 18
58
+ def prep_pdf_batch(
59
+ path:str, # Path to PDF file,
60
+ cid:str=None, # Custom ID (by default using the file name without extention)
61
+ inc_img:bool=True, # Include image in response
62
+ key=None # API key
63
+ ) -> dict: # Batch entry dict
64
+ "Upload PDF and create batch entry in one step"
65
+ url, c = upload_pdf(path, key)
66
+ return create_batch_entry(path, url, cid, inc_img), c
67
+
68
+ # %% ../nbs/00_core.ipynb 22
69
+ def submit_batch(
70
+ entries:list[dict], # List of batch entries,
71
+ c:Mistral=None, # Mistral client,
72
+ model:str=ocr_model, # Model name,
73
+ endpoint:str=ocr_endpoint # Endpoint name
74
+ ) -> dict: # Job dict
75
+ "Submit batch entries and return job"
76
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.jsonl', delete=True) as f:
77
+ for e in entries: f.write(json.dumps(e) + '\n')
78
+ f.flush()
79
+ batch_data = c.files.upload(file=dict(file_name="batch.jsonl", content=open(f.name, "rb")), purpose="batch")
80
+ return c.batch.jobs.create(input_files=[batch_data.id], model=model, endpoint=endpoint)
81
+
82
+ # %% ../nbs/00_core.ipynb 25
83
+ def wait_for_job(
84
+ job:dict, # Job dict,
85
+ c:Mistral=None, # Mistral client,
86
+ poll_interval:int=10 # Poll interval in seconds
87
+ ) -> dict: # Job dict (with status)
88
+ "Poll job until completion and return final job status"
89
+ while job.status in ["QUEUED", "RUNNING"]:
90
+ time.sleep(poll_interval)
91
+ job = c.batch.jobs.get(job_id=job.id)
92
+ return job
93
+
94
+ # %% ../nbs/00_core.ipynb 27
95
+ def download_results(
96
+ job:dict, # Job dict,
97
+ c:Mistral=None # Mistral client
98
+ ) -> list[dict]: # List of results
99
+ "Download and parse batch job results"
100
+ content = c.files.download(file_id=job.output_file).read().decode('utf-8')
101
+ return [json.loads(line) for line in content.strip().split('\n') if line]
102
+
103
+ # %% ../nbs/00_core.ipynb 32
104
+ def save_images(
105
+ page:dict, # Page dict,
106
+ img_dir:str='img' # Directory to save images
107
+ ) -> None:
108
+ "Save all images from a page to directory"
109
+ for img in page.get('images', []):
110
+ if img.get('image_base64') and img.get('id'):
111
+ img_bytes = base64.b64decode(img['image_base64'].split(',')[1])
112
+ Image.open(BytesIO(img_bytes)).save(img_dir / img['id'])
113
+
114
+ # %% ../nbs/00_core.ipynb 33
115
+ def save_page(
116
+ page:dict, # Page dict,
117
+ out_dir:str, # Directory to save page
118
+ img_dir:str='img' # Directory to save images
119
+ ) -> None:
120
+ "Save single page markdown and images"
121
+ (out_dir / f"page_{page['index']+1}.md").write_text(page['markdown'])
122
+ if page.get('images'):
123
+ img_dir.mkdir(exist_ok=True)
124
+ save_images(page, img_dir)
125
+
126
+ # %% ../nbs/00_core.ipynb 35
127
+ def save_pages(
128
+ ocr_resp:dict, # OCR response,
129
+ out_dir:str, # Directory to save pages,
130
+ cid:str # Custom ID
131
+ ) -> Path: # Output directory
132
+ "Save markdown pages and images from OCR response to output directory"
133
+ out_dir = Path(out_dir) / cid
134
+ out_dir.mkdir(parents=True, exist_ok=True)
135
+ img_dir = out_dir / 'img'
136
+ for page in ocr_resp['pages']: save_page(page, out_dir, img_dir)
137
+ return out_dir
138
+
139
+ # %% ../nbs/00_core.ipynb 41
140
+ def _get_paths(path:str) -> list[Path]:
141
+ "Get list of PDFs from file or folder"
142
+ path = Path(path)
143
+ if path.is_file(): return [path]
144
+ if path.is_dir():
145
+ pdfs = path.ls(file_exts='.pdf')
146
+ if not pdfs: raise ValueError(f"No PDFs found in {path}")
147
+ return pdfs
148
+ raise ValueError(f"Path not found: {path}")
149
+
150
+ # %% ../nbs/00_core.ipynb 42
151
+ def _prep_batch(pdfs:list[Path], inc_img:bool=True, key:str=None) -> tuple[list[dict], Mistral]:
152
+ "Prepare batch entries for list of PDFs"
153
+ entries, c = [], None
154
+ for pdf in pdfs:
155
+ entry, c = prep_pdf_batch(pdf, inc_img=inc_img, key=key)
156
+ entries.append(entry)
157
+ return entries, c
158
+
159
+ # %% ../nbs/00_core.ipynb 43
160
+ def _run_batch(entries:list[dict], c:Mistral, poll_interval:int=2) -> list[dict]:
161
+ "Submit batch, wait for completion, and download results"
162
+ job = submit_batch(entries, c)
163
+ job = wait_for_job(job, c, poll_interval)
164
+ if job.status != 'SUCCESS': raise Exception(f"Job failed with status: {job.status}")
165
+ return download_results(job, c)
166
+
167
+ # %% ../nbs/00_core.ipynb 44
168
+ def ocr(
169
+ path:str, # Path to PDF file or folder,
170
+ out_dir:str='md', # Directory to save markdown pages,
171
+ inc_img:bool=True, # Include image in response,
172
+ key:str=None, # API key,
173
+ poll_interval:int=2 # Poll interval in seconds
174
+ ) -> list[Path]: # List of output directories
175
+ "OCR a PDF file or folder of PDFs and save results"
176
+ pdfs = _get_paths(path)
177
+ entries, c = _prep_batch(pdfs, inc_img, key)
178
+ results = _run_batch(entries, c, poll_interval)
179
+ return L([save_pages(r['response']['body'], out_dir, r['custom_id']) for r in results])
@@ -0,0 +1,178 @@
1
+ Metadata-Version: 2.4
2
+ Name: mistocr
3
+ Version: 0.0.3
4
+ Summary: Simple batch OCR for PDFs using Mistral's state-of-the-art vision model
5
+ Home-page: https://github.com/franckalbinet/mistocr
6
+ Author: Solveit
7
+ Author-email: nobody@fast.ai
8
+ License: Apache Software License 2.0
9
+ Keywords: nbdev jupyter notebook python
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Natural Language :: English
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: License :: OSI Approved :: Apache Software License
18
+ Requires-Python: >=3.9
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: fastcore
22
+ Requires-Dist: mistralai
23
+ Requires-Dist: pillow
24
+ Requires-Dist: dotenv
25
+ Provides-Extra: dev
26
+ Dynamic: author
27
+ Dynamic: author-email
28
+ Dynamic: classifier
29
+ Dynamic: description
30
+ Dynamic: description-content-type
31
+ Dynamic: home-page
32
+ Dynamic: keywords
33
+ Dynamic: license
34
+ Dynamic: license-file
35
+ Dynamic: provides-extra
36
+ Dynamic: requires-dist
37
+ Dynamic: requires-python
38
+ Dynamic: summary
39
+
40
+ # mistocr
41
+
42
+
43
+ <!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
44
+
45
+ ## Why mistocr?
46
+
47
+ **Performance**: Mistral’s OCR delivers state-of-the-art accuracy on
48
+ complex documents including tables, charts, and multi-column layouts.
49
+
50
+ **Scale**: Process entire folders of PDFs in a single batch job. Upload
51
+ once, process asynchronously, and retrieve results when ready - perfect
52
+ for large document sets.
53
+
54
+ **Cost savings**: Batch OCR mode reduces costs from \$1/1000 pages to
55
+ \$0.50/1000 pages - a 50% reduction compared to synchronous processing.
56
+
57
+ **Simplicity**: A single `ocr()` function handles everything -
58
+ uploading, batch submission, polling for completion, and saving results
59
+ as markdown with extracted images. Process one PDF or an entire folder
60
+ with the same simple interface.
61
+
62
+ **Organized output**: Each PDF is automatically saved to its own folder
63
+ with pages as separate markdown files and images in an `img` subfolder,
64
+ making results easy to navigate and process further.
65
+
66
+ ## Installation
67
+
68
+ Install latest from the GitHub
69
+ [repository](https://github.com/franckalbinet/mistocr):
70
+
71
+ ``` sh
72
+ $ pip install git+https://github.com/franckalbinet/mistocr.git
73
+ ```
74
+
75
+ or from [pypi](https://pypi.org/project/mistocr/)
76
+
77
+ ``` sh
78
+ $ pip install mistocr
79
+ ```
80
+
81
+ ## How to use
82
+
83
+ ``` python
84
+ from mistocr.core import ocr
85
+ ```
86
+
87
+ - **Process a single PDF:**
88
+
89
+ <!-- -->
90
+
91
+ fname = 'files/test/attention-is-all-you-need.pdf'
92
+ result = ocr(fname)
93
+
94
+ ``` python
95
+ ```
96
+
97
+ files/test/md/attention-is-all-you-need:
98
+ img/ page_11.md page_14.md page_3.md page_6.md page_9.md
99
+ page_1.md page_12.md page_15.md page_4.md page_7.md
100
+ page_10.md page_13.md page_2.md page_5.md page_8.md
101
+
102
+ files/test/md/attention-is-all-you-need/img:
103
+ img-0.jpeg img-1.jpeg img-2.jpeg img-3.jpeg img-4.jpeg
104
+
105
+ - **Or process an entire folder:**
106
+
107
+ ``` python
108
+ results = ocr('files/test')
109
+ ```
110
+
111
+ ``` python
112
+ ```
113
+
114
+ files/test/md:
115
+ attention-is-all-you-need/ resnet/
116
+
117
+ files/test/md/attention-is-all-you-need:
118
+ img/ page_11.md page_14.md page_3.md page_6.md page_9.md
119
+ page_1.md page_12.md page_15.md page_4.md page_7.md
120
+ page_10.md page_13.md page_2.md page_5.md page_8.md
121
+
122
+ files/test/md/attention-is-all-you-need/img:
123
+ img-0.jpeg img-1.jpeg img-2.jpeg img-3.jpeg img-4.jpeg
124
+
125
+ files/test/md/resnet:
126
+ img/ page_10.md page_12.md page_3.md page_5.md page_7.md page_9.md
127
+ page_1.md page_11.md page_2.md page_4.md page_6.md page_8.md
128
+
129
+ files/test/md/resnet/img:
130
+ img-0.jpeg img-2.jpeg img-4.jpeg img-6.jpeg
131
+ img-1.jpeg img-3.jpeg img-5.jpeg
132
+
133
+ - **Customize the output:**
134
+
135
+ ``` python
136
+ results = ocr('files/test', out_dir='output', inc_img=False, poll_interval=5)
137
+ ```
138
+
139
+ **Parameters:**
140
+
141
+ - **`path`**: A single PDF file or folder containing multiple PDFs
142
+ - **`out_dir`**: Directory name for saving markdown output (default:
143
+ `'md'`)
144
+ - **`inc_img`**: Include extracted images in the output (default:
145
+ `True`)
146
+ - **`key`**: Your Mistral API key (uses `MISTRAL_API_KEY` environment
147
+ variable if not provided)
148
+ - **`poll_interval`**: Seconds between batch job status checks (default:
149
+ `2`)
150
+
151
+ **Returns:** List of paths to the generated markdown files
152
+
153
+ ## Developer Guide
154
+
155
+ If you are new to using `nbdev` here are some useful pointers to get you
156
+ started.
157
+
158
+ ### Install mistocr in Development mode
159
+
160
+ ``` sh
161
+ # make sure mistocr package is installed in development mode
162
+ $ pip install -e .
163
+
164
+ # make changes under nbs/ directory
165
+ # ...
166
+
167
+ # compile to have changes apply to mistocr
168
+ $ nbdev_prepare
169
+ ```
170
+
171
+ ### Documentation
172
+
173
+ Documentation can be found hosted on this GitHub
174
+ [repository](https://github.com/franckalbinet/mistocr)’s
175
+ [pages](https://franckalbinet.github.io/mistocr/). Additionally you can
176
+ find package manager specific guidelines on
177
+ [conda](https://anaconda.org/franckalbinet/mistocr) and
178
+ [pypi](https://pypi.org/project/mistocr/) respectively.
@@ -0,0 +1,16 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ settings.ini
6
+ setup.py
7
+ mistocr/__init__.py
8
+ mistocr/_modidx.py
9
+ mistocr/core.py
10
+ mistocr.egg-info/PKG-INFO
11
+ mistocr.egg-info/SOURCES.txt
12
+ mistocr.egg-info/dependency_links.txt
13
+ mistocr.egg-info/entry_points.txt
14
+ mistocr.egg-info/not-zip-safe
15
+ mistocr.egg-info/requires.txt
16
+ mistocr.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [nbdev]
2
+ mistocr = mistocr._modidx:d
@@ -0,0 +1,6 @@
1
+ fastcore
2
+ mistralai
3
+ pillow
4
+ dotenv
5
+
6
+ [dev]
@@ -0,0 +1 @@
1
+ mistocr
@@ -0,0 +1,3 @@
1
+ [build-system]
2
+ requires = ["setuptools>=64.0"]
3
+ build-backend = "setuptools.build_meta"
@@ -0,0 +1,39 @@
1
+ [DEFAULT]
2
+ repo = mistocr
3
+ lib_name = mistocr
4
+ version = 0.0.3
5
+ min_python = 3.9
6
+ license = apache2
7
+ black_formatting = False
8
+ doc_path = _docs
9
+ lib_path = mistocr
10
+ nbs_path = nbs
11
+ recursive = True
12
+ tst_flags = notest
13
+ put_version_in_init = True
14
+ update_pyproject = True
15
+ branch = main
16
+ custom_sidebar = False
17
+ doc_host = https://franckalbinet.github.io
18
+ doc_baseurl = /mistocr
19
+ git_url = https://github.com/franckalbinet/mistocr
20
+ title = mistocr
21
+ audience = Developers
22
+ author = Solveit
23
+ author_email = nobody@fast.ai
24
+ copyright = 2025 onwards, Solveit
25
+ description = Simple batch OCR for PDFs using Mistral's state-of-the-art vision model
26
+ keywords = nbdev jupyter notebook python
27
+ language = English
28
+ status = 3
29
+ user = franckalbinet
30
+ requirements = fastcore mistralai pillow dotenv
31
+ readme_nb = index.ipynb
32
+ allowed_metadata_keys =
33
+ allowed_cell_metadata_keys =
34
+ jupyter_hooks = False
35
+ clean_ids = True
36
+ clear_all = False
37
+ cell_number = True
38
+ skip_procs =
39
+
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
mistocr-0.0.3/setup.py ADDED
@@ -0,0 +1,64 @@
1
+ from pkg_resources import parse_version
2
+ from configparser import ConfigParser
3
+ import setuptools, shlex
4
+ assert parse_version(setuptools.__version__)>=parse_version('36.2')
5
+
6
+ # note: all settings are in settings.ini; edit there, not here
7
+ config = ConfigParser(delimiters=['='])
8
+ config.read('settings.ini', encoding='utf-8')
9
+ cfg = config['DEFAULT']
10
+
11
+ cfg_keys = 'version description keywords author author_email'.split()
12
+ expected = cfg_keys + "lib_name user branch license status min_python audience language".split()
13
+ for o in expected: assert o in cfg, "missing expected setting: {}".format(o)
14
+ setup_cfg = {o:cfg[o] for o in cfg_keys}
15
+
16
+ licenses = {
17
+ 'apache2': ('Apache Software License 2.0','OSI Approved :: Apache Software License'),
18
+ 'mit': ('MIT License', 'OSI Approved :: MIT License'),
19
+ 'gpl2': ('GNU General Public License v2', 'OSI Approved :: GNU General Public License v2 (GPLv2)'),
20
+ 'gpl3': ('GNU General Public License v3', 'OSI Approved :: GNU General Public License v3 (GPLv3)'),
21
+ 'bsd3': ('BSD License', 'OSI Approved :: BSD License'),
22
+ }
23
+ statuses = [ '1 - Planning', '2 - Pre-Alpha', '3 - Alpha',
24
+ '4 - Beta', '5 - Production/Stable', '6 - Mature', '7 - Inactive' ]
25
+ py_versions = '3.6 3.7 3.8 3.9 3.10 3.11 3.12'.split()
26
+
27
+ requirements = shlex.split(cfg.get('requirements', ''))
28
+ if cfg.get('pip_requirements'): requirements += shlex.split(cfg.get('pip_requirements', ''))
29
+ min_python = cfg['min_python']
30
+ lic = licenses.get(cfg['license'].lower(), (cfg['license'], None))
31
+ dev_requirements = (cfg.get('dev_requirements') or '').split()
32
+
33
+ package_data = dict()
34
+ pkg_data = cfg.get('package_data', None)
35
+ if pkg_data:
36
+ package_data[cfg['lib_name']] = pkg_data.split() # split as multiple files might be listed
37
+ # Add package data to setup_cfg for setuptools.setup(..., **setup_cfg)
38
+ setup_cfg['package_data'] = package_data
39
+
40
+ setuptools.setup(
41
+ name = cfg['lib_name'],
42
+ license = lic[0],
43
+ classifiers = [
44
+ 'Development Status :: ' + statuses[int(cfg['status'])],
45
+ 'Intended Audience :: ' + cfg['audience'].title(),
46
+ 'Natural Language :: ' + cfg['language'].title(),
47
+ ] + ['Programming Language :: Python :: '+o for o in py_versions[py_versions.index(min_python):]] + (['License :: ' + lic[1] ] if lic[1] else []),
48
+ url = cfg['git_url'],
49
+ packages = setuptools.find_packages(),
50
+ include_package_data = True,
51
+ install_requires = requirements,
52
+ extras_require={ 'dev': dev_requirements },
53
+ dependency_links = cfg.get('dep_links','').split(),
54
+ python_requires = '>=' + cfg['min_python'],
55
+ long_description = open('README.md', encoding='utf-8').read(),
56
+ long_description_content_type = 'text/markdown',
57
+ zip_safe = False,
58
+ entry_points = {
59
+ 'console_scripts': cfg.get('console_scripts','').split(),
60
+ 'nbdev': [f'{cfg.get("lib_path")}={cfg.get("lib_path")}._modidx:d']
61
+ },
62
+ **setup_cfg)
63
+
64
+