document2md 0.3.0__py3-none-any.whl

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,5 @@
1
+ from document2md.batch import BatchConverter
2
+
3
+ __version__ = "0.3.0"
4
+
5
+ __all__ = ["BatchConverter"]
document2md/batch.py ADDED
@@ -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
document2md/cli.py ADDED
@@ -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()
@@ -0,0 +1,183 @@
1
+ """Shell out to mineru to OCR a PDF or a set of scanned page images into
2
+ Markdown, then rewrite its raw HTML table fallback into Markdown tables (see
3
+ document2md.tables).
4
+
5
+ Reuses an already-running mineru-api server via MINERU_API_URL when one is
6
+ set (see document2md.mineru_server), so a batch of documents shares one warm
7
+ server instead of each call starting and stopping its own.
8
+ """
9
+ import contextlib
10
+ import os
11
+ import shutil
12
+ import subprocess
13
+ import tempfile
14
+ from pathlib import Path
15
+
16
+ from document2md.mineru_server import ENV_VAR as MINERU_API_URL_ENV_VAR
17
+ from document2md.mineru_server import MineruServer
18
+ from document2md.tables import html_tables_to_markdown
19
+
20
+ # Some real DOF editions run to hundreds of pages with heavy table content,
21
+ # and mineru has been observed to stall indefinitely on a single page/table
22
+ # in such cases rather than just running slowly. This bounds how long any
23
+ # one conversion is allowed to run before we give up on it.
24
+ DEFAULT_TIMEOUT_SECONDS = 3600
25
+
26
+
27
+ def _mineru_out_dir(md_path: Path, keep_mineru_output: bool):
28
+ """Context manager yielding the directory mineru should write its raw
29
+ output (Markdown, layout/model JSON, rendered PDFs...) into.
30
+
31
+ Normally that output is only a stepping stone to the Markdown this module
32
+ returns, so it lives in a throwaway temp dir. When `keep_mineru_output` is
33
+ set, callers debugging a bad conversion need to see that raw output
34
+ instead of it vanishing with the temp dir, so it is written to
35
+ `<md stem>_mineru/` next to `md_path` and left there."""
36
+ if keep_mineru_output:
37
+ out_dir = md_path.parent / f"{md_path.stem}_mineru"
38
+ out_dir.mkdir(parents=True, exist_ok=True)
39
+ return contextlib.nullcontext(str(out_dir))
40
+ return tempfile.TemporaryDirectory()
41
+
42
+
43
+ def _require_mineru() -> None:
44
+ """Raise RuntimeError with an actionable message if the `mineru` CLI
45
+ isn't on PATH, instead of letting `subprocess.run` fail opaquely."""
46
+ if shutil.which("mineru") is None:
47
+ raise RuntimeError(
48
+ "'mineru' is required to convert documents but isn't installed. "
49
+ "Install document2md's dependencies: pip install document2md"
50
+ )
51
+
52
+
53
+ def _run_mineru(input_path: Path, tmp_out: str, timeout: float) -> tuple[str, Path | None]:
54
+ """Run mineru's pipeline backend on one input file (PDF or image) inside
55
+ the given temp directory. Returns the raw Markdown text and the directory
56
+ of any figures mineru extracted (or None if there were none).
57
+
58
+ Reuses the MINERU_API_URL server if set (see mineru_server.MineruServer),
59
+ so batch conversions don't reload models once per document."""
60
+ api_url = os.environ.get(MINERU_API_URL_ENV_VAR)
61
+ cmd = ["mineru", "-o", tmp_out, "-p", str(input_path), "-b", "pipeline"]
62
+ if api_url:
63
+ cmd += ["--api-url", api_url]
64
+ subprocess.run(cmd, check=True, timeout=timeout)
65
+
66
+ auto_dir = Path(tmp_out) / input_path.stem / "auto"
67
+ md_text = (auto_dir / f"{input_path.stem}.md").read_text(encoding="utf-8")
68
+ images_src = auto_dir / "images"
69
+ if images_src.is_dir() and any(images_src.iterdir()):
70
+ return md_text, images_src
71
+ return md_text, None
72
+
73
+
74
+ def convert_to_markdown(
75
+ pdf_path: Path,
76
+ md_path: Path,
77
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
78
+ keep_mineru_output: bool = False,
79
+ ) -> None:
80
+ """Convert a PDF to Markdown using mineru's pipeline backend.
81
+
82
+ mineru auto-detects which parts of the document need OCR internally, so
83
+ this handles both born-digital and scanned DOF editions, and produces
84
+ much cleaner Markdown (real paragraphs, accurate headings) than plain
85
+ text-layer extraction — at the cost of being far slower (mineru runs
86
+ real layout/OCR models even on already-digital text).
87
+
88
+ Complex tables, which mineru emits as raw HTML, are rewritten to Markdown
89
+ tables (see tables.html_tables_to_markdown) so the output is Markdown all
90
+ the way through.
91
+
92
+ If MINERU_API_URL is set (see mineru_server.MineruServer), reuses that
93
+ already-running server instead of letting mineru spin up (and tear down)
94
+ its own temporary one for this single call — this is what lets a batch
95
+ of documents avoid reloading the models once per document.
96
+
97
+ `keep_mineru_output` writes mineru's raw output (its own Markdown, layout
98
+ JSON, rendered layout/model PDFs...) to `<md stem>_mineru/` next to
99
+ `md_path` instead of a temp dir that disappears at the end of the call —
100
+ useful when a conversion looks wrong and mineru's own read of the page is
101
+ the first thing worth inspecting.
102
+
103
+ Raises subprocess.TimeoutExpired if mineru doesn't finish within
104
+ `timeout` seconds — callers doing batch work should catch this and skip
105
+ the offending document rather than let one stuck conversion block an
106
+ entire run."""
107
+ _require_mineru()
108
+
109
+ with _mineru_out_dir(md_path, keep_mineru_output) as tmp_out:
110
+ md_text, images_src = _run_mineru(pdf_path, tmp_out, timeout)
111
+ if images_src is not None:
112
+ images_dirname = f"{pdf_path.stem}_images"
113
+ shutil.copytree(
114
+ images_src, md_path.parent / images_dirname, dirs_exist_ok=True
115
+ )
116
+ md_text = md_text.replace("](images/", f"]({images_dirname}/")
117
+
118
+ md_path.write_text(html_tables_to_markdown(md_text), encoding="utf-8")
119
+
120
+
121
+ def convert_images_to_markdown(
122
+ image_paths: list[Path],
123
+ md_path: Path,
124
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
125
+ keep_mineru_output: bool = False,
126
+ ) -> None:
127
+ """Convert one or more scanned page images into a single Markdown document.
128
+
129
+ This is the OCR path for notes that come as scanned pages rather than
130
+ digital text — e.g. the JPEGs downloaded by dofjson's
131
+ download_nota_imagenes(). Each image is OCR'd with the same mineru
132
+ pipeline backend as convert_to_markdown() and the results are
133
+ concatenated in the order given (page order), so a note spanning several
134
+ pages becomes one continuous Markdown file.
135
+
136
+ Complex tables mineru emits as raw HTML are rewritten to Markdown tables
137
+ (see tables.html_tables_to_markdown), like convert_to_markdown().
138
+
139
+ The page images typically hold more than the note of interest (a page can
140
+ start or end mid-note); callers wanting only one note should slice the
141
+ result afterwards — see cutter.cut_markdown_by_titles(), or use
142
+ BatchConverter, which does the cut inline.
143
+
144
+ Figures mineru extracts from a page are copied next to the output under
145
+ `<md stem>_images/<image stem>/` (namespaced per page so figures from
146
+ different pages can't collide), and their Markdown references rewritten to
147
+ match. Raises subprocess.TimeoutExpired like convert_to_markdown().
148
+
149
+ `keep_mineru_output`, like in convert_to_markdown(), keeps mineru's raw
150
+ per-page output instead of discarding it — each page lands in its own
151
+ `<md stem>_mineru/<image stem>/` subdirectory, mirroring how the
152
+ extracted figures are namespaced per page.
153
+
154
+ A note spanning several pages OCRs each page with a separate `mineru`
155
+ invocation; left alone, that means reloading mineru's layout/OCR models
156
+ once per page. When MINERU_API_URL isn't already set (i.e. no caller is
157
+ already running a batch server across multiple notes) and there's more
158
+ than one page, this starts a MineruServer for the duration of the loop
159
+ so all of this note's pages share one already-warm server instead of
160
+ each page starting and stopping its own."""
161
+ _require_mineru()
162
+ image_paths = [Path(p) for p in image_paths]
163
+ if not image_paths:
164
+ raise ValueError("convert_images_to_markdown requires at least one image path")
165
+
166
+ images_dirname = f"{md_path.stem}_images"
167
+ parts = []
168
+ needs_server = len(image_paths) > 1 and MINERU_API_URL_ENV_VAR not in os.environ
169
+ server = MineruServer() if needs_server else contextlib.nullcontext()
170
+ with server, _mineru_out_dir(md_path, keep_mineru_output) as tmp_out:
171
+ for image_path in image_paths:
172
+ md_text, images_src = _run_mineru(image_path, tmp_out, timeout)
173
+ if images_src is not None:
174
+ page_dest = md_path.parent / images_dirname / image_path.stem
175
+ shutil.copytree(images_src, page_dest, dirs_exist_ok=True)
176
+ md_text = md_text.replace(
177
+ "](images/", f"]({images_dirname}/{image_path.stem}/"
178
+ )
179
+ parts.append(md_text.strip())
180
+
181
+ md_path.write_text(
182
+ html_tables_to_markdown("\n\n".join(parts)) + "\n", encoding="utf-8"
183
+ )
document2md/cutter.py ADDED
@@ -0,0 +1,189 @@
1
+ """Slice the Markdown OCR'd from a note's scanned page images down to just the
2
+ note of interest.
3
+
4
+ The page images downloaded for a note (dofjson.download_nota_imagenes) hold
5
+ whole pages: the first page usually begins with the tail of the previous note,
6
+ and the last page often ends with the start of the next one. But the per-day
7
+ note index gives us the title of every note in order, so we can locate two
8
+ boundaries in the OCR'd text — where THIS note's title appears (start) and
9
+ where the NEXT note's title appears (end) — and keep only what lies between.
10
+
11
+ Matching is fuzzy on purpose: OCR text differs from the index title in case,
12
+ accents, line breaks and the odd misread character, so titles are compared on
13
+ an accent-folded, marker-stripped, whitespace-collapsed form, and located with
14
+ difflib's longest-matching-block alignment rather than an exact search.
15
+ """
16
+ import difflib
17
+ import re
18
+ import unicodedata
19
+
20
+ _SKIP_CHARS = set("#*|\\>_`~[]")
21
+ _HEADING_LINE = re.compile(r"^#{1,6}\s")
22
+
23
+
24
+ def _normalize_with_map(text: str) -> tuple[str, list[int]]:
25
+ """Return an accent-folded, lowercased, marker-stripped, single-spaced copy
26
+ of `text`, alongside a map from each normalized-character position back to
27
+ its index in the original `text` (so a match can be sliced from the
28
+ original)."""
29
+ norm_chars: list[str] = []
30
+ idx_map: list[int] = []
31
+ prev_space = True
32
+ for i, ch in enumerate(text):
33
+ base = unicodedata.normalize("NFKD", ch)
34
+ base = "".join(c for c in base if not unicodedata.combining(c)).lower()
35
+ if not base or base in _SKIP_CHARS:
36
+ continue
37
+ if base.isspace():
38
+ if not prev_space:
39
+ norm_chars.append(" ")
40
+ idx_map.append(i)
41
+ prev_space = True
42
+ continue
43
+ for c in base:
44
+ if c in _SKIP_CHARS:
45
+ continue
46
+ norm_chars.append(c)
47
+ idx_map.append(i)
48
+ prev_space = False
49
+ return "".join(norm_chars), idx_map
50
+
51
+
52
+ def _locate(
53
+ norm_text: str, idx_map: list[int], title: str, from_norm: int = 0
54
+ ) -> tuple[int | None, int | None, float]:
55
+ """Best-effort match for `title` within `norm_text[from_norm:]`. Returns
56
+ (normalized offset, original-text offset, 0..1 confidence), or
57
+ (None, None, 0.0) if nothing matches.
58
+
59
+ `from_norm` lets the caller skip past an earlier region — used to find the
60
+ NEXT note's title after the current one, which matters when consecutive
61
+ titles are near-duplicates (e.g. two deslinde avisos differing only in a
62
+ number) and a whole-text search would otherwise anchor on the first.
63
+
64
+ Confidence is matched characters divided by the span of haystack they are
65
+ spread across (floored at the title's own length): a title that appears
66
+ together, even split by a few OCR glitches, matches within a span close
67
+ to its own length. Boilerplate that merely echoes some of the title's
68
+ words (e.g. a shared date phrase in running prose) racks up the same
69
+ matched-character count but scattered over a much wider span, so it is
70
+ penalized instead of being scored as if it were one solid match — that
71
+ scattering is exactly what let such boilerplate be mistaken for a real
72
+ title match before."""
73
+ norm_title, _ = _normalize_with_map(title)
74
+ norm_title = norm_title.strip()
75
+ if not norm_title:
76
+ return None, None, 0.0
77
+
78
+ haystack = norm_text[from_norm:]
79
+ matcher = difflib.SequenceMatcher(None, haystack, norm_title, autojunk=False)
80
+ blocks = [b for b in matcher.get_matching_blocks() if b.size > 0]
81
+ if not blocks:
82
+ return None, None, 0.0
83
+ anchor = max(blocks, key=lambda b: b.size)
84
+
85
+ matched = sum(b.size for b in blocks)
86
+ span = max(b.a + b.size for b in blocks) - min(b.a for b in blocks)
87
+ confidence = matched / max(span, len(norm_title))
88
+ start_local = max(0, anchor.a - anchor.b)
89
+ start_norm = min(from_norm + start_local, len(idx_map) - 1)
90
+ return start_norm, idx_map[start_norm], confidence
91
+
92
+
93
+ def locate_titles(
94
+ markdown: str, titulo: str, titulo_siguiente: str | None = None
95
+ ) -> dict:
96
+ """Locate the start (this note's title) and end (next note's title)
97
+ boundaries in `markdown`. Exposed mainly for inspection/testing;
98
+ cut_markdown_by_titles() is the usual entry point.
99
+
100
+ Returns a dict with `start`, `start_confidence`, `end`, `end_confidence`
101
+ (offsets are into `markdown`; `end` is None when there is no next title or
102
+ it wasn't found after the start)."""
103
+ norm_text, idx_map = _normalize_with_map(markdown)
104
+
105
+ if titulo:
106
+ start_norm, start, start_conf = _locate(norm_text, idx_map, titulo)
107
+ else:
108
+ start_norm, start, start_conf = None, None, 0.0
109
+ if start is None:
110
+ start_norm, start = 0, 0
111
+
112
+ end, end_conf = None, 0.0
113
+ if titulo_siguiente:
114
+ # Skip past the current note's own title before searching for the next
115
+ # one, so near-duplicate titles don't anchor the end back on the start.
116
+ norm_titulo, _ = _normalize_with_map(titulo or "")
117
+ from_norm = min(start_norm + len(norm_titulo.strip()), len(norm_text))
118
+ _, candidate, end_conf = _locate(
119
+ norm_text, idx_map, titulo_siguiente, from_norm=from_norm
120
+ )
121
+ if candidate is not None and candidate > start:
122
+ end = candidate
123
+
124
+ return {
125
+ "start": start,
126
+ "start_confidence": start_conf,
127
+ "end": end,
128
+ "end_confidence": end_conf,
129
+ }
130
+
131
+
132
+ def cut_markdown_by_titles(
133
+ markdown: str,
134
+ titulo: str,
135
+ titulo_siguiente: str | None = None,
136
+ min_confidence: float = 0.6,
137
+ ) -> str:
138
+ """Return the slice of `markdown` that belongs to the note titled `titulo`.
139
+
140
+ `titulo` and `titulo_siguiente` are the note's own title and the next
141
+ note's title (in publication order) from the per-day index — the next
142
+ title marks where this note ends.
143
+
144
+ A boundary is only applied when its match confidence clears
145
+ `min_confidence`: a start below the threshold falls back to the beginning
146
+ of the text, and a weak/absent next-title match falls back to the end, so
147
+ a poor match degrades to keeping more text rather than dropping the note's
148
+ content."""
149
+ if not markdown.strip():
150
+ return ""
151
+
152
+ located = locate_titles(markdown, titulo, titulo_siguiente)
153
+
154
+ start = located["start"] if located["start_confidence"] >= min_confidence else 0
155
+ boundary_applied = (
156
+ located["end"] is not None and located["end_confidence"] >= min_confidence
157
+ )
158
+
159
+ # Snap the start to the beginning of its line, so the note's own heading
160
+ # marker (`## `) travels with its title instead of being clipped off.
161
+ start = markdown.rfind("\n", 0, start) + 1
162
+
163
+ if boundary_applied:
164
+ # Snap the end to the start of the next note's title line, then walk
165
+ # back over the blank and heading lines right before it: the DOF prints
166
+ # the next note's organism headers (e.g. `# SECRETARIA DE ENERGIA`)
167
+ # ABOVE its title, so they'd otherwise be left dangling at the tail of
168
+ # this note.
169
+ end = markdown.rfind("\n", 0, located["end"]) + 1
170
+ end = _trim_preceding_headings(markdown, end)
171
+ else:
172
+ end = len(markdown)
173
+ if end <= start:
174
+ end = len(markdown)
175
+
176
+ return markdown[start:end].strip()
177
+
178
+
179
+ def _trim_preceding_headings(markdown: str, end: int) -> int:
180
+ """Move `end` back over any run of blank and heading (`#…`) lines that
181
+ immediately precede it, returning the new offset."""
182
+ while end > 0:
183
+ line_start = markdown.rfind("\n", 0, end - 1) + 1
184
+ line = markdown[line_start:end].strip()
185
+ if line == "" or _HEADING_LINE.match(line):
186
+ end = line_start
187
+ else:
188
+ break
189
+ return end
@@ -0,0 +1,103 @@
1
+ """Manages a persistent `mineru-api` process for batch conversions.
2
+
3
+ Left to itself, the `mineru` CLI spins up (and tears down) a fresh temporary
4
+ API server — reloading all layout/OCR models — on every single invocation.
5
+ That's fine for converting one document, but wasteful when a batch job
6
+ converts many documents in the same run. MineruServer starts one `mineru-api`
7
+ process, waits for it to report healthy, and points `convert_to_markdown` at
8
+ it via the MINERU_API_URL environment variable for the duration of the batch.
9
+ """
10
+ import os
11
+ import socket
12
+ import subprocess
13
+ import time
14
+
15
+ import requests
16
+
17
+ ENV_VAR = "MINERU_API_URL"
18
+
19
+
20
+ def _find_free_port() -> int:
21
+ """Return a currently-unused TCP port on 127.0.0.1, by binding to port 0
22
+ and reading back the OS-assigned port."""
23
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
24
+ s.bind(("127.0.0.1", 0))
25
+ return s.getsockname()[1]
26
+
27
+
28
+ def _wait_until_healthy(base_url: str, timeout: float = 300.0, interval: float = 1.0) -> None:
29
+ """Poll `base_url`'s `/health` endpoint every `interval` seconds until it
30
+ answers 200, raising RuntimeError if it hasn't within `timeout` seconds —
31
+ mineru-api takes a while to come up because it loads its models on
32
+ startup."""
33
+ deadline = time.monotonic() + timeout
34
+ health_url = f"{base_url}/health"
35
+ while time.monotonic() < deadline:
36
+ try:
37
+ if requests.get(health_url, timeout=2).status_code == 200:
38
+ return
39
+ except requests.exceptions.RequestException:
40
+ pass
41
+ time.sleep(interval)
42
+ raise RuntimeError(f"mineru-api did not become healthy within {timeout}s at {health_url}")
43
+
44
+
45
+ class MineruServer:
46
+ """Context manager: starts a persistent mineru-api server on __enter__,
47
+ exposes it to convert_to_markdown() via MINERU_API_URL, and stops it on
48
+ __exit__ (restoring any previous MINERU_API_URL value)."""
49
+
50
+ def __init__(self, host: str = "127.0.0.1", port: int | None = None):
51
+ """Create an unstarted server bound to `host`/`port` (a free port is
52
+ picked when `port` is `None`); call `start()` (or use as a context
53
+ manager) to actually launch it."""
54
+ self.host = host
55
+ self.port = port if port is not None else _find_free_port()
56
+ self.base_url = f"http://{self.host}:{self.port}"
57
+ self._process: subprocess.Popen | None = None
58
+ self._previous_env_value: str | None = None
59
+
60
+ def start(self) -> None:
61
+ """Launch `mineru-api` as a subprocess, block until it reports
62
+ healthy (stopping it again on failure), and point MINERU_API_URL at
63
+ it so `converter.py` picks it up."""
64
+ self._process = subprocess.Popen(
65
+ ["mineru-api", "--host", self.host, "--port", str(self.port)],
66
+ stdout=subprocess.DEVNULL,
67
+ stderr=subprocess.DEVNULL,
68
+ )
69
+ try:
70
+ _wait_until_healthy(self.base_url)
71
+ except Exception:
72
+ self.stop()
73
+ raise
74
+ self._previous_env_value = os.environ.get(ENV_VAR)
75
+ os.environ[ENV_VAR] = self.base_url
76
+
77
+ def stop(self) -> None:
78
+ """Restore MINERU_API_URL to whatever it was before `start()`, and
79
+ terminate the `mineru-api` subprocess (killing it if it doesn't exit
80
+ within 15s)."""
81
+ if self._previous_env_value is None:
82
+ os.environ.pop(ENV_VAR, None)
83
+ else:
84
+ os.environ[ENV_VAR] = self._previous_env_value
85
+
86
+ if self._process is None:
87
+ return
88
+ self._process.terminate()
89
+ try:
90
+ self._process.wait(timeout=15)
91
+ except subprocess.TimeoutExpired:
92
+ self._process.kill()
93
+ self._process.wait()
94
+ self._process = None
95
+
96
+ def __enter__(self) -> "MineruServer":
97
+ """Call `start()` and return `self`."""
98
+ self.start()
99
+ return self
100
+
101
+ def __exit__(self, exc_type, exc, tb) -> None:
102
+ """Call `stop()`."""
103
+ self.stop()
document2md/tables.py ADDED
@@ -0,0 +1,132 @@
1
+ """Turn the raw HTML tables mineru emits into Markdown tables.
2
+
3
+ mineru renders simple tables as Markdown but falls back to raw HTML
4
+ (``<table>…</table>`` with rowspan/colspan) for anything complex. This module
5
+ rewrites those HTML tables into GitHub Markdown tables so document2md's output is
6
+ Markdown all the way through — no leftover HTML.
7
+
8
+ Implemented with the standard library's ``html.parser`` only (no BeautifulSoup)
9
+ to keep document2md's dependencies to just ``requests`` and ``mineru``.
10
+ """
11
+ import re
12
+ from html.parser import HTMLParser
13
+
14
+ _TABLE_RE = re.compile(r"<table\b[^>]*>.*?</table>", re.DOTALL | re.IGNORECASE)
15
+
16
+
17
+ def html_tables_to_markdown(text: str) -> str:
18
+ """Replace every ``<table>…</table>`` block in `text` with a GitHub
19
+ Markdown table, leaving everything else untouched. Blank lines are ensured
20
+ around each converted table so it renders as a table."""
21
+
22
+ def _replace(match: "re.Match") -> str:
23
+ rows = _parse_rows(match.group(0))
24
+ rendered = _render(rows)
25
+ return f"\n\n{rendered}\n\n" if rendered else match.group(0)
26
+
27
+ return re.sub(r"\n{3,}", "\n\n", _TABLE_RE.sub(_replace, text))
28
+
29
+
30
+ class _TableParser(HTMLParser):
31
+ """Collect a single HTML table's cells as rows of (text, attrs)."""
32
+
33
+ def __init__(self):
34
+ super().__init__(convert_charrefs=True)
35
+ self.rows: list[list[tuple[str, dict]]] = []
36
+ self._row: list[tuple[str, dict]] | None = None
37
+ self._cell: list[str] | None = None
38
+ self._cell_attrs: dict = {}
39
+
40
+ def handle_starttag(self, tag, attrs):
41
+ """Open a new row on `<tr>`, a new cell (recording its attrs, for
42
+ rowspan/colspan) on `<td>`/`<th>`, and turn `<br>` inside a cell into
43
+ a space so wrapped lines don't run together."""
44
+ tag = tag.lower()
45
+ if tag == "tr":
46
+ self._row = []
47
+ elif tag in ("td", "th"):
48
+ self._cell = []
49
+ self._cell_attrs = {k.lower(): v for k, v in attrs}
50
+ elif tag == "br" and self._cell is not None:
51
+ self._cell.append(" ")
52
+
53
+ def handle_endtag(self, tag):
54
+ """Close the current cell into `self._row` on `</td>`/`</th>`, and
55
+ the current row into `self.rows` on `</tr>`."""
56
+ tag = tag.lower()
57
+ if tag in ("td", "th") and self._cell is not None and self._row is not None:
58
+ self._row.append(("".join(self._cell), self._cell_attrs))
59
+ self._cell = None
60
+ elif tag == "tr" and self._row is not None:
61
+ self.rows.append(self._row)
62
+ self._row = None
63
+
64
+ def handle_data(self, data):
65
+ """Append text content to the currently-open cell, if any."""
66
+ if self._cell is not None:
67
+ self._cell.append(data)
68
+
69
+
70
+ def _parse_rows(fragment: str) -> list[list[tuple[str, dict]]]:
71
+ """Parse a single ``<table>…</table>`` fragment into `_TableParser`'s row
72
+ structure."""
73
+ parser = _TableParser()
74
+ parser.feed(fragment)
75
+ parser.close()
76
+ return parser.rows
77
+
78
+
79
+ def _span(attrs: dict, name: str) -> int:
80
+ """Read `attrs[name]` (`rowspan`/`colspan`) as a positive int, defaulting
81
+ to 1 when it is missing or not a valid integer."""
82
+ try:
83
+ return max(1, int(attrs.get(name, 1)))
84
+ except (TypeError, ValueError):
85
+ return 1
86
+
87
+
88
+ def _clean_cell(text: str) -> str:
89
+ """Collapse a cell's whitespace to single spaces and escape `|` so it
90
+ can't be mistaken for a Markdown table column separator."""
91
+ return re.sub(r"\s+", " ", text).strip().replace("|", r"\|")
92
+
93
+
94
+ def _grid(rows: list[list[tuple[str, dict]]]) -> list[list[str]]:
95
+ """Flatten rows into a rectangular grid honouring rowspan/colspan. A
96
+ spanned cell's text goes in its top-left slot; the covered slots are filled
97
+ with empty strings, since Markdown tables can't merge cells."""
98
+ filled: dict[tuple[int, int], str] = {}
99
+ n_cols = 0
100
+ for r, row in enumerate(rows):
101
+ c = 0
102
+ for text, attrs in row:
103
+ while (r, c) in filled:
104
+ c += 1
105
+ row_span = _span(attrs, "rowspan")
106
+ col_span = _span(attrs, "colspan")
107
+ cell = _clean_cell(text)
108
+ for dr in range(row_span):
109
+ for dc in range(col_span):
110
+ filled[(r + dr, c + dc)] = cell if (dr == 0 and dc == 0) else ""
111
+ c += col_span
112
+ n_cols = max(n_cols, c)
113
+ return [[filled.get((r, c), "") for c in range(n_cols)] for r in range(len(rows))]
114
+
115
+
116
+ def _render(rows: list[list[tuple[str, dict]]]) -> str:
117
+ """Render `_grid(rows)` as a GitHub Markdown table (first row as the
118
+ header), or `""` if the table has no rows/columns."""
119
+ grid = _grid(rows)
120
+ if not grid or not grid[0]:
121
+ return ""
122
+
123
+ n_cols = max(len(row) for row in grid)
124
+ grid = [row + [""] * (n_cols - len(row)) for row in grid]
125
+
126
+ lines = [
127
+ "| " + " | ".join(grid[0]) + " |",
128
+ "|" + "---|" * n_cols,
129
+ ]
130
+ for row in grid[1:]:
131
+ lines.append("| " + " | ".join(row) + " |")
132
+ return "\n".join(lines)
@@ -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,13 @@
1
+ document2md/__init__.py,sha256=aj7I0ERFad-qtEX6Qk88AuLuJdQIRGYwBMOrGvH-VoI,98
2
+ document2md/batch.py,sha256=8cmHuD1VsFEz9kt42x9o0Oq64TQHZq_XaXagSjLfExw,4582
3
+ document2md/cli.py,sha256=esehDNiKuWW4lmy76pBoOx6UVy3wKZBWA69Rn1kcNic,4454
4
+ document2md/converter.py,sha256=Le9CRTMACQvkI3FZtlKIKQp7IdF9c6iYEADwXCMjqdE,8555
5
+ document2md/cutter.py,sha256=ZyrP42tL3m-dQJD7aR4qKlziipgGeiGlH-Q4wPPGlUA,7778
6
+ document2md/mineru_server.py,sha256=oOIJDeQX-hNWmDPZC7Jl2PqzrEcrp-SGf0oW6_nz1LU,3983
7
+ document2md/tables.py,sha256=r6JxI1Jo_jqBKybaS8tn7-Ot20MMAi5PVkebBzhK8cI,5023
8
+ document2md-0.3.0.dist-info/licenses/LICENSE,sha256=wA3K6wenbE9W-CRkfkqA9A1yrSnjX1HF7d39YPBI91Q,11338
9
+ document2md-0.3.0.dist-info/METADATA,sha256=fh3DXuj5WZ_VMFcwbzlUD42QNSRK4EIStVQ_pN5r_9k,5204
10
+ document2md-0.3.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
11
+ document2md-0.3.0.dist-info/entry_points.txt,sha256=YX6oFN0auVrrJTKynBI60PUqTVUcvolxyrJ8f2ogPXg,53
12
+ document2md-0.3.0.dist-info/top_level.txt,sha256=AIczvx4b8KEaa7kjtp7aGbZDtr8t-kspvlXKKqNOS7w,12
13
+ document2md-0.3.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ document2md = document2md.cli:main
@@ -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 @@
1
+ document2md