pdf-cell-links 0.1.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.
- pdf_cell_links-0.1.0/.github/workflows/release.yml +40 -0
- pdf_cell_links-0.1.0/.gitignore +7 -0
- pdf_cell_links-0.1.0/LICENSE +21 -0
- pdf_cell_links-0.1.0/PKG-INFO +45 -0
- pdf_cell_links-0.1.0/README.md +31 -0
- pdf_cell_links-0.1.0/benchmarks/public_anchors.py +65 -0
- pdf_cell_links-0.1.0/pyproject.toml +27 -0
- pdf_cell_links-0.1.0/src/pdf_cell_links/__init__.py +182 -0
- pdf_cell_links-0.1.0/src/pdf_cell_links/cli.py +40 -0
- pdf_cell_links-0.1.0/tests/test_tables.py +71 -0
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
name: Release
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
release:
|
|
5
|
+
types: [published]
|
|
6
|
+
|
|
7
|
+
permissions:
|
|
8
|
+
contents: read
|
|
9
|
+
|
|
10
|
+
jobs:
|
|
11
|
+
build:
|
|
12
|
+
runs-on: ubuntu-latest
|
|
13
|
+
steps:
|
|
14
|
+
- uses: actions/checkout@v4
|
|
15
|
+
- uses: actions/setup-python@v5
|
|
16
|
+
with:
|
|
17
|
+
python-version: "3.13"
|
|
18
|
+
- run: python -m pip install build
|
|
19
|
+
- run: python -m pip install ".[camelot]" pytest reportlab
|
|
20
|
+
- run: python -m pytest -q
|
|
21
|
+
- run: python -m build
|
|
22
|
+
- uses: actions/upload-artifact@v4
|
|
23
|
+
with:
|
|
24
|
+
name: dist
|
|
25
|
+
path: dist/
|
|
26
|
+
|
|
27
|
+
publish:
|
|
28
|
+
needs: build
|
|
29
|
+
runs-on: ubuntu-latest
|
|
30
|
+
environment:
|
|
31
|
+
name: pypi
|
|
32
|
+
url: https://pypi.org/project/pdf-cell-links/
|
|
33
|
+
permissions:
|
|
34
|
+
id-token: write
|
|
35
|
+
steps:
|
|
36
|
+
- uses: actions/download-artifact@v4
|
|
37
|
+
with:
|
|
38
|
+
name: dist
|
|
39
|
+
path: dist/
|
|
40
|
+
- uses: pypa/gh-action-pypi-publish@release/v1
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Rion Hwang
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pdf-cell-links
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Link multi-page PDF tables while preserving verifiable page-local cell citations.
|
|
5
|
+
Project-URL: Repository, https://github.com/RionHwang0/pdf-cell-links
|
|
6
|
+
Author: Rion Hwang
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Requires-Dist: pdfplumber<1,>=0.11
|
|
11
|
+
Provides-Extra: camelot
|
|
12
|
+
Requires-Dist: camelot-py<2,>=1; extra == 'camelot'
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# pdf-cell-links
|
|
16
|
+
|
|
17
|
+
Cite the original page and rectangle of a cell in a multi-page PDF table. Compare pdfplumber and Camelot results in one coordinate system. Every cell includes its text, PDF SHA-256, page, table, row, column and bounding box in PDF points measured from the top left.
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
pip install pdf-cell-links
|
|
21
|
+
pdf-cell-links report.pdf
|
|
22
|
+
pdf-cell-links report.pdf --find 'Revenue'
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from pdf_cell_links import cells, extract, link, resolve
|
|
27
|
+
|
|
28
|
+
fragments = extract("report.pdf")
|
|
29
|
+
for group in link(fragments):
|
|
30
|
+
for cell in cells(group):
|
|
31
|
+
print(cell.page, cell.bbox, cell.text, cell.reference)
|
|
32
|
+
assert resolve(fragments, cell.reference) == cell
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
To adapt Camelot results, pass its table list, a lowercase SHA-256 of the source bytes and a mapping from 1-based page number to parser page dimensions in points to `from_camelot(tables, pdf_sha256, page_sizes)`. Use the same displayed page geometry for both parsers. A cell reference round-trips with the same parser, settings and version. Compare text, page and rectangles across parsers because their table and cell numbering can differ.
|
|
36
|
+
|
|
37
|
+
The continuation heuristic checks adjacent page boundaries, repeated nonempty headers, column alignment and distance from page edges. Each group keeps its physical rows, including repeated headers and partial rows. Similar tables with identical headers near opposing margins can yield a false link. The default extractor needs machine-readable text and ruling lines. Pass pdfplumber table settings to `extract` for other layouts.
|
|
38
|
+
|
|
39
|
+
## Check original positions in ten public PDFs
|
|
40
|
+
|
|
41
|
+
The [word anchor benchmark](benchmarks/public_anchors.py) compares pdfplumber's returned cells with page and point locations read independently using PyMuPDF. Nine of ten chosen word positions mapped to a unique cell and resolved back by reference. In the Assam document the inner table and a page-sized enclosing table both contained the word. The benchmark reports both candidates. The one-row page continuation keeps the correct physical cell even when its missing repeated header prevents automatic linking. The package tests additionally compare both parsers on the same generated two-page table, including repeated values with separate references.
|
|
42
|
+
|
|
43
|
+
```sh
|
|
44
|
+
python benchmarks/public_anchors.py ./pdf-cache
|
|
45
|
+
```
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
# pdf-cell-links
|
|
2
|
+
|
|
3
|
+
Cite the original page and rectangle of a cell in a multi-page PDF table. Compare pdfplumber and Camelot results in one coordinate system. Every cell includes its text, PDF SHA-256, page, table, row, column and bounding box in PDF points measured from the top left.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pip install pdf-cell-links
|
|
7
|
+
pdf-cell-links report.pdf
|
|
8
|
+
pdf-cell-links report.pdf --find 'Revenue'
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
```python
|
|
12
|
+
from pdf_cell_links import cells, extract, link, resolve
|
|
13
|
+
|
|
14
|
+
fragments = extract("report.pdf")
|
|
15
|
+
for group in link(fragments):
|
|
16
|
+
for cell in cells(group):
|
|
17
|
+
print(cell.page, cell.bbox, cell.text, cell.reference)
|
|
18
|
+
assert resolve(fragments, cell.reference) == cell
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
To adapt Camelot results, pass its table list, a lowercase SHA-256 of the source bytes and a mapping from 1-based page number to parser page dimensions in points to `from_camelot(tables, pdf_sha256, page_sizes)`. Use the same displayed page geometry for both parsers. A cell reference round-trips with the same parser, settings and version. Compare text, page and rectangles across parsers because their table and cell numbering can differ.
|
|
22
|
+
|
|
23
|
+
The continuation heuristic checks adjacent page boundaries, repeated nonempty headers, column alignment and distance from page edges. Each group keeps its physical rows, including repeated headers and partial rows. Similar tables with identical headers near opposing margins can yield a false link. The default extractor needs machine-readable text and ruling lines. Pass pdfplumber table settings to `extract` for other layouts.
|
|
24
|
+
|
|
25
|
+
## Check original positions in ten public PDFs
|
|
26
|
+
|
|
27
|
+
The [word anchor benchmark](benchmarks/public_anchors.py) compares pdfplumber's returned cells with page and point locations read independently using PyMuPDF. Nine of ten chosen word positions mapped to a unique cell and resolved back by reference. In the Assam document the inner table and a page-sized enclosing table both contained the word. The benchmark reports both candidates. The one-row page continuation keeps the correct physical cell even when its missing repeated header prevents automatic linking. The package tests additionally compare both parsers on the same generated two-page table, including repeated values with separate references.
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
python benchmarks/public_anchors.py ./pdf-cache
|
|
31
|
+
```
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Resolve cell references at ten fixed page-local word positions in Camelot's public corpus."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import hashlib
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from urllib.request import urlopen
|
|
7
|
+
|
|
8
|
+
from pdf_cell_links import cells, extract, resolve
|
|
9
|
+
|
|
10
|
+
SOURCE = "https://raw.githubusercontent.com/camelot-dev/camelot/cc60ee97bceca671bd70fb4ee99b0665adf3d77c/tests/files/"
|
|
11
|
+
# Positions in points were read with PyMuPDF's word geometry independently of pdfplumber.
|
|
12
|
+
ANCHORS = [
|
|
13
|
+
("foo", 1, "2012_2", 142, 605),
|
|
14
|
+
("district_health", 1, "Indicators", 91, 93),
|
|
15
|
+
("lattice_one_row_next_page", 2, "2026-02", 81, 50),
|
|
16
|
+
("multiple_tables", 1, "Trtrt", 88, 252),
|
|
17
|
+
("agstat", 1, "District", 115, 185),
|
|
18
|
+
("diesel_engines", 2, "particulars", 138, 119),
|
|
19
|
+
("rainfall_distribution", 1, "Excess", 127, 701),
|
|
20
|
+
("column_span_1", 1, "Suicides", 394, 37),
|
|
21
|
+
("row_span_2", 1, "Disease/", 221, 33),
|
|
22
|
+
("assam", 1, "Person", 219, 111),
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def main():
|
|
27
|
+
parser = argparse.ArgumentParser(description=__doc__)
|
|
28
|
+
parser.add_argument(
|
|
29
|
+
"directory", type=Path, help="Cache directory for pinned public PDFs"
|
|
30
|
+
)
|
|
31
|
+
folder = parser.parse_args().directory
|
|
32
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
33
|
+
unique = 0
|
|
34
|
+
for name, page, word, x, y in ANCHORS:
|
|
35
|
+
path = folder / (name + ".pdf")
|
|
36
|
+
if not path.exists():
|
|
37
|
+
with urlopen(SOURCE + path.name, timeout=30) as response:
|
|
38
|
+
path.write_bytes(response.read())
|
|
39
|
+
fragments = extract(path)
|
|
40
|
+
matches = [
|
|
41
|
+
c
|
|
42
|
+
for c in cells(fragments)
|
|
43
|
+
if c.page == page
|
|
44
|
+
and word in c.text
|
|
45
|
+
and c.bbox[0] <= x <= c.bbox[2]
|
|
46
|
+
and c.bbox[1] <= y <= c.bbox[3]
|
|
47
|
+
]
|
|
48
|
+
# This document has a page-sized enclosing table and a smaller inner table.
|
|
49
|
+
expected = 2 if name == "assam" else 1
|
|
50
|
+
assert len(matches) == expected, (name, [c.reference for c in matches])
|
|
51
|
+
if len(matches) > 1:
|
|
52
|
+
print(path.name, "ambiguous", [c.reference for c in matches])
|
|
53
|
+
continue
|
|
54
|
+
unique += 1
|
|
55
|
+
match = matches[0]
|
|
56
|
+
assert match.pdf_sha256 == hashlib.sha256(path.read_bytes()).hexdigest()
|
|
57
|
+
assert resolve(fragments, match.reference) == match
|
|
58
|
+
print(path.name, word, match.reference)
|
|
59
|
+
print(
|
|
60
|
+
f"{unique}/{len(ANCHORS)} unique word anchors; {len(ANCHORS) - unique} ambiguous"
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
if __name__ == "__main__":
|
|
65
|
+
main()
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pdf-cell-links"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Link multi-page PDF tables while preserving verifiable page-local cell citations."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [{name = "Rion Hwang"}]
|
|
14
|
+
dependencies = ["pdfplumber>=0.11,<1"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
[project.optional-dependencies]
|
|
18
|
+
camelot = ["camelot-py>=1,<2"]
|
|
19
|
+
|
|
20
|
+
[project.scripts]
|
|
21
|
+
pdf-cell-links = "pdf_cell_links.cli:main"
|
|
22
|
+
|
|
23
|
+
[project.urls]
|
|
24
|
+
Repository = "https://github.com/RionHwang0/pdf-cell-links"
|
|
25
|
+
|
|
26
|
+
[tool.hatch.build.targets.wheel]
|
|
27
|
+
packages = ["src/pdf_cell_links"]
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""Page-local source coordinates and conservative continuation links for PDF tables."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
from hashlib import sha256
|
|
7
|
+
from math import isfinite
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class Cell:
|
|
13
|
+
pdf_sha256: str
|
|
14
|
+
page: int
|
|
15
|
+
table: int
|
|
16
|
+
row: int
|
|
17
|
+
column: int
|
|
18
|
+
bbox: tuple[float, float, float, float]
|
|
19
|
+
text: str
|
|
20
|
+
|
|
21
|
+
@property
|
|
22
|
+
def reference(self):
|
|
23
|
+
return f"pdf-cell:{self.pdf_sha256}/{self.page}/{self.table}/{self.row}/{self.column}"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@dataclass(frozen=True)
|
|
27
|
+
class Fragment:
|
|
28
|
+
page: int
|
|
29
|
+
table: int
|
|
30
|
+
width: float
|
|
31
|
+
height: float
|
|
32
|
+
rows: tuple[tuple[Cell, ...], ...]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _fragment(digest, page, table, width, height, rows):
|
|
36
|
+
if not isfinite(width) or not isfinite(height) or min(width, height) <= 0:
|
|
37
|
+
raise ValueError("Invalid page dimensions")
|
|
38
|
+
result = []
|
|
39
|
+
for r, items in enumerate(rows, 1):
|
|
40
|
+
cells = []
|
|
41
|
+
for col, item in enumerate(items, 1):
|
|
42
|
+
if item is None:
|
|
43
|
+
continue
|
|
44
|
+
box, value = item
|
|
45
|
+
left, top, right, bottom = map(float, box)
|
|
46
|
+
if (
|
|
47
|
+
not all(map(isfinite, (left, top, right, bottom)))
|
|
48
|
+
or left >= right
|
|
49
|
+
or top >= bottom
|
|
50
|
+
):
|
|
51
|
+
raise ValueError(
|
|
52
|
+
f"Invalid rectangle on page {page}, row {r}, column {col}"
|
|
53
|
+
)
|
|
54
|
+
cells.append(
|
|
55
|
+
Cell(
|
|
56
|
+
digest, page, table, r, col, (left, top, right, bottom), value or ""
|
|
57
|
+
)
|
|
58
|
+
)
|
|
59
|
+
result.append(tuple(cells))
|
|
60
|
+
return Fragment(page, table, float(width), float(height), tuple(result))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def extract(path, settings=None):
|
|
64
|
+
"""Read ruled text tables using pdfplumber; coordinates are page-local PDF points."""
|
|
65
|
+
import pdfplumber
|
|
66
|
+
|
|
67
|
+
path = Path(path)
|
|
68
|
+
with path.open("rb") as stream:
|
|
69
|
+
digest = sha256()
|
|
70
|
+
for block in iter(lambda: stream.read(1024 * 1024), b""):
|
|
71
|
+
digest.update(block)
|
|
72
|
+
stream.seek(0)
|
|
73
|
+
fragments = []
|
|
74
|
+
with pdfplumber.open(stream) as doc:
|
|
75
|
+
for page in doc.pages:
|
|
76
|
+
x, y = page.bbox[:2]
|
|
77
|
+
for i, table in enumerate(page.find_tables(settings), 1):
|
|
78
|
+
rows = []
|
|
79
|
+
for row, texts in zip(table.rows, table.extract()):
|
|
80
|
+
entries = []
|
|
81
|
+
for box, value in zip(row.cells, texts):
|
|
82
|
+
if box is None:
|
|
83
|
+
entries.append(None)
|
|
84
|
+
else:
|
|
85
|
+
l, t, r, b = box
|
|
86
|
+
entries.append(((l - x, t - y, r - x, b - y), value))
|
|
87
|
+
rows.append(entries)
|
|
88
|
+
fragments.append(
|
|
89
|
+
_fragment(
|
|
90
|
+
digest.hexdigest(),
|
|
91
|
+
page.page_number,
|
|
92
|
+
i,
|
|
93
|
+
page.width,
|
|
94
|
+
page.height,
|
|
95
|
+
rows,
|
|
96
|
+
)
|
|
97
|
+
)
|
|
98
|
+
return fragments
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def from_camelot(tables, pdf_sha256, page_sizes):
|
|
102
|
+
"""Adapt Camelot Table objects; pass the parser's (width, height) for each page."""
|
|
103
|
+
if len(pdf_sha256) != 64 or any(c not in "0123456789abcdef" for c in pdf_sha256):
|
|
104
|
+
raise ValueError("Expected a lowercase SHA-256 digest of the PDF")
|
|
105
|
+
fragments = []
|
|
106
|
+
seen = set()
|
|
107
|
+
for table in tables:
|
|
108
|
+
page, index = int(table.page), int(table.order)
|
|
109
|
+
if min(page, index) < 1 or (page, index) in seen:
|
|
110
|
+
raise ValueError("Expected unique positive page and table numbers")
|
|
111
|
+
seen.add((page, index))
|
|
112
|
+
width, height = page_sizes[page]
|
|
113
|
+
rows = [
|
|
114
|
+
[
|
|
115
|
+
((c.x1, height - c.y2, c.x2, height - c.y1), c.text.rstrip("\n"))
|
|
116
|
+
for c in row
|
|
117
|
+
]
|
|
118
|
+
for row in table.cells
|
|
119
|
+
]
|
|
120
|
+
fragments.append(_fragment(pdf_sha256, page, index, width, height, rows))
|
|
121
|
+
return fragments
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _continues(previous, current, tolerance, edge):
|
|
125
|
+
if (
|
|
126
|
+
current.page != previous.page + 1
|
|
127
|
+
or len(previous.rows) < 2
|
|
128
|
+
or len(current.rows) < 2
|
|
129
|
+
):
|
|
130
|
+
return False
|
|
131
|
+
first, second = previous.rows[0], current.rows[0]
|
|
132
|
+
if len(first) < 2 or len(first) != len(second) or not previous.rows[-1]:
|
|
133
|
+
return False
|
|
134
|
+
if first[0].pdf_sha256 != second[0].pdf_sha256:
|
|
135
|
+
return False
|
|
136
|
+
for a, b in zip(first, second):
|
|
137
|
+
label = " ".join(a.text.casefold().split())
|
|
138
|
+
if (
|
|
139
|
+
not label
|
|
140
|
+
or label != " ".join(b.text.casefold().split())
|
|
141
|
+
or a.column != b.column
|
|
142
|
+
):
|
|
143
|
+
return False
|
|
144
|
+
if any(
|
|
145
|
+
abs(a.bbox[i] / previous.width - b.bbox[i] / current.width) > tolerance
|
|
146
|
+
for i in (0, 2)
|
|
147
|
+
):
|
|
148
|
+
return False
|
|
149
|
+
return (
|
|
150
|
+
max(c.bbox[3] for c in previous.rows[-1]) >= previous.height * (1 - edge)
|
|
151
|
+
and min(c.bbox[1] for c in second) <= current.height * edge
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def link(fragments, *, tolerance=0.012, edge=0.22):
|
|
156
|
+
"""Group adjacent boundary fragments with repeated headers. Preserve every physical row."""
|
|
157
|
+
if not 0 <= tolerance < 1 or not 0 <= edge < 0.5:
|
|
158
|
+
raise ValueError("Invalid column tolerance or page edge fraction")
|
|
159
|
+
groups, seen = [], set()
|
|
160
|
+
for fragment in sorted(fragments, key=lambda f: (f.page, f.table)):
|
|
161
|
+
key = (fragment.page, fragment.table)
|
|
162
|
+
if key in seen:
|
|
163
|
+
raise ValueError("Duplicate page and table index")
|
|
164
|
+
seen.add(key)
|
|
165
|
+
if groups and _continues(groups[-1][-1], fragment, tolerance, edge):
|
|
166
|
+
groups[-1].append(fragment)
|
|
167
|
+
else:
|
|
168
|
+
groups.append([fragment])
|
|
169
|
+
return groups
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def cells(fragments):
|
|
173
|
+
for fragment in fragments:
|
|
174
|
+
for row in fragment.rows:
|
|
175
|
+
yield from row
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def resolve(fragments, reference):
|
|
179
|
+
for cell in cells(fragments):
|
|
180
|
+
if cell.reference == reference:
|
|
181
|
+
return cell
|
|
182
|
+
raise KeyError(reference)
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
import json
|
|
3
|
+
from dataclasses import asdict
|
|
4
|
+
|
|
5
|
+
from . import cells, extract, link, resolve
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main():
|
|
9
|
+
parser = argparse.ArgumentParser(
|
|
10
|
+
description="Look up original PDF table cells and page-local rectangles."
|
|
11
|
+
)
|
|
12
|
+
parser.add_argument("pdf")
|
|
13
|
+
query = parser.add_mutually_exclusive_group()
|
|
14
|
+
query.add_argument("--find", help="Match a case-sensitive substring of cell text")
|
|
15
|
+
query.add_argument(
|
|
16
|
+
"--ref",
|
|
17
|
+
help="Resolve a fingerprinted cell citation with the same parser settings",
|
|
18
|
+
)
|
|
19
|
+
args = parser.parse_args()
|
|
20
|
+
fragments = extract(args.pdf)
|
|
21
|
+
if args.find is None and args.ref is None:
|
|
22
|
+
print(json.dumps([[[f.page, f.table] for f in g] for g in link(fragments)]))
|
|
23
|
+
return
|
|
24
|
+
if args.ref:
|
|
25
|
+
try:
|
|
26
|
+
selected = [resolve(fragments, args.ref)]
|
|
27
|
+
except KeyError:
|
|
28
|
+
parser.exit(1, "No matching cell reference\n")
|
|
29
|
+
else:
|
|
30
|
+
selected = [c for c in cells(fragments) if args.find in c.text]
|
|
31
|
+
print(
|
|
32
|
+
json.dumps(
|
|
33
|
+
[dict(asdict(c), reference=c.reference) for c in selected],
|
|
34
|
+
ensure_ascii=False,
|
|
35
|
+
)
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
if __name__ == "__main__":
|
|
40
|
+
main()
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
from hashlib import sha256
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from pdf_cell_links import cells, extract, from_camelot, link, resolve
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def test_reference_and_grouping():
|
|
9
|
+
from types import SimpleNamespace as Obj
|
|
10
|
+
|
|
11
|
+
digest = "a" * 64
|
|
12
|
+
|
|
13
|
+
def table(page, offset, heading="Amount"):
|
|
14
|
+
def row(labels, top):
|
|
15
|
+
return [
|
|
16
|
+
Obj(
|
|
17
|
+
x1=50 + i * 100,
|
|
18
|
+
y1=top - 20,
|
|
19
|
+
x2=150 + i * 100,
|
|
20
|
+
y2=top,
|
|
21
|
+
text=label + "\n",
|
|
22
|
+
)
|
|
23
|
+
for i, label in enumerate(labels)
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
return Obj(
|
|
27
|
+
page=page,
|
|
28
|
+
order=1,
|
|
29
|
+
cells=[row(["Year", heading], offset), row(["2025", "17"], offset - 20)],
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
tables = [table(1, 100), table(2, 760), table(3, 760, "Item"), table(5, 760)]
|
|
33
|
+
fragments = from_camelot(tables, digest, dict.fromkeys([1, 2, 3, 5], (600, 800)))
|
|
34
|
+
assert [[f.page for f in group] for group in link(fragments)] == [[1, 2], [3], [5]]
|
|
35
|
+
item = fragments[1].rows[1][1]
|
|
36
|
+
assert item.bbox == (150, 60, 250, 80)
|
|
37
|
+
assert resolve(fragments, item.reference).text == "17"
|
|
38
|
+
with pytest.raises(KeyError):
|
|
39
|
+
resolve(fragments, item.reference.replace(digest, "b" * 64))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def test_real_pdf(tmp_path):
|
|
43
|
+
canvas = pytest.importorskip("reportlab.pdfgen.canvas")
|
|
44
|
+
pytest.importorskip("pdfplumber")
|
|
45
|
+
path = tmp_path / "two-pages.pdf"
|
|
46
|
+
pdf = canvas.Canvas(str(path), pagesize=(600, 800))
|
|
47
|
+
for top in [100, 760]:
|
|
48
|
+
for x in [50, 150, 250]:
|
|
49
|
+
pdf.line(x, top, x, top - 40)
|
|
50
|
+
for y in [top, top - 20, top - 40]:
|
|
51
|
+
pdf.line(50, y, 250, y)
|
|
52
|
+
for i, labels in enumerate([["Year", "Amount"], ["2025", "17"]]):
|
|
53
|
+
for j, label in enumerate(labels):
|
|
54
|
+
pdf.drawString(55 + 100 * j, top - 15 - 20 * i, label)
|
|
55
|
+
pdf.showPage()
|
|
56
|
+
pdf.save()
|
|
57
|
+
fragments = extract(path)
|
|
58
|
+
assert [len(g) for g in link(fragments)] == [2]
|
|
59
|
+
digest = sha256(path.read_bytes()).hexdigest()
|
|
60
|
+
assert [c.page for c in cells(fragments) if c.text == "17"] == [1, 2]
|
|
61
|
+
assert all(c.pdf_sha256 == digest for c in cells(fragments))
|
|
62
|
+
camelot = pytest.importorskip("camelot")
|
|
63
|
+
parsed = from_camelot(
|
|
64
|
+
camelot.read_pdf(str(path), pages="all", flavor="lattice", line_scale=60),
|
|
65
|
+
digest,
|
|
66
|
+
{1: (600, 800), 2: (600, 800)},
|
|
67
|
+
)
|
|
68
|
+
assert [len(g) for g in link(parsed)] == [2]
|
|
69
|
+
for a, b in zip(cells(fragments), cells(parsed), strict=True):
|
|
70
|
+
assert (a.text, a.page) == (b.text, b.page)
|
|
71
|
+
assert max(abs(x - y) for x, y in zip(a.bbox, b.bbox)) < 2
|