mistocr 0.1.6__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.1.6/LICENSE +201 -0
- mistocr-0.1.6/MANIFEST.in +5 -0
- mistocr-0.1.6/PKG-INFO +183 -0
- mistocr-0.1.6/README.md +143 -0
- mistocr-0.1.6/mistocr/__init__.py +1 -0
- mistocr-0.1.6/mistocr/_modidx.py +31 -0
- mistocr-0.1.6/mistocr/core.py +186 -0
- mistocr-0.1.6/mistocr/refine.py +143 -0
- mistocr-0.1.6/mistocr.egg-info/PKG-INFO +183 -0
- mistocr-0.1.6/mistocr.egg-info/SOURCES.txt +17 -0
- mistocr-0.1.6/mistocr.egg-info/dependency_links.txt +1 -0
- mistocr-0.1.6/mistocr.egg-info/entry_points.txt +2 -0
- mistocr-0.1.6/mistocr.egg-info/not-zip-safe +1 -0
- mistocr-0.1.6/mistocr.egg-info/requires.txt +7 -0
- mistocr-0.1.6/mistocr.egg-info/top_level.txt +1 -0
- mistocr-0.1.6/pyproject.toml +3 -0
- mistocr-0.1.6/settings.ini +39 -0
- mistocr-0.1.6/setup.cfg +4 -0
- mistocr-0.1.6/setup.py +64 -0
mistocr-0.1.6/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.
|
mistocr-0.1.6/PKG-INFO
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mistocr
|
|
3
|
+
Version: 0.1.6
|
|
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
|
+
Requires-Dist: lisette
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Dynamic: author
|
|
28
|
+
Dynamic: author-email
|
|
29
|
+
Dynamic: classifier
|
|
30
|
+
Dynamic: description
|
|
31
|
+
Dynamic: description-content-type
|
|
32
|
+
Dynamic: home-page
|
|
33
|
+
Dynamic: keywords
|
|
34
|
+
Dynamic: license
|
|
35
|
+
Dynamic: license-file
|
|
36
|
+
Dynamic: provides-extra
|
|
37
|
+
Dynamic: requires-dist
|
|
38
|
+
Dynamic: requires-python
|
|
39
|
+
Dynamic: summary
|
|
40
|
+
|
|
41
|
+
# mistocr
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
|
|
45
|
+
|
|
46
|
+
## Why mistocr?
|
|
47
|
+
|
|
48
|
+
**Performance**: Mistral’s OCR delivers state-of-the-art accuracy on
|
|
49
|
+
complex documents including tables, charts, and multi-column layouts.
|
|
50
|
+
|
|
51
|
+
**Scale**: Process entire folders of PDFs in a single batch job. Upload
|
|
52
|
+
once, process asynchronously, and retrieve results when ready - perfect
|
|
53
|
+
for large document sets.
|
|
54
|
+
|
|
55
|
+
**Cost savings**: Batch OCR mode reduces costs from \$1/1000 pages to
|
|
56
|
+
\$0.50/1000 pages - a 50% reduction compared to synchronous processing.
|
|
57
|
+
|
|
58
|
+
**Simplicity**: A single
|
|
59
|
+
[`ocr()`](https://franckalbinet.github.io/mistocr/core.html#ocr)
|
|
60
|
+
function handles everything - uploading, batch submission, polling for
|
|
61
|
+
completion, and saving results as markdown with extracted images.
|
|
62
|
+
Process one PDF or an entire folder with the same simple interface.
|
|
63
|
+
|
|
64
|
+
**Organized output**: Each PDF is automatically saved to its own folder
|
|
65
|
+
with pages as separate markdown files and images in an `img` subfolder,
|
|
66
|
+
making results easy to navigate and process further.
|
|
67
|
+
|
|
68
|
+
## Installation
|
|
69
|
+
|
|
70
|
+
Install latest from the GitHub
|
|
71
|
+
[repository](https://github.com/franckalbinet/mistocr):
|
|
72
|
+
|
|
73
|
+
``` sh
|
|
74
|
+
$ pip install git+https://github.com/franckalbinet/mistocr.git
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
or from [pypi](https://pypi.org/project/mistocr/)
|
|
78
|
+
|
|
79
|
+
``` sh
|
|
80
|
+
$ pip install mistocr
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## How to use
|
|
84
|
+
|
|
85
|
+
### Basic usage
|
|
86
|
+
|
|
87
|
+
Process a single PDF:
|
|
88
|
+
|
|
89
|
+
``` python
|
|
90
|
+
from mistocr.core import ocr
|
|
91
|
+
|
|
92
|
+
fname = 'files/test/attention-is-all-you-need.pdf'
|
|
93
|
+
result = ocr(fname)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Or process an entire folder:
|
|
97
|
+
|
|
98
|
+
``` python
|
|
99
|
+
results = ocr('files/test')
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Output structure
|
|
103
|
+
|
|
104
|
+
Each PDF is saved to its own folder with pages as separate markdown
|
|
105
|
+
files and images in an `img` subfolder:
|
|
106
|
+
|
|
107
|
+
files/test/md/
|
|
108
|
+
├── attention-is-all-you-need/
|
|
109
|
+
│ ├── img/
|
|
110
|
+
│ │ ├── img-0.jpeg
|
|
111
|
+
│ │ ├── img-1.jpeg
|
|
112
|
+
│ │ └── ...
|
|
113
|
+
│ ├── page_1.md
|
|
114
|
+
│ ├── page_2.md
|
|
115
|
+
│ └── ...
|
|
116
|
+
└── resnet/
|
|
117
|
+
├── img/
|
|
118
|
+
└── ...
|
|
119
|
+
|
|
120
|
+
### Reading results
|
|
121
|
+
|
|
122
|
+
Read all pages from a processed PDF:
|
|
123
|
+
|
|
124
|
+
``` python
|
|
125
|
+
from mistocr.core import read_pgs
|
|
126
|
+
|
|
127
|
+
text = read_pgs('files/test/md/attention-is-all-you-need')
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Or read a specific page:
|
|
131
|
+
|
|
132
|
+
``` python
|
|
133
|
+
text = read_pgs('files/test/md/attention-is-all-you-need', 10)
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### Customization
|
|
137
|
+
|
|
138
|
+
Customize output directory, image inclusion, and polling interval:
|
|
139
|
+
|
|
140
|
+
``` python
|
|
141
|
+
results = ocr('files/test', out_dir='output', inc_img=False, poll_interval=5)
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
**Parameters:**
|
|
145
|
+
|
|
146
|
+
- **`path`**: A single PDF file or folder containing multiple PDFs
|
|
147
|
+
- **`out_dir`**: Directory name for saving markdown output (default:
|
|
148
|
+
`'md'`)
|
|
149
|
+
- **`inc_img`**: Include extracted images in the output (default:
|
|
150
|
+
`True`)
|
|
151
|
+
- **`key`**: Your Mistral API key (uses `MISTRAL_API_KEY` environment
|
|
152
|
+
variable if not provided)
|
|
153
|
+
- **`poll_interval`**: Seconds between batch job status checks (default:
|
|
154
|
+
`2`)
|
|
155
|
+
|
|
156
|
+
**Returns:** List of paths to the generated markdown files
|
|
157
|
+
|
|
158
|
+
## Developer Guide
|
|
159
|
+
|
|
160
|
+
If you are new to using `nbdev` here are some useful pointers to get you
|
|
161
|
+
started.
|
|
162
|
+
|
|
163
|
+
### Install mistocr in Development mode
|
|
164
|
+
|
|
165
|
+
``` sh
|
|
166
|
+
# make sure mistocr package is installed in development mode
|
|
167
|
+
$ pip install -e .
|
|
168
|
+
|
|
169
|
+
# make changes under nbs/ directory
|
|
170
|
+
# ...
|
|
171
|
+
|
|
172
|
+
# compile to have changes apply to mistocr
|
|
173
|
+
$ nbdev_prepare
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
### Documentation
|
|
177
|
+
|
|
178
|
+
Documentation can be found hosted on this GitHub
|
|
179
|
+
[repository](https://github.com/franckalbinet/mistocr)’s
|
|
180
|
+
[pages](https://franckalbinet.github.io/mistocr/). Additionally you can
|
|
181
|
+
find package manager specific guidelines on
|
|
182
|
+
[conda](https://anaconda.org/franckalbinet/mistocr) and
|
|
183
|
+
[pypi](https://pypi.org/project/mistocr/) respectively.
|
mistocr-0.1.6/README.md
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
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
|
|
19
|
+
[`ocr()`](https://franckalbinet.github.io/mistocr/core.html#ocr)
|
|
20
|
+
function handles everything - uploading, batch submission, polling for
|
|
21
|
+
completion, and saving results as markdown with extracted images.
|
|
22
|
+
Process one PDF or an entire folder with the same simple interface.
|
|
23
|
+
|
|
24
|
+
**Organized output**: Each PDF is automatically saved to its own folder
|
|
25
|
+
with pages as separate markdown files and images in an `img` subfolder,
|
|
26
|
+
making results easy to navigate and process further.
|
|
27
|
+
|
|
28
|
+
## Installation
|
|
29
|
+
|
|
30
|
+
Install latest from the GitHub
|
|
31
|
+
[repository](https://github.com/franckalbinet/mistocr):
|
|
32
|
+
|
|
33
|
+
``` sh
|
|
34
|
+
$ pip install git+https://github.com/franckalbinet/mistocr.git
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
or from [pypi](https://pypi.org/project/mistocr/)
|
|
38
|
+
|
|
39
|
+
``` sh
|
|
40
|
+
$ pip install mistocr
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## How to use
|
|
44
|
+
|
|
45
|
+
### Basic usage
|
|
46
|
+
|
|
47
|
+
Process a single PDF:
|
|
48
|
+
|
|
49
|
+
``` python
|
|
50
|
+
from mistocr.core import ocr
|
|
51
|
+
|
|
52
|
+
fname = 'files/test/attention-is-all-you-need.pdf'
|
|
53
|
+
result = ocr(fname)
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Or process an entire folder:
|
|
57
|
+
|
|
58
|
+
``` python
|
|
59
|
+
results = ocr('files/test')
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### Output structure
|
|
63
|
+
|
|
64
|
+
Each PDF is saved to its own folder with pages as separate markdown
|
|
65
|
+
files and images in an `img` subfolder:
|
|
66
|
+
|
|
67
|
+
files/test/md/
|
|
68
|
+
├── attention-is-all-you-need/
|
|
69
|
+
│ ├── img/
|
|
70
|
+
│ │ ├── img-0.jpeg
|
|
71
|
+
│ │ ├── img-1.jpeg
|
|
72
|
+
│ │ └── ...
|
|
73
|
+
│ ├── page_1.md
|
|
74
|
+
│ ├── page_2.md
|
|
75
|
+
│ └── ...
|
|
76
|
+
└── resnet/
|
|
77
|
+
├── img/
|
|
78
|
+
└── ...
|
|
79
|
+
|
|
80
|
+
### Reading results
|
|
81
|
+
|
|
82
|
+
Read all pages from a processed PDF:
|
|
83
|
+
|
|
84
|
+
``` python
|
|
85
|
+
from mistocr.core import read_pgs
|
|
86
|
+
|
|
87
|
+
text = read_pgs('files/test/md/attention-is-all-you-need')
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Or read a specific page:
|
|
91
|
+
|
|
92
|
+
``` python
|
|
93
|
+
text = read_pgs('files/test/md/attention-is-all-you-need', 10)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
### Customization
|
|
97
|
+
|
|
98
|
+
Customize output directory, image inclusion, and polling interval:
|
|
99
|
+
|
|
100
|
+
``` python
|
|
101
|
+
results = ocr('files/test', out_dir='output', inc_img=False, poll_interval=5)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
**Parameters:**
|
|
105
|
+
|
|
106
|
+
- **`path`**: A single PDF file or folder containing multiple PDFs
|
|
107
|
+
- **`out_dir`**: Directory name for saving markdown output (default:
|
|
108
|
+
`'md'`)
|
|
109
|
+
- **`inc_img`**: Include extracted images in the output (default:
|
|
110
|
+
`True`)
|
|
111
|
+
- **`key`**: Your Mistral API key (uses `MISTRAL_API_KEY` environment
|
|
112
|
+
variable if not provided)
|
|
113
|
+
- **`poll_interval`**: Seconds between batch job status checks (default:
|
|
114
|
+
`2`)
|
|
115
|
+
|
|
116
|
+
**Returns:** List of paths to the generated markdown files
|
|
117
|
+
|
|
118
|
+
## Developer Guide
|
|
119
|
+
|
|
120
|
+
If you are new to using `nbdev` here are some useful pointers to get you
|
|
121
|
+
started.
|
|
122
|
+
|
|
123
|
+
### Install mistocr in Development mode
|
|
124
|
+
|
|
125
|
+
``` sh
|
|
126
|
+
# make sure mistocr package is installed in development mode
|
|
127
|
+
$ pip install -e .
|
|
128
|
+
|
|
129
|
+
# make changes under nbs/ directory
|
|
130
|
+
# ...
|
|
131
|
+
|
|
132
|
+
# compile to have changes apply to mistocr
|
|
133
|
+
$ nbdev_prepare
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### Documentation
|
|
137
|
+
|
|
138
|
+
Documentation can be found hosted on this GitHub
|
|
139
|
+
[repository](https://github.com/franckalbinet/mistocr)’s
|
|
140
|
+
[pages](https://franckalbinet.github.io/mistocr/). Additionally you can
|
|
141
|
+
find package manager specific guidelines on
|
|
142
|
+
[conda](https://anaconda.org/franckalbinet/mistocr) and
|
|
143
|
+
[pypi](https://pypi.org/project/mistocr/) respectively.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.6"
|
|
@@ -0,0 +1,31 @@
|
|
|
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.read_pgs': ('core.html#read_pgs', 'mistocr/core.py'),
|
|
17
|
+
'mistocr.core.save_images': ('core.html#save_images', 'mistocr/core.py'),
|
|
18
|
+
'mistocr.core.save_page': ('core.html#save_page', 'mistocr/core.py'),
|
|
19
|
+
'mistocr.core.save_pages': ('core.html#save_pages', 'mistocr/core.py'),
|
|
20
|
+
'mistocr.core.submit_batch': ('core.html#submit_batch', 'mistocr/core.py'),
|
|
21
|
+
'mistocr.core.upload_pdf': ('core.html#upload_pdf', 'mistocr/core.py'),
|
|
22
|
+
'mistocr.core.wait_for_job': ('core.html#wait_for_job', 'mistocr/core.py')},
|
|
23
|
+
'mistocr.refine': { 'mistocr.refine.HeadingCorrections': ('refine.html#headingcorrections', 'mistocr/refine.py'),
|
|
24
|
+
'mistocr.refine.add_pg_hdgs': ('refine.html#add_pg_hdgs', 'mistocr/refine.py'),
|
|
25
|
+
'mistocr.refine.apply_hdg_fixes': ('refine.html#apply_hdg_fixes', 'mistocr/refine.py'),
|
|
26
|
+
'mistocr.refine.fix_hdg_hierarchy': ('refine.html#fix_hdg_hierarchy', 'mistocr/refine.py'),
|
|
27
|
+
'mistocr.refine.fix_md_hdgs': ('refine.html#fix_md_hdgs', 'mistocr/refine.py'),
|
|
28
|
+
'mistocr.refine.fmt_hdgs_idx': ('refine.html#fmt_hdgs_idx', 'mistocr/refine.py'),
|
|
29
|
+
'mistocr.refine.get_hdgs': ('refine.html#get_hdgs', 'mistocr/refine.py'),
|
|
30
|
+
'mistocr.refine.mk_fixes_lut': ('refine.html#mk_fixes_lut', 'mistocr/refine.py'),
|
|
31
|
+
'mistocr.refine.read_pgs_pg': ('refine.html#read_pgs_pg', 'mistocr/refine.py')}}}
|
|
@@ -0,0 +1,186 @@
|
|
|
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', 'read_pgs']
|
|
8
|
+
|
|
9
|
+
# %% ../nbs/00_core.ipynb 3
|
|
10
|
+
from fastcore.all import *
|
|
11
|
+
import os, re, json, time, base64, tempfile, logging
|
|
12
|
+
from io import BytesIO
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from PIL import Image
|
|
15
|
+
from mistralai import Mistral
|
|
16
|
+
|
|
17
|
+
# %% ../nbs/00_core.ipynb 6
|
|
18
|
+
def get_api_key(
|
|
19
|
+
key:str=None # Mistral API key
|
|
20
|
+
):
|
|
21
|
+
"Get Mistral API key from parameter or environment"
|
|
22
|
+
key = key or os.getenv("MISTRAL_API_KEY")
|
|
23
|
+
if not key: raise ValueError("MISTRAL_API_KEY not found")
|
|
24
|
+
return key
|
|
25
|
+
|
|
26
|
+
# %% ../nbs/00_core.ipynb 7
|
|
27
|
+
ocr_model = "mistral-ocr-latest"
|
|
28
|
+
ocr_endpoint = "/v1/ocr"
|
|
29
|
+
|
|
30
|
+
# %% ../nbs/00_core.ipynb 10
|
|
31
|
+
def upload_pdf(
|
|
32
|
+
path:str, # Path to PDF file
|
|
33
|
+
key:str=None # Mistral API key
|
|
34
|
+
) -> tuple[str, Mistral]: # Mistral pdf signed url and client
|
|
35
|
+
"Upload PDF to Mistral and return signed URL"
|
|
36
|
+
c = Mistral(api_key=get_api_key(key))
|
|
37
|
+
path = Path(path)
|
|
38
|
+
uploaded = c.files.upload(file=dict(file_name=path.stem, content=path.read_bytes()), purpose="ocr")
|
|
39
|
+
return c.files.get_signed_url(file_id=uploaded.id).url, c
|
|
40
|
+
|
|
41
|
+
# %% ../nbs/00_core.ipynb 15
|
|
42
|
+
def create_batch_entry(
|
|
43
|
+
path:str, # Path to PDF file,
|
|
44
|
+
url:str, # Mistral signed URL
|
|
45
|
+
cid:str=None, # Custom ID (by default using the file name without extension)
|
|
46
|
+
inc_img:bool=True # Include image in response
|
|
47
|
+
) -> dict[str, str | dict[str, str | bool]]: # Batch entry dict
|
|
48
|
+
"Create a batch entry dict for OCR"
|
|
49
|
+
path = Path(path)
|
|
50
|
+
if not cid: cid = path.stem
|
|
51
|
+
return dict(custom_id=cid, body=dict(document=dict(type="document_url", document_url=url), include_image_base64=inc_img))
|
|
52
|
+
|
|
53
|
+
# %% ../nbs/00_core.ipynb 17
|
|
54
|
+
def prep_pdf_batch(
|
|
55
|
+
path:str, # Path to PDF file,
|
|
56
|
+
cid:str=None, # Custom ID (by default using the file name without extention)
|
|
57
|
+
inc_img:bool=True, # Include image in response
|
|
58
|
+
key=None # API key
|
|
59
|
+
) -> dict: # Batch entry dict
|
|
60
|
+
"Upload PDF and create batch entry in one step"
|
|
61
|
+
url, c = upload_pdf(path, key)
|
|
62
|
+
return create_batch_entry(path, url, cid, inc_img), c
|
|
63
|
+
|
|
64
|
+
# %% ../nbs/00_core.ipynb 21
|
|
65
|
+
def submit_batch(
|
|
66
|
+
entries:list[dict], # List of batch entries,
|
|
67
|
+
c:Mistral=None, # Mistral client,
|
|
68
|
+
model:str=ocr_model, # Model name,
|
|
69
|
+
endpoint:str=ocr_endpoint # Endpoint name
|
|
70
|
+
) -> dict: # Job dict
|
|
71
|
+
"Submit batch entries and return job"
|
|
72
|
+
with tempfile.NamedTemporaryFile(mode='w', suffix='.jsonl', delete=True) as f:
|
|
73
|
+
for e in entries: f.write(json.dumps(e) + '\n')
|
|
74
|
+
f.flush()
|
|
75
|
+
batch_data = c.files.upload(file=dict(file_name="batch.jsonl", content=open(f.name, "rb")), purpose="batch")
|
|
76
|
+
return c.batch.jobs.create(input_files=[batch_data.id], model=model, endpoint=endpoint)
|
|
77
|
+
|
|
78
|
+
# %% ../nbs/00_core.ipynb 24
|
|
79
|
+
def wait_for_job(
|
|
80
|
+
job:dict, # Job dict,
|
|
81
|
+
c:Mistral=None, # Mistral client,
|
|
82
|
+
poll_interval:int=10 # Poll interval in seconds
|
|
83
|
+
) -> dict: # Job dict (with status)
|
|
84
|
+
"Poll job until completion and return final job status"
|
|
85
|
+
while job.status in ["QUEUED", "RUNNING"]:
|
|
86
|
+
time.sleep(poll_interval)
|
|
87
|
+
job = c.batch.jobs.get(job_id=job.id)
|
|
88
|
+
return job
|
|
89
|
+
|
|
90
|
+
# %% ../nbs/00_core.ipynb 26
|
|
91
|
+
def download_results(
|
|
92
|
+
job:dict, # Job dict,
|
|
93
|
+
c:Mistral=None # Mistral client
|
|
94
|
+
) -> list[dict]: # List of results
|
|
95
|
+
"Download and parse batch job results"
|
|
96
|
+
content = c.files.download(file_id=job.output_file).read().decode('utf-8')
|
|
97
|
+
return [json.loads(line) for line in content.strip().split('\n') if line]
|
|
98
|
+
|
|
99
|
+
# %% ../nbs/00_core.ipynb 31
|
|
100
|
+
def save_images(
|
|
101
|
+
page:dict, # Page dict,
|
|
102
|
+
img_dir:str='img' # Directory to save images
|
|
103
|
+
) -> None:
|
|
104
|
+
"Save all images from a page to directory"
|
|
105
|
+
for img in page.get('images', []):
|
|
106
|
+
if img.get('image_base64') and img.get('id'):
|
|
107
|
+
img_bytes = base64.b64decode(img['image_base64'].split(',')[1])
|
|
108
|
+
Image.open(BytesIO(img_bytes)).save(img_dir / img['id'])
|
|
109
|
+
|
|
110
|
+
# %% ../nbs/00_core.ipynb 32
|
|
111
|
+
def save_page(
|
|
112
|
+
page:dict, # Page dict,
|
|
113
|
+
dst:str, # Directory to save page
|
|
114
|
+
img_dir:str='img' # Directory to save images
|
|
115
|
+
) -> None:
|
|
116
|
+
"Save single page markdown and images"
|
|
117
|
+
(dst / f"page_{page['index']+1}.md").write_text(page['markdown'])
|
|
118
|
+
if page.get('images'):
|
|
119
|
+
img_dir.mkdir(exist_ok=True)
|
|
120
|
+
save_images(page, img_dir)
|
|
121
|
+
|
|
122
|
+
# %% ../nbs/00_core.ipynb 34
|
|
123
|
+
def save_pages(
|
|
124
|
+
ocr_resp:dict, # OCR response,
|
|
125
|
+
dst:str, # Directory to save pages,
|
|
126
|
+
cid:str # Custom ID
|
|
127
|
+
) -> Path: # Output directory
|
|
128
|
+
"Save markdown pages and images from OCR response to output directory"
|
|
129
|
+
dst = Path(dst) / cid
|
|
130
|
+
dst.mkdir(parents=True, exist_ok=True)
|
|
131
|
+
img_dir = dst / 'img'
|
|
132
|
+
for page in ocr_resp['pages']: save_page(page, dst, img_dir)
|
|
133
|
+
return dst
|
|
134
|
+
|
|
135
|
+
# %% ../nbs/00_core.ipynb 40
|
|
136
|
+
def _get_paths(path:str) -> list[Path]:
|
|
137
|
+
"Get list of PDFs from file or folder"
|
|
138
|
+
path = Path(path)
|
|
139
|
+
if path.is_file(): return [path]
|
|
140
|
+
if path.is_dir():
|
|
141
|
+
pdfs = path.ls(file_exts='.pdf')
|
|
142
|
+
if not pdfs: raise ValueError(f"No PDFs found in {path}")
|
|
143
|
+
return pdfs
|
|
144
|
+
raise ValueError(f"Path not found: {path}")
|
|
145
|
+
|
|
146
|
+
# %% ../nbs/00_core.ipynb 41
|
|
147
|
+
def _prep_batch(pdfs:list[Path], inc_img:bool=True, key:str=None) -> tuple[list[dict], Mistral]:
|
|
148
|
+
"Prepare batch entries for list of PDFs"
|
|
149
|
+
entries, c = [], None
|
|
150
|
+
for pdf in pdfs:
|
|
151
|
+
entry, c = prep_pdf_batch(pdf, inc_img=inc_img, key=key)
|
|
152
|
+
entries.append(entry)
|
|
153
|
+
return entries, c
|
|
154
|
+
|
|
155
|
+
# %% ../nbs/00_core.ipynb 42
|
|
156
|
+
def _run_batch(entries:list[dict], c:Mistral, poll_interval:int=2) -> list[dict]:
|
|
157
|
+
"Submit batch, wait for completion, and download results"
|
|
158
|
+
job = submit_batch(entries, c)
|
|
159
|
+
job = wait_for_job(job, c, poll_interval)
|
|
160
|
+
if job.status != 'SUCCESS': raise Exception(f"Job failed with status: {job.status}")
|
|
161
|
+
return download_results(job, c)
|
|
162
|
+
|
|
163
|
+
# %% ../nbs/00_core.ipynb 43
|
|
164
|
+
def ocr(
|
|
165
|
+
path:str, # Path to PDF file or folder,
|
|
166
|
+
dst:str='md', # Directory to save markdown pages,
|
|
167
|
+
inc_img:bool=True, # Include image in response,
|
|
168
|
+
key:str=None, # API key,
|
|
169
|
+
poll_interval:int=2 # Poll interval in seconds
|
|
170
|
+
) -> list[Path]: # List of output directories
|
|
171
|
+
"OCR a PDF file or folder of PDFs and save results"
|
|
172
|
+
pdfs = _get_paths(path)
|
|
173
|
+
entries, c = _prep_batch(pdfs, inc_img, key)
|
|
174
|
+
results = _run_batch(entries, c, poll_interval)
|
|
175
|
+
return L([save_pages(r['response']['body'], dst, r['custom_id']) for r in results])
|
|
176
|
+
|
|
177
|
+
# %% ../nbs/00_core.ipynb 48
|
|
178
|
+
def read_pgs(
|
|
179
|
+
path:str, # OCR output directory,
|
|
180
|
+
join:bool=True # Join pages into single string
|
|
181
|
+
) -> str|list[str]: # Joined string or list of page contents
|
|
182
|
+
"Read specific page or all pages from OCR output directory"
|
|
183
|
+
path = Path(path)
|
|
184
|
+
pgs = sorted(path.glob('page_*.md'), key=lambda p: int(p.stem.split('_')[1]))
|
|
185
|
+
contents = L([p.read_text() for p in pgs])
|
|
186
|
+
return '\n\n'.join(contents) if join else contents
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Postprocess markdown files by fixing heading hierarchy and describint images"""
|
|
2
|
+
|
|
3
|
+
# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_refine.ipynb.
|
|
4
|
+
|
|
5
|
+
# %% auto 0
|
|
6
|
+
__all__ = ['prompt_fix_hdgs', 'get_hdgs', 'add_pg_hdgs', 'read_pgs_pg', 'fmt_hdgs_idx', 'HeadingCorrections', 'fix_hdg_hierarchy',
|
|
7
|
+
'mk_fixes_lut', 'apply_hdg_fixes', 'fix_md_hdgs']
|
|
8
|
+
|
|
9
|
+
# %% ../nbs/01_refine.ipynb 3
|
|
10
|
+
from fastcore.all import *
|
|
11
|
+
from .core import read_pgs
|
|
12
|
+
from re import sub, findall, MULTILINE
|
|
13
|
+
from pydantic import BaseModel
|
|
14
|
+
from lisette.core import completion
|
|
15
|
+
from typing import Callable
|
|
16
|
+
import os
|
|
17
|
+
import json
|
|
18
|
+
|
|
19
|
+
# %% ../nbs/01_refine.ipynb 7
|
|
20
|
+
def get_hdgs(
|
|
21
|
+
md:str # Markdown file string
|
|
22
|
+
) -> L: # L of strings
|
|
23
|
+
"Return the markdown headings"
|
|
24
|
+
# Sanitize removing '#' in python snippet if any
|
|
25
|
+
md = sub(r'```[\s\S]*?```', '', md)
|
|
26
|
+
return L(findall(r'^#{1,6} .+$', md, MULTILINE))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
# %% ../nbs/01_refine.ipynb 8
|
|
31
|
+
def add_pg_hdgs(
|
|
32
|
+
md:str, # Markdown file string,
|
|
33
|
+
n:int # Page number
|
|
34
|
+
) -> str: # Markdown file string
|
|
35
|
+
"Add page number to all headings in page markdown"
|
|
36
|
+
md = sub(r'```[\s\S]*?```', '', md)
|
|
37
|
+
def repl(m): return m.group(0) + f' ... page {n}'
|
|
38
|
+
return sub(r'^#{1,6} .+$', repl, md, flags=MULTILINE)
|
|
39
|
+
|
|
40
|
+
# %% ../nbs/01_refine.ipynb 12
|
|
41
|
+
def read_pgs_pg(
|
|
42
|
+
path:str # Path to the markdown file
|
|
43
|
+
) -> L: # List of markdown pages
|
|
44
|
+
"Read all pages of a markdown file and add page numbers to all headings"
|
|
45
|
+
pgs = read_pgs(path, join=False)
|
|
46
|
+
return L([add_pg_hdgs(pg, n) for n, pg in enumerate(pgs, 1)]).concat()
|
|
47
|
+
|
|
48
|
+
# %% ../nbs/01_refine.ipynb 15
|
|
49
|
+
def fmt_hdgs_idx(
|
|
50
|
+
hdgs: list[str] # List of markdown headings
|
|
51
|
+
) -> str: # Formatted string with index
|
|
52
|
+
"Format the headings with index"
|
|
53
|
+
return '\n'.join(f"{i}. {h}" for i, h in enumerate(hdgs))
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# %% ../nbs/01_refine.ipynb 18
|
|
57
|
+
class HeadingCorrections(BaseModel):
|
|
58
|
+
corrections: dict[int, str] # index → corrected heading
|
|
59
|
+
|
|
60
|
+
# %% ../nbs/01_refine.ipynb 20
|
|
61
|
+
prompt_fix_hdgs = """Fix markdown heading hierarchy errors while preserving the document's intended structure.
|
|
62
|
+
|
|
63
|
+
INPUT FORMAT: Each heading is prefixed with its index number (e.g., "0. # Title ... page 1")
|
|
64
|
+
|
|
65
|
+
RULES - Apply these fixes in order:
|
|
66
|
+
|
|
67
|
+
1. **Single H1 rule**: Documents must have exactly ONE # heading (typically the document title at the top)
|
|
68
|
+
- If index 0 is already #, then all subsequent headings (index 1+) must be ## or deeper
|
|
69
|
+
- If no H1 exists, the first major heading should be #, and all others ## or deeper
|
|
70
|
+
- NO exceptions: appendices, references, and all sections are ## or deeper after the title
|
|
71
|
+
|
|
72
|
+
2. **Infer depth from numbering patterns**: If headings contain section numbers, deeper nesting means deeper heading level
|
|
73
|
+
- Parent section (e.g., "1", "2", "A") should be shallower than child (e.g., "1.1", "2.a", "A.1")
|
|
74
|
+
- Child section should be one # deeper than parent
|
|
75
|
+
- Works with any numbering: "1/1.1/1.1.1", "A/A.1/A.1.a", "I/I.A/I.A.1", etc.
|
|
76
|
+
|
|
77
|
+
3. **Level jumps**: Headings can only increase by one # at a time when moving deeper
|
|
78
|
+
- Wrong: ## Section → ##### Subsection
|
|
79
|
+
- Fixed: ## Section → ### Subsection
|
|
80
|
+
|
|
81
|
+
4. **Decreasing levels is OK**: Moving back up the hierarchy (### to ##) is valid for new sections
|
|
82
|
+
|
|
83
|
+
OUTPUT: Return a Python dictionary mapping index to corrected heading (without the index prefix).
|
|
84
|
+
IMPORTANT: Preserve the " ... page N" suffix in all corrected headings.
|
|
85
|
+
Only include entries that need changes.
|
|
86
|
+
|
|
87
|
+
Headings to analyze:
|
|
88
|
+
{headings_list}
|
|
89
|
+
"""
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# %% ../nbs/01_refine.ipynb 22
|
|
93
|
+
def fix_hdg_hierarchy(
|
|
94
|
+
hdgs: list[str], # List of markdown headings
|
|
95
|
+
prompt: str=None, # Prompt to use
|
|
96
|
+
model: str='claude-sonnet-4-5', # Model to use
|
|
97
|
+
api_key: str=None # API key
|
|
98
|
+
) -> dict[int, str]: # Dictionary of index → corrected heading
|
|
99
|
+
"Fix the heading hierarchy"
|
|
100
|
+
if api_key is None: api_key = os.getenv('ANTHROPIC_API_KEY')
|
|
101
|
+
if prompt is None: prompt = prompt_fix_hdgs
|
|
102
|
+
prompt = prompt.format(headings_list=fmt_hdgs_idx(hdgs))
|
|
103
|
+
r = completion(model=model, messages=[{"role": "user", "content": prompt}], response_format=HeadingCorrections, api_key=api_key)
|
|
104
|
+
return json.loads(r.choices[0].message.content)['corrections']
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
# %% ../nbs/01_refine.ipynb 25
|
|
108
|
+
@delegates(fix_hdg_hierarchy)
|
|
109
|
+
def mk_fixes_lut(
|
|
110
|
+
hdgs: list[str], # List of markdown headings
|
|
111
|
+
model: str='claude-sonnet-4-5', # Model to use
|
|
112
|
+
api_key: str=None, # API key
|
|
113
|
+
**kwargs
|
|
114
|
+
) -> dict[str, str]: # Dictionary of old → new heading
|
|
115
|
+
"Make a lookup table of fixes"
|
|
116
|
+
if api_key is None: api_key = os.getenv('ANTHROPIC_API_KEY')
|
|
117
|
+
fixes = fix_hdg_hierarchy(hdgs, model=model, api_key=api_key, **kwargs)
|
|
118
|
+
return {hdgs[int(k)]:v for k,v in fixes.items()}
|
|
119
|
+
|
|
120
|
+
# %% ../nbs/01_refine.ipynb 28
|
|
121
|
+
def apply_hdg_fixes(
|
|
122
|
+
p:str, # Page to fix
|
|
123
|
+
lut_fixes: dict[str, str], # Lookup table of fixes
|
|
124
|
+
) -> str: # Page with fixes applied
|
|
125
|
+
"Apply the fixes to the page"
|
|
126
|
+
for old in get_hdgs(p): p = p.replace(old, lut_fixes.get(old, old))
|
|
127
|
+
return p
|
|
128
|
+
|
|
129
|
+
# %% ../nbs/01_refine.ipynb 31
|
|
130
|
+
@delegates(mk_fixes_lut)
|
|
131
|
+
def fix_md_hdgs(
|
|
132
|
+
src:str, # Source directory with markdown pages
|
|
133
|
+
model:str='claude-sonnet-4-5', # Model
|
|
134
|
+
dst:str=None, # Destination directory (None=overwrite)
|
|
135
|
+
**kwargs
|
|
136
|
+
):
|
|
137
|
+
"Fix heading hierarchy in markdown document"
|
|
138
|
+
src_path,dst_path = Path(src),Path(dst) if dst else Path(src)
|
|
139
|
+
if dst_path != src_path: dst_path.mkdir(parents=True, exist_ok=True)
|
|
140
|
+
pgs_with_pg = read_pgs_pg(src_path)
|
|
141
|
+
lut = mk_fixes_lut(L([get_hdgs(pg) for pg in pgs_with_pg]).concat(), model, **kwargs)
|
|
142
|
+
for i,p in enumerate(pgs_with_pg, 1):
|
|
143
|
+
(dst_path/f'page_{i}.md').write_text(apply_hdg_fixes(p, lut))
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: mistocr
|
|
3
|
+
Version: 0.1.6
|
|
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
|
+
Requires-Dist: lisette
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Dynamic: author
|
|
28
|
+
Dynamic: author-email
|
|
29
|
+
Dynamic: classifier
|
|
30
|
+
Dynamic: description
|
|
31
|
+
Dynamic: description-content-type
|
|
32
|
+
Dynamic: home-page
|
|
33
|
+
Dynamic: keywords
|
|
34
|
+
Dynamic: license
|
|
35
|
+
Dynamic: license-file
|
|
36
|
+
Dynamic: provides-extra
|
|
37
|
+
Dynamic: requires-dist
|
|
38
|
+
Dynamic: requires-python
|
|
39
|
+
Dynamic: summary
|
|
40
|
+
|
|
41
|
+
# mistocr
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->
|
|
45
|
+
|
|
46
|
+
## Why mistocr?
|
|
47
|
+
|
|
48
|
+
**Performance**: Mistral’s OCR delivers state-of-the-art accuracy on
|
|
49
|
+
complex documents including tables, charts, and multi-column layouts.
|
|
50
|
+
|
|
51
|
+
**Scale**: Process entire folders of PDFs in a single batch job. Upload
|
|
52
|
+
once, process asynchronously, and retrieve results when ready - perfect
|
|
53
|
+
for large document sets.
|
|
54
|
+
|
|
55
|
+
**Cost savings**: Batch OCR mode reduces costs from \$1/1000 pages to
|
|
56
|
+
\$0.50/1000 pages - a 50% reduction compared to synchronous processing.
|
|
57
|
+
|
|
58
|
+
**Simplicity**: A single
|
|
59
|
+
[`ocr()`](https://franckalbinet.github.io/mistocr/core.html#ocr)
|
|
60
|
+
function handles everything - uploading, batch submission, polling for
|
|
61
|
+
completion, and saving results as markdown with extracted images.
|
|
62
|
+
Process one PDF or an entire folder with the same simple interface.
|
|
63
|
+
|
|
64
|
+
**Organized output**: Each PDF is automatically saved to its own folder
|
|
65
|
+
with pages as separate markdown files and images in an `img` subfolder,
|
|
66
|
+
making results easy to navigate and process further.
|
|
67
|
+
|
|
68
|
+
## Installation
|
|
69
|
+
|
|
70
|
+
Install latest from the GitHub
|
|
71
|
+
[repository](https://github.com/franckalbinet/mistocr):
|
|
72
|
+
|
|
73
|
+
``` sh
|
|
74
|
+
$ pip install git+https://github.com/franckalbinet/mistocr.git
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
or from [pypi](https://pypi.org/project/mistocr/)
|
|
78
|
+
|
|
79
|
+
``` sh
|
|
80
|
+
$ pip install mistocr
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## How to use
|
|
84
|
+
|
|
85
|
+
### Basic usage
|
|
86
|
+
|
|
87
|
+
Process a single PDF:
|
|
88
|
+
|
|
89
|
+
``` python
|
|
90
|
+
from mistocr.core import ocr
|
|
91
|
+
|
|
92
|
+
fname = 'files/test/attention-is-all-you-need.pdf'
|
|
93
|
+
result = ocr(fname)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Or process an entire folder:
|
|
97
|
+
|
|
98
|
+
``` python
|
|
99
|
+
results = ocr('files/test')
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Output structure
|
|
103
|
+
|
|
104
|
+
Each PDF is saved to its own folder with pages as separate markdown
|
|
105
|
+
files and images in an `img` subfolder:
|
|
106
|
+
|
|
107
|
+
files/test/md/
|
|
108
|
+
├── attention-is-all-you-need/
|
|
109
|
+
│ ├── img/
|
|
110
|
+
│ │ ├── img-0.jpeg
|
|
111
|
+
│ │ ├── img-1.jpeg
|
|
112
|
+
│ │ └── ...
|
|
113
|
+
│ ├── page_1.md
|
|
114
|
+
│ ├── page_2.md
|
|
115
|
+
│ └── ...
|
|
116
|
+
└── resnet/
|
|
117
|
+
├── img/
|
|
118
|
+
└── ...
|
|
119
|
+
|
|
120
|
+
### Reading results
|
|
121
|
+
|
|
122
|
+
Read all pages from a processed PDF:
|
|
123
|
+
|
|
124
|
+
``` python
|
|
125
|
+
from mistocr.core import read_pgs
|
|
126
|
+
|
|
127
|
+
text = read_pgs('files/test/md/attention-is-all-you-need')
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
Or read a specific page:
|
|
131
|
+
|
|
132
|
+
``` python
|
|
133
|
+
text = read_pgs('files/test/md/attention-is-all-you-need', 10)
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
### Customization
|
|
137
|
+
|
|
138
|
+
Customize output directory, image inclusion, and polling interval:
|
|
139
|
+
|
|
140
|
+
``` python
|
|
141
|
+
results = ocr('files/test', out_dir='output', inc_img=False, poll_interval=5)
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
**Parameters:**
|
|
145
|
+
|
|
146
|
+
- **`path`**: A single PDF file or folder containing multiple PDFs
|
|
147
|
+
- **`out_dir`**: Directory name for saving markdown output (default:
|
|
148
|
+
`'md'`)
|
|
149
|
+
- **`inc_img`**: Include extracted images in the output (default:
|
|
150
|
+
`True`)
|
|
151
|
+
- **`key`**: Your Mistral API key (uses `MISTRAL_API_KEY` environment
|
|
152
|
+
variable if not provided)
|
|
153
|
+
- **`poll_interval`**: Seconds between batch job status checks (default:
|
|
154
|
+
`2`)
|
|
155
|
+
|
|
156
|
+
**Returns:** List of paths to the generated markdown files
|
|
157
|
+
|
|
158
|
+
## Developer Guide
|
|
159
|
+
|
|
160
|
+
If you are new to using `nbdev` here are some useful pointers to get you
|
|
161
|
+
started.
|
|
162
|
+
|
|
163
|
+
### Install mistocr in Development mode
|
|
164
|
+
|
|
165
|
+
``` sh
|
|
166
|
+
# make sure mistocr package is installed in development mode
|
|
167
|
+
$ pip install -e .
|
|
168
|
+
|
|
169
|
+
# make changes under nbs/ directory
|
|
170
|
+
# ...
|
|
171
|
+
|
|
172
|
+
# compile to have changes apply to mistocr
|
|
173
|
+
$ nbdev_prepare
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
### Documentation
|
|
177
|
+
|
|
178
|
+
Documentation can be found hosted on this GitHub
|
|
179
|
+
[repository](https://github.com/franckalbinet/mistocr)’s
|
|
180
|
+
[pages](https://franckalbinet.github.io/mistocr/). Additionally you can
|
|
181
|
+
find package manager specific guidelines on
|
|
182
|
+
[conda](https://anaconda.org/franckalbinet/mistocr) and
|
|
183
|
+
[pypi](https://pypi.org/project/mistocr/) respectively.
|
|
@@ -0,0 +1,17 @@
|
|
|
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/refine.py
|
|
11
|
+
mistocr.egg-info/PKG-INFO
|
|
12
|
+
mistocr.egg-info/SOURCES.txt
|
|
13
|
+
mistocr.egg-info/dependency_links.txt
|
|
14
|
+
mistocr.egg-info/entry_points.txt
|
|
15
|
+
mistocr.egg-info/not-zip-safe
|
|
16
|
+
mistocr.egg-info/requires.txt
|
|
17
|
+
mistocr.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
mistocr
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
[DEFAULT]
|
|
2
|
+
repo = mistocr
|
|
3
|
+
lib_name = mistocr
|
|
4
|
+
version = 0.1.6
|
|
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 lisette
|
|
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
|
+
|
mistocr-0.1.6/setup.cfg
ADDED
mistocr-0.1.6/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
|
+
|