kalamos 0.1.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.
- kalamos/__init__.py +12 -0
- kalamos/__main__.py +3 -0
- kalamos/backends/__init__.py +15 -0
- kalamos/backends/base.py +39 -0
- kalamos/backends/docling.py +43 -0
- kalamos/backends/external.py +49 -0
- kalamos/backends/marker.py +54 -0
- kalamos/backends/mineru.py +46 -0
- kalamos/backends/textlayer.py +24 -0
- kalamos/checks.py +224 -0
- kalamos/cli.py +141 -0
- kalamos/garble.py +81 -0
- kalamos/ocr.py +55 -0
- kalamos/pipeline.py +263 -0
- kalamos/postprocess.py +21 -0
- kalamos/recover.py +68 -0
- kalamos/reference.py +379 -0
- kalamos/text.py +103 -0
- kalamos-0.1.0.dist-info/METADATA +148 -0
- kalamos-0.1.0.dist-info/RECORD +26 -0
- kalamos-0.1.0.dist-info/WHEEL +4 -0
- kalamos-0.1.0.dist-info/entry_points.txt +2 -0
- kalamos-0.1.0.dist-info/licenses/LICENSE +22 -0
- kalamos-0.1.0.dist-info/licenses/LICENSES/Apache-2.0.txt +202 -0
- kalamos-0.1.0.dist-info/licenses/LICENSES/MIT-pdfmux.txt +21 -0
- kalamos-0.1.0.dist-info/licenses/NOTICE +37 -0
kalamos/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""kalamos: PDF to markdown that checks its own work.
|
|
2
|
+
|
|
3
|
+
kalamos runs proven layout engines (MinerU, marker, docling), checks every page
|
|
4
|
+
against the text layer of the PDF, puts back text an engine dropped, and falls
|
|
5
|
+
back page by page to the next engine when a check fails.
|
|
6
|
+
"""
|
|
7
|
+
__version__ = "0.1.0"
|
|
8
|
+
|
|
9
|
+
from .checks import PageScore, Thresholds, score_page # noqa: E402
|
|
10
|
+
from .pipeline import Document, convert # noqa: E402
|
|
11
|
+
|
|
12
|
+
__all__ = ["convert", "Document", "Thresholds", "PageScore", "score_page", "__version__"]
|
kalamos/__main__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Conversion backends. Each one is optional except the text layer."""
|
|
2
|
+
from .base import Backend, BackendUnavailable
|
|
3
|
+
from .docling import DoclingBackend
|
|
4
|
+
from .marker import MarkerBackend
|
|
5
|
+
from .mineru import MinerUBackend
|
|
6
|
+
from .textlayer import TextLayerBackend
|
|
7
|
+
|
|
8
|
+
REGISTRY: dict[str, type[Backend]] = {
|
|
9
|
+
"docling": DoclingBackend,
|
|
10
|
+
"marker": MarkerBackend,
|
|
11
|
+
"mineru": MinerUBackend,
|
|
12
|
+
"textlayer": TextLayerBackend,
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
__all__ = ["Backend", "BackendUnavailable", "REGISTRY"]
|
kalamos/backends/base.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""The interface that every conversion backend implements."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from abc import ABC, abstractmethod
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class BackendUnavailable(RuntimeError):
|
|
9
|
+
"""The backend is not installed or cannot run here."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Backend(ABC):
|
|
13
|
+
#: Name used on the command line and in reports.
|
|
14
|
+
name: str = ""
|
|
15
|
+
#: Extra that installs the backend, as in ``pip install kalamos[docling]``.
|
|
16
|
+
extra: str = ""
|
|
17
|
+
|
|
18
|
+
@classmethod
|
|
19
|
+
@abstractmethod
|
|
20
|
+
def available(cls) -> bool:
|
|
21
|
+
"""Whether the backend can run in this environment."""
|
|
22
|
+
|
|
23
|
+
@abstractmethod
|
|
24
|
+
def convert(self, pdf: Path, pages: list[int]) -> dict[int, str]:
|
|
25
|
+
"""Convert the given 1-based pages and return markdown for each.
|
|
26
|
+
|
|
27
|
+
A page missing from the result counts as a failed conversion.
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def ranges(pages: list[int]) -> list[tuple[int, int]]:
|
|
32
|
+
"""Group sorted 1-based page numbers into inclusive runs."""
|
|
33
|
+
out: list[tuple[int, int]] = []
|
|
34
|
+
for p in sorted(set(pages)):
|
|
35
|
+
if out and p == out[-1][1] + 1:
|
|
36
|
+
out[-1] = (out[-1][0], p)
|
|
37
|
+
else:
|
|
38
|
+
out.append((p, p))
|
|
39
|
+
return out
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
"""Backend for docling (MIT licence, https://github.com/docling-project/docling)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import importlib.util
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from .base import Backend, BackendUnavailable, ranges
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class DoclingBackend(Backend):
|
|
11
|
+
name = "docling"
|
|
12
|
+
extra = "docling"
|
|
13
|
+
|
|
14
|
+
def __init__(self) -> None:
|
|
15
|
+
self._converter = None
|
|
16
|
+
|
|
17
|
+
@classmethod
|
|
18
|
+
def available(cls) -> bool:
|
|
19
|
+
return importlib.util.find_spec("docling") is not None
|
|
20
|
+
|
|
21
|
+
def _get(self):
|
|
22
|
+
if self._converter is None:
|
|
23
|
+
if not self.available():
|
|
24
|
+
raise BackendUnavailable("pip install 'kalamos[docling]'")
|
|
25
|
+
from docling.document_converter import DocumentConverter
|
|
26
|
+
self._converter = DocumentConverter()
|
|
27
|
+
return self._converter
|
|
28
|
+
|
|
29
|
+
def convert(self, pdf: Path, pages: list[int]) -> dict[int, str]:
|
|
30
|
+
from docling_core.types.doc import ImageRefMode
|
|
31
|
+
|
|
32
|
+
conv = self._get()
|
|
33
|
+
out: dict[int, str] = {}
|
|
34
|
+
for first, last in ranges(pages):
|
|
35
|
+
result = conv.convert(str(pdf), page_range=(first, last), raises_on_error=False)
|
|
36
|
+
doc = result.document
|
|
37
|
+
if doc is None:
|
|
38
|
+
continue
|
|
39
|
+
for p in range(first, last + 1):
|
|
40
|
+
out[p] = doc.export_to_markdown(
|
|
41
|
+
page_no=p, image_mode=ImageRefMode.PLACEHOLDER,
|
|
42
|
+
traverse_pictures=True) # keep text drawn inside figures
|
|
43
|
+
return out
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Shared plumbing for backends that run as a separate program.
|
|
2
|
+
|
|
3
|
+
marker and MinerU each bring their own torch stack and pinned dependencies.
|
|
4
|
+
Running them as separate programs keeps their environments apart, keeps their
|
|
5
|
+
code and model weights out of this package, and lets each be installed where it
|
|
6
|
+
works best (for example with ``uv tool install``).
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
import shutil
|
|
12
|
+
import subprocess
|
|
13
|
+
import tempfile
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from .base import BackendUnavailable
|
|
17
|
+
|
|
18
|
+
#: Environment passed to external tools: never send telemetry, never phone home.
|
|
19
|
+
QUIET_ENV = {
|
|
20
|
+
"MINERU_TELEMETRY_DISABLED": "1",
|
|
21
|
+
"DO_NOT_TRACK": "1",
|
|
22
|
+
"HF_HUB_DISABLE_TELEMETRY": "1",
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def find(program: str, env_var: str) -> str | None:
|
|
27
|
+
"""Locate a program, honouring an override such as KALAMOS_MARKER."""
|
|
28
|
+
override = os.environ.get(env_var)
|
|
29
|
+
if override:
|
|
30
|
+
return override if Path(override).exists() else None
|
|
31
|
+
return shutil.which(program)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def run(cmd: list[str], timeout: float | None = None) -> None:
|
|
35
|
+
env = {**os.environ, **QUIET_ENV}
|
|
36
|
+
proc = subprocess.run(cmd, capture_output=True, text=True, env=env, timeout=timeout)
|
|
37
|
+
if proc.returncode != 0:
|
|
38
|
+
tail = (proc.stderr or proc.stdout).strip().splitlines()[-5:]
|
|
39
|
+
raise RuntimeError("%s exited with %d: %s" % (Path(cmd[0]).name, proc.returncode, " | ".join(tail)))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def workdir() -> tempfile.TemporaryDirectory:
|
|
43
|
+
return tempfile.TemporaryDirectory(prefix="kalamos-")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def require(program: str | None, name: str, hint: str) -> str:
|
|
47
|
+
if not program:
|
|
48
|
+
raise BackendUnavailable("%s not found; %s" % (name, hint))
|
|
49
|
+
return program
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Backend for marker (code Apache 2.0, https://github.com/datalab-to/marker).
|
|
2
|
+
|
|
3
|
+
marker runs as its own program, ``marker_single``. Its model weights are under a
|
|
4
|
+
modified OpenRAIL-M licence with use restrictions; kalamos neither bundles nor
|
|
5
|
+
downloads them, and whoever installs marker accepts that licence.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from .base import Backend
|
|
13
|
+
from .external import find, require, run, workdir
|
|
14
|
+
|
|
15
|
+
# marker separates pages with "\n\n{N}" followed by 48 dashes, N 0-based.
|
|
16
|
+
_PAGE_BREAK = re.compile(r"(?:^|\n\n)\{(\d+)\}-{48}\n\n")
|
|
17
|
+
HINT = "install marker with: uv tool install marker-pdf (or set KALAMOS_MARKER)"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def split_pages(md: str) -> dict[int, str]:
|
|
21
|
+
"""Split paginated marker output into 1-based pages."""
|
|
22
|
+
parts = _PAGE_BREAK.split(md)
|
|
23
|
+
pages: dict[int, str] = {}
|
|
24
|
+
for i in range(1, len(parts) - 1, 2):
|
|
25
|
+
pages[int(parts[i]) + 1] = parts[i + 1].strip()
|
|
26
|
+
return pages
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class MarkerBackend(Backend):
|
|
30
|
+
name = "marker"
|
|
31
|
+
extra = "marker"
|
|
32
|
+
|
|
33
|
+
def __init__(self, timeout: float | None = 1800) -> None:
|
|
34
|
+
self.timeout = timeout
|
|
35
|
+
|
|
36
|
+
@classmethod
|
|
37
|
+
def program(cls) -> str | None:
|
|
38
|
+
return find("marker_single", "KALAMOS_MARKER")
|
|
39
|
+
|
|
40
|
+
@classmethod
|
|
41
|
+
def available(cls) -> bool:
|
|
42
|
+
return cls.program() is not None
|
|
43
|
+
|
|
44
|
+
def convert(self, pdf: Path, pages: list[int]) -> dict[int, str]:
|
|
45
|
+
exe = require(self.program(), "marker_single", HINT)
|
|
46
|
+
with workdir() as tmp:
|
|
47
|
+
run([exe, str(pdf), "--output_dir", tmp, "--output_format", "markdown",
|
|
48
|
+
"--disable_image_extraction", "--paginate_output",
|
|
49
|
+
"--page_range", ",".join(str(p - 1) for p in pages)], self.timeout)
|
|
50
|
+
found = list(Path(tmp).rglob("*.md"))
|
|
51
|
+
if not found:
|
|
52
|
+
return {}
|
|
53
|
+
out = split_pages(found[0].read_text(encoding="utf-8"))
|
|
54
|
+
return {p: md for p, md in out.items() if p in pages}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Backend for MinerU (Apache 2.0 with additional terms,
|
|
2
|
+
https://github.com/opendatalab/MinerU).
|
|
3
|
+
|
|
4
|
+
MinerU runs as its own program, ``mineru-kit``, always locally: kalamos never
|
|
5
|
+
passes ``--remote`` and always sets MINERU_TELEMETRY_DISABLED. MinerU's licence
|
|
6
|
+
adds terms to Apache 2.0, among them that an online service built on MinerU
|
|
7
|
+
must say so; kalamos reports which backend produced each page so that a
|
|
8
|
+
service built on kalamos can comply.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from .base import Backend
|
|
15
|
+
from .external import find, require, run, workdir
|
|
16
|
+
|
|
17
|
+
HINT = "install MinerU with: uv tool install 'mineru[core]' (or set KALAMOS_MINERU)"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class MinerUBackend(Backend):
|
|
21
|
+
name = "mineru"
|
|
22
|
+
extra = "mineru"
|
|
23
|
+
|
|
24
|
+
def __init__(self, tier: str = "standard", timeout: float | None = 1800) -> None:
|
|
25
|
+
self.tier = tier
|
|
26
|
+
self.timeout = timeout
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def program(cls) -> str | None:
|
|
30
|
+
return find("mineru-kit", "KALAMOS_MINERU")
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
def available(cls) -> bool:
|
|
34
|
+
return cls.program() is not None
|
|
35
|
+
|
|
36
|
+
def convert(self, pdf: Path, pages: list[int]) -> dict[int, str]:
|
|
37
|
+
exe = require(self.program(), "mineru-kit", HINT)
|
|
38
|
+
out: dict[int, str] = {}
|
|
39
|
+
for p in pages:
|
|
40
|
+
with workdir() as tmp:
|
|
41
|
+
run([exe, "parse", str(pdf), "-o", tmp, "-p", str(p), "-f", "markdown",
|
|
42
|
+
"--tier", self.tier, "--disable-image-analysis"], self.timeout)
|
|
43
|
+
found = sorted(Path(tmp).rglob("*.md"))
|
|
44
|
+
if found:
|
|
45
|
+
out[p] = found[0].read_text(encoding="utf-8")
|
|
46
|
+
return out
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""The PDF text layer as plain text: always available, never the first choice.
|
|
2
|
+
|
|
3
|
+
It keeps every word the PDF stores but no structure, so it serves as the last
|
|
4
|
+
fallback for a page that every layout backend failed.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from ..reference import text_layer
|
|
11
|
+
from .base import Backend
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class TextLayerBackend(Backend):
|
|
15
|
+
name = "textlayer"
|
|
16
|
+
extra = ""
|
|
17
|
+
|
|
18
|
+
@classmethod
|
|
19
|
+
def available(cls) -> bool:
|
|
20
|
+
return True
|
|
21
|
+
|
|
22
|
+
def convert(self, pdf: Path, pages: list[int]) -> dict[int, str]:
|
|
23
|
+
layer = text_layer(pdf)
|
|
24
|
+
return {p: layer[p - 1].strip() for p in pages if 0 < p <= len(layer)}
|
kalamos/checks.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""Checks that score a converted page against the text layer of the PDF.
|
|
2
|
+
|
|
3
|
+
Each failure that these checks look for has been seen in a widely used
|
|
4
|
+
converter: columns read across the page, words run together, text inside
|
|
5
|
+
figures dropped, blocks moved out of order, images embedded as base64.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from bisect import bisect_left
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
|
|
13
|
+
from .text import bag, strip_math, tokens
|
|
14
|
+
|
|
15
|
+
SHINGLE = 4
|
|
16
|
+
RUN_TOGETHER_LEN = 25
|
|
17
|
+
_BASE64_IMAGE = re.compile(r"data:image/[a-z]+;base64,")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass(frozen=True)
|
|
21
|
+
class Thresholds:
|
|
22
|
+
min_coverage: float = 0.85
|
|
23
|
+
min_precision: float = 0.85
|
|
24
|
+
min_order: float = 0.80
|
|
25
|
+
max_run_together: float = 0.02
|
|
26
|
+
min_reference_words: int = 20
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class PageScore:
|
|
31
|
+
page: int
|
|
32
|
+
reference_words: int
|
|
33
|
+
output_words: int
|
|
34
|
+
coverage: float | None
|
|
35
|
+
precision: float | None
|
|
36
|
+
order: float | None
|
|
37
|
+
run_together: float
|
|
38
|
+
base64_images: int
|
|
39
|
+
missing: list[str] = field(default_factory=list)
|
|
40
|
+
missing_numbers: list[str] = field(default_factory=list)
|
|
41
|
+
problems: list[str] = field(default_factory=list)
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def verifiable(self) -> bool:
|
|
45
|
+
return self.coverage is not None
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def passed(self) -> bool:
|
|
49
|
+
return not self.problems
|
|
50
|
+
|
|
51
|
+
def as_dict(self) -> dict:
|
|
52
|
+
return {
|
|
53
|
+
"page": self.page,
|
|
54
|
+
"reference_words": self.reference_words,
|
|
55
|
+
"output_words": self.output_words,
|
|
56
|
+
"coverage": None if self.coverage is None else round(self.coverage, 4),
|
|
57
|
+
"precision": None if self.precision is None else round(self.precision, 4),
|
|
58
|
+
"order": None if self.order is None else round(self.order, 4),
|
|
59
|
+
"run_together": round(self.run_together, 4),
|
|
60
|
+
"base64_images": self.base64_images,
|
|
61
|
+
"verifiable": self.verifiable,
|
|
62
|
+
"passed": self.passed,
|
|
63
|
+
"problems": self.problems,
|
|
64
|
+
"missing_sample": self.missing[:20],
|
|
65
|
+
"missing_numbers": self.missing_numbers[:20],
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def coverage(ref: list[str], out: list[str]) -> float:
|
|
70
|
+
"""Share of reference words, counted with multiplicity, found in the output."""
|
|
71
|
+
if not ref:
|
|
72
|
+
return 1.0
|
|
73
|
+
rb, ob = bag(ref), bag(out)
|
|
74
|
+
return sum(min(n, ob[w]) for w, n in rb.items()) / len(ref)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def precision(ref: list[str], out: list[str]) -> float:
|
|
78
|
+
"""Share of output words, counted with multiplicity, that the page contains.
|
|
79
|
+
|
|
80
|
+
Low precision means duplicated blocks or text that is not on the page.
|
|
81
|
+
"""
|
|
82
|
+
if not out:
|
|
83
|
+
return 1.0
|
|
84
|
+
rb, ob = bag(ref), bag(out)
|
|
85
|
+
return sum(min(n, rb[w]) for w, n in ob.items()) / len(out)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def order(ref: list[str], out: list[str]) -> float | None:
|
|
89
|
+
"""Agreement of word order between reference and output, from 0 to 1.
|
|
90
|
+
|
|
91
|
+
Runs of SHINGLE words that occur exactly once in both texts serve as
|
|
92
|
+
anchors. The score is the longest run of anchors that appear in the same
|
|
93
|
+
order in both, over the anchors found in the output, so lost text lowers
|
|
94
|
+
coverage but not order. Columns read across the page break most
|
|
95
|
+
anchors apart; a block moved out of place lowers the score in proportion to
|
|
96
|
+
its size. Returns None when too few anchors exist to judge.
|
|
97
|
+
"""
|
|
98
|
+
def grams(t):
|
|
99
|
+
return [tuple(t[i:i + SHINGLE]) for i in range(len(t) - SHINGLE + 1)]
|
|
100
|
+
|
|
101
|
+
rg, og = grams(ref), grams(out)
|
|
102
|
+
rcount, ocount = bag(rg), bag(og)
|
|
103
|
+
opos = {g: i for i, g in enumerate(og) if ocount[g] == 1}
|
|
104
|
+
seq = [opos[g] for g in rg if rcount[g] == 1 and g in opos]
|
|
105
|
+
if len(seq) < 5:
|
|
106
|
+
return None
|
|
107
|
+
tails: list[int] = []
|
|
108
|
+
for x in seq:
|
|
109
|
+
k = bisect_left(tails, x)
|
|
110
|
+
if k == len(tails):
|
|
111
|
+
tails.append(x)
|
|
112
|
+
else:
|
|
113
|
+
tails[k] = x
|
|
114
|
+
return len(tails) / len(seq)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def run_together(md: str) -> float:
|
|
118
|
+
words = md.split()
|
|
119
|
+
if not words:
|
|
120
|
+
return 0.0
|
|
121
|
+
long = [w for w in words
|
|
122
|
+
if len(w) > RUN_TOGETHER_LEN and w.isalpha()]
|
|
123
|
+
return len(long) / len(words)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def missing_words(ref: list[str], out: list[str]) -> list[str]:
|
|
127
|
+
ob = bag(out)
|
|
128
|
+
seen, miss = bag([]), []
|
|
129
|
+
for w in ref:
|
|
130
|
+
seen[w] += 1
|
|
131
|
+
if seen[w] > ob[w] and len(w) > 2:
|
|
132
|
+
miss.append(w)
|
|
133
|
+
return miss
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
# Numeric literals: thousands-grouped numbers, decimals, and integers of four
|
|
137
|
+
# or more digits. Shorter integers are page numbers, list indices and section
|
|
138
|
+
# numbers, which word coverage already counts. Adapted from verifier.py in
|
|
139
|
+
# pdfmux (https://github.com/NameetP/pdfmux, commit ff8c406, MIT License,
|
|
140
|
+
# Copyright (c) 2026 Nameet Potnis); kalamos fails the page on any loss and
|
|
141
|
+
# reads numbers inside LaTeX.
|
|
142
|
+
_NUMBER = re.compile(r"(?<![\w.])(?:\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+\.\d+|\d{4,})(?![\w]|\.\d)")
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def _canonical_number(raw: str) -> str:
|
|
146
|
+
"""1,348,243,150.00 and 1348243150 are the same value."""
|
|
147
|
+
s = raw.replace(",", "")
|
|
148
|
+
whole, _, frac = s.partition(".")
|
|
149
|
+
whole = whole.lstrip("0") or "0"
|
|
150
|
+
frac = frac.rstrip("0")
|
|
151
|
+
return "%s.%s" % (whole, frac) if frac else whole
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
_MATH_SPAN = re.compile(r"\$\$.+?\$\$|\$[^$]+\$|\\\(.+?\\\)|\\\[.+?\\\]", re.S)
|
|
155
|
+
_SPACED_DIGITS = re.compile(r"(?<=[\d.,])\s+(?=[\d.,])")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _join_math_digits(text: str) -> str:
|
|
159
|
+
"""Inside LaTeX, OCR models space out digits ($0 . 0 5$); join them there
|
|
160
|
+
and only there, so two values in prose never merge."""
|
|
161
|
+
return _MATH_SPAN.sub(lambda m: _SPACED_DIGITS.sub("", m.group(0)), text)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _is_year(raw: str) -> bool:
|
|
165
|
+
return len(raw) == 4 and raw.isdigit() and 1900 <= int(raw) <= 2099
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def numbers(text: str):
|
|
169
|
+
"""Canonical values, with years left out: they are dates in headers and
|
|
170
|
+
citations, which word coverage already counts."""
|
|
171
|
+
from collections import Counter
|
|
172
|
+
return Counter(_canonical_number(m.group(0)) for m in _NUMBER.finditer(text)
|
|
173
|
+
if not _is_year(m.group(0)))
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def missing_numbers(reference: str, markdown: str) -> list[str]:
|
|
177
|
+
"""Values on the page that the output has fewer times, or not at all."""
|
|
178
|
+
ref, out = numbers(reference), numbers(_join_math_digits(markdown))
|
|
179
|
+
return sorted(v for v, n in ref.items() if out[v] < n)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def score_page(page: int, reference: str, markdown: str,
|
|
183
|
+
thresholds: Thresholds = Thresholds(), body: str | None = None,
|
|
184
|
+
check_numbers: bool = True) -> PageScore:
|
|
185
|
+
"""Score one converted page.
|
|
186
|
+
|
|
187
|
+
``body`` is the page without running headers, footers and page numbers,
|
|
188
|
+
which converters drop on purpose; coverage and order are measured against
|
|
189
|
+
it. Precision is measured against the whole page, so keeping a header is not
|
|
190
|
+
counted as invented text either.
|
|
191
|
+
"""
|
|
192
|
+
whole = tokens(reference)
|
|
193
|
+
ref = tokens(body) if body is not None else whole
|
|
194
|
+
out = tokens(markdown, markdown=True)
|
|
195
|
+
b64 = len(_BASE64_IMAGE.findall(markdown))
|
|
196
|
+
rt = run_together(markdown)
|
|
197
|
+
s = PageScore(page=page, reference_words=len(ref), output_words=len(out),
|
|
198
|
+
coverage=None, precision=None, order=None, run_together=rt,
|
|
199
|
+
base64_images=b64)
|
|
200
|
+
if b64:
|
|
201
|
+
s.problems.append("base64 images in output")
|
|
202
|
+
if rt > thresholds.max_run_together:
|
|
203
|
+
s.problems.append("words run together (%.1f%% of tokens)" % (100 * rt))
|
|
204
|
+
if len(ref) < thresholds.min_reference_words:
|
|
205
|
+
# A scanned page or a page of figures: nothing to check against.
|
|
206
|
+
if not out and len(ref) > 0:
|
|
207
|
+
s.problems.append("empty output")
|
|
208
|
+
return s
|
|
209
|
+
s.coverage = coverage(ref, out)
|
|
210
|
+
s.precision = precision(whole, tokens(strip_math(markdown), markdown=True))
|
|
211
|
+
s.order = order(ref, out)
|
|
212
|
+
s.missing = missing_words(ref, out)
|
|
213
|
+
if s.coverage < thresholds.min_coverage:
|
|
214
|
+
s.problems.append("text lost (coverage %.1f%%)" % (100 * s.coverage))
|
|
215
|
+
if s.precision < thresholds.min_precision:
|
|
216
|
+
s.problems.append("text not on the page, or duplicated (precision %.1f%%)"
|
|
217
|
+
% (100 * s.precision))
|
|
218
|
+
if s.order is not None and s.order < thresholds.min_order:
|
|
219
|
+
s.problems.append("reading order differs (order %.1f%%)" % (100 * s.order))
|
|
220
|
+
if check_numbers:
|
|
221
|
+
s.missing_numbers = missing_numbers(body if body is not None else reference, markdown)
|
|
222
|
+
if s.missing_numbers:
|
|
223
|
+
s.problems.append("numbers lost or changed: %s" % ", ".join(s.missing_numbers[:5]))
|
|
224
|
+
return s
|
kalamos/cli.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"""Command line: kalamos convert | check | backends."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from .backends import REGISTRY
|
|
12
|
+
from .checks import Thresholds, score_page
|
|
13
|
+
from .pipeline import DEFAULT_BACKENDS, convert
|
|
14
|
+
from .reference import text_layer
|
|
15
|
+
|
|
16
|
+
_PAGE_MARK = re.compile(r"<!-- page (\d+) -->")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _thresholds(a) -> Thresholds:
|
|
20
|
+
return Thresholds(min_coverage=a.min_coverage, min_order=a.min_order,
|
|
21
|
+
max_run_together=a.max_run_together)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class UsageError(Exception):
|
|
25
|
+
"""A mistake in the command line, reported without a traceback."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _pages(spec: str | None) -> list[int] | None:
|
|
29
|
+
"""Parse "1-3,7" into page numbers; reject anything else outright."""
|
|
30
|
+
if spec is None:
|
|
31
|
+
return None
|
|
32
|
+
out: list[int] = []
|
|
33
|
+
for part in spec.split(","):
|
|
34
|
+
a, dash, b = part.strip().partition("-")
|
|
35
|
+
if not a.isdigit() or (dash and not b.isdigit()):
|
|
36
|
+
raise UsageError("bad page range %r; use forms like 2 or 1-3,7" % spec)
|
|
37
|
+
first, last = int(a), int(b) if dash else int(a)
|
|
38
|
+
if first < 1 or last < first:
|
|
39
|
+
raise UsageError("bad page range %r: pages start at 1 and ranges go up" % spec)
|
|
40
|
+
out.extend(range(first, last + 1))
|
|
41
|
+
return out
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def cmd_convert(a) -> int:
|
|
45
|
+
doc = convert(a.pdf, backends=[b for b in a.backends.split(",") if b],
|
|
46
|
+
thresholds=_thresholds(a), recover=not a.no_recover, pages=_pages(a.pages))
|
|
47
|
+
md = doc.markdown(page_markers=not a.no_page_markers)
|
|
48
|
+
if a.output:
|
|
49
|
+
Path(a.output).write_text(md, encoding="utf-8")
|
|
50
|
+
else:
|
|
51
|
+
sys.stdout.write(md)
|
|
52
|
+
rep = doc.report()
|
|
53
|
+
if a.report:
|
|
54
|
+
doc.write_report(a.report)
|
|
55
|
+
print("kalamos: %d pages, %d passed, %d recovered from the text layer, %d cross-checked against OCR, %d unverifiable, %d failed; backends used %s"
|
|
56
|
+
% (rep["pages"], rep["passed"], rep["recovered"], rep["cross_checked"], rep["unverifiable"], rep["failed"],
|
|
57
|
+
json.dumps(rep["backends_used"])), file=sys.stderr)
|
|
58
|
+
for name, why in rep["backends_skipped"].items():
|
|
59
|
+
print("kalamos: skipped %s: %s" % (name, why), file=sys.stderr)
|
|
60
|
+
return 2 if a.strict and rep["failed"] else 0
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def cmd_check(a) -> int:
|
|
64
|
+
reference = text_layer(a.pdf)
|
|
65
|
+
md = Path(a.markdown).read_text(encoding="utf-8")
|
|
66
|
+
pieces = _PAGE_MARK.split(md)
|
|
67
|
+
if len(pieces) > 1:
|
|
68
|
+
pages = {int(pieces[i]): pieces[i + 1] for i in range(1, len(pieces) - 1, 2)}
|
|
69
|
+
scores = [score_page(p, reference[p - 1], text, _thresholds(a))
|
|
70
|
+
for p, text in sorted(pages.items()) if 0 < p <= len(reference)]
|
|
71
|
+
else:
|
|
72
|
+
scores = [score_page(0, "\n".join(reference), md, _thresholds(a))]
|
|
73
|
+
result = {"pdf": Path(a.pdf).name, "markdown": Path(a.markdown).name,
|
|
74
|
+
"pages": [s.as_dict() for s in scores],
|
|
75
|
+
"failed": sum(not s.passed for s in scores)}
|
|
76
|
+
print(json.dumps(result, indent=2))
|
|
77
|
+
return 2 if result["failed"] else 0
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def cmd_backends(a) -> int:
|
|
81
|
+
for name, cls in REGISTRY.items():
|
|
82
|
+
print("%-10s %s" % (name, "available" if cls.available() else "not installed"))
|
|
83
|
+
return 0
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
87
|
+
p = argparse.ArgumentParser(prog="kalamos", description=__doc__)
|
|
88
|
+
p.add_argument("--version", action="version", version="kalamos " + __version__)
|
|
89
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
90
|
+
|
|
91
|
+
def thresholds(sp):
|
|
92
|
+
d = Thresholds()
|
|
93
|
+
sp.add_argument("--min-coverage", type=float, default=d.min_coverage)
|
|
94
|
+
sp.add_argument("--min-order", type=float, default=d.min_order)
|
|
95
|
+
sp.add_argument("--max-run-together", type=float, default=d.max_run_together)
|
|
96
|
+
|
|
97
|
+
c = sub.add_parser("convert", help="convert a PDF to markdown, checking every page")
|
|
98
|
+
c.add_argument("pdf")
|
|
99
|
+
c.add_argument("-o", "--output", help="markdown file (default: standard output)")
|
|
100
|
+
c.add_argument("-b", "--backends", default=",".join(DEFAULT_BACKENDS),
|
|
101
|
+
help="comma-separated order of preference (default: %(default)s)")
|
|
102
|
+
c.add_argument("-p", "--pages", help="1-based pages, as in 1-3,7")
|
|
103
|
+
c.add_argument("--report", help="write the per-page JSON report here")
|
|
104
|
+
c.add_argument("--no-recover", action="store_true", help="do not put back dropped text")
|
|
105
|
+
c.add_argument("--no-page-markers", action="store_true")
|
|
106
|
+
c.add_argument("--strict", action="store_true", help="exit 2 if any page fails its checks")
|
|
107
|
+
thresholds(c)
|
|
108
|
+
c.set_defaults(func=cmd_convert)
|
|
109
|
+
|
|
110
|
+
k = sub.add_parser("check", help="score an existing markdown file against its PDF")
|
|
111
|
+
k.add_argument("pdf")
|
|
112
|
+
k.add_argument("markdown")
|
|
113
|
+
thresholds(k)
|
|
114
|
+
k.set_defaults(func=cmd_check)
|
|
115
|
+
|
|
116
|
+
b = sub.add_parser("backends", help="list backends and whether each is installed")
|
|
117
|
+
b.set_defaults(func=cmd_backends)
|
|
118
|
+
return p
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def main(argv: list[str] | None = None) -> int:
|
|
122
|
+
a = build_parser().parse_args(argv)
|
|
123
|
+
try:
|
|
124
|
+
if hasattr(a, "pdf") and not Path(a.pdf).is_file():
|
|
125
|
+
raise UsageError("no such file: %s" % a.pdf)
|
|
126
|
+
return a.func(a)
|
|
127
|
+
except UsageError as exc:
|
|
128
|
+
print("kalamos: error: %s" % exc, file=sys.stderr)
|
|
129
|
+
return 1
|
|
130
|
+
except ValueError as exc: # unknown backend, page out of range
|
|
131
|
+
print("kalamos: error: %s" % exc, file=sys.stderr)
|
|
132
|
+
return 1
|
|
133
|
+
except Exception as exc: # e.g. a file that is not a PDF
|
|
134
|
+
name = getattr(a, "pdf", "")
|
|
135
|
+
print("kalamos: error: cannot read %s: %s: %s" % (name, type(exc).__name__, exc),
|
|
136
|
+
file=sys.stderr)
|
|
137
|
+
return 1
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
if __name__ == "__main__":
|
|
141
|
+
raise SystemExit(main())
|