document2md 0.3.0__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.
@@ -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
141
+ the 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 2026 INGEOTEC
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,138 @@
1
+ Metadata-Version: 2.4
2
+ Name: document2md
3
+ Version: 0.3.0
4
+ Summary: Convert a PDF or a set of scanned page images to Markdown via OCR.
5
+ License: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/INGEOTEC/document2md
7
+ Classifier: License :: OSI Approved :: Apache Software License
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3 :: Only
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Requires-Dist: requests>=2.31
14
+ Requires-Dist: mineru[pipeline]
15
+ Provides-Extra: test
16
+ Requires-Dist: pytest>=7.0; extra == "test"
17
+ Dynamic: license-file
18
+
19
+ # document2md
20
+
21
+ [![test](https://github.com/INGEOTEC/document2md/actions/workflows/test.yml/badge.svg)](https://github.com/INGEOTEC/document2md/actions/workflows/test.yml)
22
+ [![Documentation Status](https://readthedocs.org/projects/document2md/badge/?version=latest)](https://document2md.readthedocs.io/en/latest/)
23
+
24
+ Converts a PDF, or a set of scanned page images, into Markdown — any
25
+ document, such as an edition of Mexico's official gazette (DOF, *Diario
26
+ Oficial de la Federación*) — optionally cropped down to a single note.
27
+ It's a wrapper
28
+ around [mineru](https://github.com/opendatalab/MinerU) for the OCR/layout
29
+ analysis itself; `document2md`'s own contribution is:
30
+
31
+ - Keeping mineru's `mineru-api` server warm across a batch of documents,
32
+ instead of paying its startup (and model-loading) cost once per document.
33
+ - Stitching the OCR of a list of page images (several scanned pages of the
34
+ same note) into one continuous Markdown document.
35
+ - Rewriting the raw HTML tables mineru falls back to (rowspan/colspan) into
36
+ Markdown tables, so the output is Markdown all the way through.
37
+ - Cropping the result down to a single note, by locating its title and the
38
+ next note's title in the OCR'd text — useful because a scanned page
39
+ usually holds the tail of one note and the head of the next.
40
+
41
+ It was extracted from the [LegalIA](https://github.com/INGEOTEC/LegalIA)
42
+ monorepo at commit `e1f258c`, where every commit of its earlier history (as
43
+ `packages/document2md`, and as `packages/dof2md` before the rename) can still
44
+ be read.
45
+
46
+ ## Install
47
+
48
+ ```bash
49
+ pip install document2md
50
+ ```
51
+
52
+ For development, from a clone of this repository:
53
+
54
+ ```bash
55
+ pip install -e ".[test]"
56
+ ```
57
+
58
+ ## Usage
59
+
60
+ ### CLI
61
+
62
+ `document2md` takes exactly one input source — a local PDF or a set of local page
63
+ images — and converts it to Markdown. It never downloads anything itself;
64
+ get the PDF first (e.g. `dofjson.download_edicion_pdf` for a whole DOF
65
+ edition by date and edition, see the
66
+ [dofjson README](https://github.com/INGEOTEC/LegalIA/tree/master/packages/dofjson)),
67
+ then convert it:
68
+
69
+ ```bash
70
+ document2md --pdf edicion.pdf # a local PDF
71
+
72
+ document2md --images pagina-1.jpg pagina-2.jpg \
73
+ --filename out.md # scanned pages, in order
74
+ ```
75
+
76
+ `--filename` sets the output Markdown's name; with `--pdf` it defaults to
77
+ the PDF's own name (`edicion.pdf` → `edicion.md`), but with `--images` it's
78
+ required, since a set of images has no single name to derive one from.
79
+ `--outdir` sets the output directory (default: `output/`).
80
+
81
+ Since one edition's PDF holds every note published that day,
82
+ `--titulo`/`--titulo-siguiente` crop the resulting Markdown down to just one
83
+ note — its own title, and the next note's title, as they appear in the
84
+ gazette's own index:
85
+
86
+ ```bash
87
+ document2md --pdf edicion.pdf \
88
+ --titulo "ACUERDO por el que se..." \
89
+ --titulo-siguiente "DECRETO por el que se..."
90
+ ```
91
+
92
+ Title matching is fuzzy (OCR text rarely matches an index title exactly), so
93
+ a match below `--min-confidence` (default `0.6`) is treated as not found and
94
+ the crop falls back to keeping more text rather than dropping content. Other
95
+ flags:
96
+
97
+ - `--keep-pages` — also keep the uncropped Markdown, as
98
+ `<outdir>/<pdf stem>.full.md`.
99
+ - `--keep-mineru-output` — keep mineru's own raw output (layout/model JSON,
100
+ rendered PDFs...) in `<outdir>/<pdf stem>_mineru/` instead of discarding
101
+ it; useful when a conversion looks wrong and mineru's own read of the page
102
+ is the first thing worth inspecting.
103
+
104
+ ### Python: batch conversion
105
+
106
+ Converting many documents in one run is where mineru's startup cost starts
107
+ to matter. `BatchConverter` keeps a single `mineru-api` server warm across
108
+ the whole batch instead of restarting it per document:
109
+
110
+ ```python
111
+ from document2md import BatchConverter
112
+
113
+ jobs = [
114
+ ("a.pdf", "output", "a.md"),
115
+ (["b-p1.jpg", "b-p2.jpg"], "output", "b.md"),
116
+ ]
117
+
118
+ with BatchConverter() as convert:
119
+ for path_or_paths, outdir, filename in jobs:
120
+ convert(path_or_paths, outdir, filename)
121
+ ```
122
+
123
+ Each call takes a single PDF path, or a list of image paths for a document
124
+ spanning several scanned pages, and writes the result to `outdir/filename`.
125
+ The same `titulo`/`titulo_siguiente`, `min_confidence`, `keep_pages` and
126
+ `keep_mineru_output` options the CLI exposes are also its keyword
127
+ arguments — see `BatchConverter.__call__`'s docstring for the full
128
+ signature.
129
+
130
+ `nota2md.legal_provisions` accepts an already-`__enter__`'d `BatchConverter`
131
+ as its own `converter` parameter, so a batch of DOF legal provisions can
132
+ share the same warm server too.
133
+
134
+ ## Tests
135
+
136
+ ```bash
137
+ pytest -v
138
+ ```
@@ -0,0 +1,120 @@
1
+ # document2md
2
+
3
+ [![test](https://github.com/INGEOTEC/document2md/actions/workflows/test.yml/badge.svg)](https://github.com/INGEOTEC/document2md/actions/workflows/test.yml)
4
+ [![Documentation Status](https://readthedocs.org/projects/document2md/badge/?version=latest)](https://document2md.readthedocs.io/en/latest/)
5
+
6
+ Converts a PDF, or a set of scanned page images, into Markdown — any
7
+ document, such as an edition of Mexico's official gazette (DOF, *Diario
8
+ Oficial de la Federación*) — optionally cropped down to a single note.
9
+ It's a wrapper
10
+ around [mineru](https://github.com/opendatalab/MinerU) for the OCR/layout
11
+ analysis itself; `document2md`'s own contribution is:
12
+
13
+ - Keeping mineru's `mineru-api` server warm across a batch of documents,
14
+ instead of paying its startup (and model-loading) cost once per document.
15
+ - Stitching the OCR of a list of page images (several scanned pages of the
16
+ same note) into one continuous Markdown document.
17
+ - Rewriting the raw HTML tables mineru falls back to (rowspan/colspan) into
18
+ Markdown tables, so the output is Markdown all the way through.
19
+ - Cropping the result down to a single note, by locating its title and the
20
+ next note's title in the OCR'd text — useful because a scanned page
21
+ usually holds the tail of one note and the head of the next.
22
+
23
+ It was extracted from the [LegalIA](https://github.com/INGEOTEC/LegalIA)
24
+ monorepo at commit `e1f258c`, where every commit of its earlier history (as
25
+ `packages/document2md`, and as `packages/dof2md` before the rename) can still
26
+ be read.
27
+
28
+ ## Install
29
+
30
+ ```bash
31
+ pip install document2md
32
+ ```
33
+
34
+ For development, from a clone of this repository:
35
+
36
+ ```bash
37
+ pip install -e ".[test]"
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ ### CLI
43
+
44
+ `document2md` takes exactly one input source — a local PDF or a set of local page
45
+ images — and converts it to Markdown. It never downloads anything itself;
46
+ get the PDF first (e.g. `dofjson.download_edicion_pdf` for a whole DOF
47
+ edition by date and edition, see the
48
+ [dofjson README](https://github.com/INGEOTEC/LegalIA/tree/master/packages/dofjson)),
49
+ then convert it:
50
+
51
+ ```bash
52
+ document2md --pdf edicion.pdf # a local PDF
53
+
54
+ document2md --images pagina-1.jpg pagina-2.jpg \
55
+ --filename out.md # scanned pages, in order
56
+ ```
57
+
58
+ `--filename` sets the output Markdown's name; with `--pdf` it defaults to
59
+ the PDF's own name (`edicion.pdf` → `edicion.md`), but with `--images` it's
60
+ required, since a set of images has no single name to derive one from.
61
+ `--outdir` sets the output directory (default: `output/`).
62
+
63
+ Since one edition's PDF holds every note published that day,
64
+ `--titulo`/`--titulo-siguiente` crop the resulting Markdown down to just one
65
+ note — its own title, and the next note's title, as they appear in the
66
+ gazette's own index:
67
+
68
+ ```bash
69
+ document2md --pdf edicion.pdf \
70
+ --titulo "ACUERDO por el que se..." \
71
+ --titulo-siguiente "DECRETO por el que se..."
72
+ ```
73
+
74
+ Title matching is fuzzy (OCR text rarely matches an index title exactly), so
75
+ a match below `--min-confidence` (default `0.6`) is treated as not found and
76
+ the crop falls back to keeping more text rather than dropping content. Other
77
+ flags:
78
+
79
+ - `--keep-pages` — also keep the uncropped Markdown, as
80
+ `<outdir>/<pdf stem>.full.md`.
81
+ - `--keep-mineru-output` — keep mineru's own raw output (layout/model JSON,
82
+ rendered PDFs...) in `<outdir>/<pdf stem>_mineru/` instead of discarding
83
+ it; useful when a conversion looks wrong and mineru's own read of the page
84
+ is the first thing worth inspecting.
85
+
86
+ ### Python: batch conversion
87
+
88
+ Converting many documents in one run is where mineru's startup cost starts
89
+ to matter. `BatchConverter` keeps a single `mineru-api` server warm across
90
+ the whole batch instead of restarting it per document:
91
+
92
+ ```python
93
+ from document2md import BatchConverter
94
+
95
+ jobs = [
96
+ ("a.pdf", "output", "a.md"),
97
+ (["b-p1.jpg", "b-p2.jpg"], "output", "b.md"),
98
+ ]
99
+
100
+ with BatchConverter() as convert:
101
+ for path_or_paths, outdir, filename in jobs:
102
+ convert(path_or_paths, outdir, filename)
103
+ ```
104
+
105
+ Each call takes a single PDF path, or a list of image paths for a document
106
+ spanning several scanned pages, and writes the result to `outdir/filename`.
107
+ The same `titulo`/`titulo_siguiente`, `min_confidence`, `keep_pages` and
108
+ `keep_mineru_output` options the CLI exposes are also its keyword
109
+ arguments — see `BatchConverter.__call__`'s docstring for the full
110
+ signature.
111
+
112
+ `nota2md.legal_provisions` accepts an already-`__enter__`'d `BatchConverter`
113
+ as its own `converter` parameter, so a batch of DOF legal provisions can
114
+ share the same warm server too.
115
+
116
+ ## Tests
117
+
118
+ ```bash
119
+ pytest -v
120
+ ```
@@ -0,0 +1,5 @@
1
+ from document2md.batch import BatchConverter
2
+
3
+ __version__ = "0.3.0"
4
+
5
+ __all__ = ["BatchConverter"]
@@ -0,0 +1,108 @@
1
+ """Batch document-to-Markdown conversion, keeping one mineru-api server warm
2
+ across many jobs instead of paying its startup (and model-loading) cost once
3
+ per document:
4
+
5
+ with BatchConverter() as convert:
6
+ for pdf_path, outdir, filename in jobs:
7
+ convert(pdf_path, outdir, filename)
8
+
9
+ document2md itself has no notion of what a "note" is or where a document came
10
+ from — a job is just a PDF (a single path) or a set of scanned page images (a
11
+ list of paths), an output directory, and an output filename. Whatever calls
12
+ this decides what those mean (a DOF legal provision, or anything else).
13
+ """
14
+ from pathlib import Path
15
+
16
+ from document2md import converter as _converter
17
+ from document2md.converter import DEFAULT_TIMEOUT_SECONDS
18
+ from document2md.cutter import cut_markdown_by_titles
19
+ from document2md.mineru_server import ENV_VAR as _MINERU_API_URL_ENV_VAR
20
+ from document2md.mineru_server import MineruServer
21
+
22
+
23
+ class BatchConverter:
24
+ """Context manager: `__enter__` starts a persistent `mineru-api` server
25
+ (skipped if a caller further up already has one running via
26
+ MINERU_API_URL) and returns `self`, callable once per document;
27
+ `__exit__` stops it. Calling it converts one document — a single PDF
28
+ path, or a list of image paths for a document spanning several scanned
29
+ pages — to Markdown, written to `outdir/filename`.
30
+
31
+ `titulo`/`titulo_siguiente`, when given, slice the OCR'd Markdown down
32
+ to the text between their two boundaries (see
33
+ document2md.cutter.cut_markdown_by_titles) — e.g. a DOF legal provision's own
34
+ title and the next one's, to cut a page shared with the notes before and
35
+ after it down to just this one. Left out (the default), the whole
36
+ conversion is kept as-is, on the assumption that the whole document is
37
+ what was asked for.
38
+ """
39
+
40
+ def __init__(self):
41
+ """Create an unstarted converter; call `__enter__` (or use as a
42
+ context manager) before calling it."""
43
+ self._server: MineruServer | None = None
44
+
45
+ def __enter__(self) -> "BatchConverter":
46
+ """Start a persistent `mineru-api` server, unless one is already
47
+ reachable via MINERU_API_URL, and return `self`."""
48
+ import os
49
+
50
+ if _MINERU_API_URL_ENV_VAR not in os.environ:
51
+ self._server = MineruServer()
52
+ self._server.start()
53
+ return self
54
+
55
+ def __exit__(self, exc_type, exc, tb) -> None:
56
+ """Stop the `mineru-api` server started by `__enter__`, if any."""
57
+ if self._server is not None:
58
+ self._server.stop()
59
+ self._server = None
60
+
61
+ def __call__(
62
+ self,
63
+ path_or_paths: str | Path | list[str | Path],
64
+ outdir: str | Path,
65
+ filename: str,
66
+ titulo: str | None = None,
67
+ titulo_siguiente: str | None = None,
68
+ *,
69
+ min_confidence: float = 0.6,
70
+ keep_pages: bool = False,
71
+ keep_mineru_output: bool = False,
72
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
73
+ ) -> Path:
74
+ """Convert one document — `path_or_paths` a single PDF path, or a
75
+ list of image paths for a document spanning several scanned pages —
76
+ to Markdown, written to `outdir/filename`, and return that path.
77
+
78
+ `titulo`/`titulo_siguiente`, `min_confidence` and `keep_pages` are
79
+ forwarded to `cutter.cut_markdown_by_titles` to crop the result down
80
+ to a single note; left as `None` (the default), the whole conversion
81
+ is kept as-is. `keep_mineru_output` and `timeout` are forwarded to
82
+ `converter.convert_to_markdown`/`convert_images_to_markdown`."""
83
+ outdir = Path(outdir)
84
+ outdir.mkdir(parents=True, exist_ok=True)
85
+ dest = outdir / filename
86
+
87
+ if isinstance(path_or_paths, (list, tuple)):
88
+ _converter.convert_images_to_markdown(
89
+ [Path(p) for p in path_or_paths], dest,
90
+ timeout=timeout, keep_mineru_output=keep_mineru_output,
91
+ )
92
+ else:
93
+ _converter.convert_to_markdown(
94
+ Path(path_or_paths), dest,
95
+ timeout=timeout, keep_mineru_output=keep_mineru_output,
96
+ )
97
+
98
+ if titulo is None:
99
+ return dest
100
+
101
+ full_markdown = dest.read_text(encoding="utf-8")
102
+ if keep_pages:
103
+ (outdir / f"{dest.stem}.full.md").write_text(full_markdown, encoding="utf-8")
104
+ cut = cut_markdown_by_titles(
105
+ full_markdown, titulo, titulo_siguiente, min_confidence=min_confidence
106
+ )
107
+ dest.write_text(cut + "\n", encoding="utf-8")
108
+ return dest
@@ -0,0 +1,109 @@
1
+ """The `document2md` console script: parses command-line arguments and runs one
2
+ `document2md.batch.BatchConverter` conversion."""
3
+ import argparse
4
+ import subprocess
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from document2md.batch import BatchConverter
9
+ from document2md.converter import DEFAULT_TIMEOUT_SECONDS
10
+
11
+
12
+ def parse_args(argv=None):
13
+ """Parse the `document2md` command-line arguments (`argv`, or `sys.argv` when
14
+ `None`) and return the resulting `argparse.Namespace`."""
15
+ parser = argparse.ArgumentParser(
16
+ description="Convert a local PDF, or an ordered set of scanned page images, to "
17
+ "Markdown — any document, such as an edition of Mexico's official gazette (DOF)."
18
+ )
19
+ parser.add_argument(
20
+ "--pdf", default=None,
21
+ help="Convert this local PDF file.",
22
+ )
23
+ parser.add_argument(
24
+ "--images", nargs="+", default=None, metavar="PATH",
25
+ help="Convert this ordered list of scanned page image files (one note spanning "
26
+ "several pages).",
27
+ )
28
+ parser.add_argument(
29
+ "--filename", default=None,
30
+ help="Output Markdown filename. Defaults to the --pdf file's own name; required with "
31
+ "--images, since there's no single input name to derive one from.",
32
+ )
33
+ parser.add_argument("--outdir", default="output", help="Output directory (default: output/)")
34
+ parser.add_argument(
35
+ "--titulo", default=None,
36
+ help="Title of the note to keep — crops the converted Markdown down to just that note "
37
+ "(the whole edition's Markdown is kept by default). Combine with --titulo-siguiente.",
38
+ )
39
+ parser.add_argument(
40
+ "--titulo-siguiente", default=None,
41
+ help="Title of the note right after --titulo, marking where the kept note ends",
42
+ )
43
+ parser.add_argument(
44
+ "--min-confidence", type=float, default=0.6,
45
+ help="Minimum title-match confidence (0..1) required to apply a --titulo/--titulo-siguiente "
46
+ "boundary; a weaker match falls back to keeping more text rather than dropping content "
47
+ "(default: 0.6)",
48
+ )
49
+ parser.add_argument(
50
+ "--keep-pages", action="store_true",
51
+ help="With --titulo, also keep the uncropped Markdown as <outdir>/<pdf stem>.full.md",
52
+ )
53
+ parser.add_argument(
54
+ "--keep-mineru-output", action="store_true",
55
+ help="Keep mineru's raw output (layout/model JSON, rendered PDFs...) in "
56
+ "<outdir>/<pdf stem>_mineru/ instead of discarding it",
57
+ )
58
+ return parser.parse_args(argv)
59
+
60
+
61
+ def main(argv=None):
62
+ """Entry point for the `document2md` console script: parse arguments, run one
63
+ `BatchConverter` conversion, and print where the Markdown was saved.
64
+ Exits with an error message (no traceback) on a missing/ambiguous input
65
+ source or a mineru timeout."""
66
+ args = parse_args(argv)
67
+
68
+ sources_given = sum(x is not None for x in (args.pdf, args.images))
69
+ if sources_given != 1:
70
+ sys.exit("Provide exactly one of: --pdf or --images.")
71
+
72
+ outdir = Path(args.outdir)
73
+ outdir.mkdir(parents=True, exist_ok=True)
74
+
75
+ if args.pdf is not None:
76
+ pdf_path = Path(args.pdf)
77
+ if not pdf_path.is_file():
78
+ sys.exit(f"--pdf file not found: {pdf_path}")
79
+ md_filename = args.filename or pdf_path.with_suffix(".md").name
80
+ path_or_paths = pdf_path
81
+ else:
82
+ if args.filename is None:
83
+ sys.exit("--filename is required with --images (there's no single input name to derive one from).")
84
+ image_paths = [Path(p) for p in args.images]
85
+ missing = [p for p in image_paths if not p.is_file()]
86
+ if missing:
87
+ sys.exit(f"--images file(s) not found: {', '.join(str(p) for p in missing)}")
88
+ md_filename = args.filename
89
+ path_or_paths = image_paths
90
+
91
+ print("Converting to Markdown (mineru)...")
92
+ try:
93
+ with BatchConverter() as convert:
94
+ md_path = convert(
95
+ path_or_paths, outdir, md_filename, args.titulo, args.titulo_siguiente,
96
+ min_confidence=args.min_confidence,
97
+ keep_pages=args.keep_pages,
98
+ keep_mineru_output=args.keep_mineru_output,
99
+ )
100
+ except subprocess.TimeoutExpired:
101
+ sys.exit(
102
+ f"Conversion timed out after {DEFAULT_TIMEOUT_SECONDS}s. "
103
+ "This document may be unusually large."
104
+ )
105
+ print(f"Markdown saved to: {md_path}")
106
+
107
+
108
+ if __name__ == "__main__":
109
+ main()