Repository navigation
Expand file tree
/
Copy pathtablepatch.py
More file actions
305 lines (280 loc) · 15.2 KB
/
Copy pathtablepatch.py
File metadata and controls
305 lines (280 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
"""Propose bounded missing table-bottom edges without modifying source PDFs.
The geometry heuristic is deliberately conservative. Proposals are not proof
that cells are correct; inspect the original page before using extracted data.
"""
from __future__ import annotations
import argparse
from collections import Counter
import hashlib
import json
from pathlib import Path
import statistics
import sys
ROOT = Path(__file__).resolve().parent
if (ROOT / '.deps').is_dir():
sys.path.insert(0, str(ROOT / '.deps'))
TOOL_VERSION = '1.0.0'
TOLERANCE = 3.0
def _cluster(values, tolerance=TOLERANCE):
"""Cluster numeric coordinates with a bounded total span, not chaining."""
groups = []
for value in sorted(values):
if not groups or value - groups[-1][0] > tolerance:
groups.append([value])
else:
groups[-1].append(value)
return groups
def _coverage(segments, left, right):
if right <= left:
return 0.0
current = left
length = 0.0
for a, b in sorted((max(left, a), min(right, b)) for a, b in segments):
if b <= a:
continue
start = max(a, current)
length += max(0, b - start)
current = max(current, b)
return length / (right - left)
def infer_from_geometry(edges, chars, table_bboxes, width, height, tolerance=TOLERANCE):
"""Infer possible missing bottoms from repeated vertical-line endpoints.
Only a table's final populated band is considered. Text below a candidate
in the same table region prevents acceptance: this avoids inventing row
separators in intentional merged-cell regions.
"""
verticals = [e for e in edges if e.get('orientation') == 'v'
and e.get('bottom', 0) - e.get('top', 0) >= 8]
horizontals = [e for e in edges if e.get('orientation') == 'h']
candidates = []
for group in _cluster([e['bottom'] for e in verticals], tolerance):
y = statistics.median(group)
supporting = [e for e in verticals if abs(e['bottom'] - y) <= tolerance]
xs = [statistics.median(g) for g in _cluster([e['x0'] for e in supporting], tolerance)]
if len(xs) < 3 or xs[-1] - xs[0] < 40:
continue
# The table may currently end at its last closed row, above the missing
# bottom. Permit extension only along existing connected verticals.
matches = [bbox for bbox in table_bboxes
if bbox[0] - tolerance <= xs[0] <= xs[-1] <= bbox[2] + tolerance
and bbox[1] + 4 < y <= bbox[3] + height * 0.20]
if not matches:
continue
bbox = min(matches, key=lambda b: abs(min(y, b[3]) - y))
x0, x1 = bbox[0], bbox[2]
# Do not extend a rule across another independently detected table.
if _coverage([(e['x0'], e['x1']) for e in horizontals
if abs(e['top'] - y) <= tolerance], x0, x1) >= 0.95:
continue
reasons = []
full_rules = [e['top'] for e in horizontals
if bbox[1] - tolerance <= e['top'] < y - 4
and _coverage([(h['x0'], h['x1']) for h in horizontals
if abs(h['top'] - e['top']) <= tolerance], x0, x1) >= 0.90]
row_top = max(full_rules) if full_rules else None
if row_top is None:
reasons.append('no_spanning_row_top')
elif y - row_top > height * 0.20:
reasons.append('row_band_too_tall')
connected = [e for e in supporting if row_top is not None and e['top'] <= row_top + tolerance]
connected_xs = [statistics.median(g) for g in _cluster([e['x0'] for e in connected], tolerance)]
if len(connected_xs) < 3:
reasons.append('insufficient_connected_separators')
if (xs[-1] - xs[0]) / max(x1 - x0, 1) < 0.40:
reasons.append('narrow_endpoint_support')
boundaries = sorted(set([x0, *connected_xs, x1]))
boundaries = [statistics.median(g) for g in _cluster(boundaries, tolerance)]
band_chars = [c for c in chars if row_top is not None
and c.get('text', '').strip()
and x0 <= (c['x0'] + c['x1']) / 2 <= x1
and row_top <= (c['top'] + c['bottom']) / 2 < y]
populated = 0
for left, right in zip(boundaries, boundaries[1:]):
if any(left <= (c['x0'] + c['x1']) / 2 < right for c in band_chars):
populated += 1
if populated < 3:
reasons.append('fewer_than_three_populated_columns')
crossing = [c for c in chars if c.get('text', '').strip()
and c['x1'] > x0 and c['x0'] < x1
and c['top'] + 0.5 < y < c['bottom'] - 0.5]
if crossing:
reasons.append('text_crosses_candidate')
# A continuation of the grid below the candidate can indicate a merged
# cell rather than a missing bottom; require no text there.
lower_limit = max(bbox[3], y)
below = [c for c in chars if c.get('text', '').strip()
and x0 <= (c['x0'] + c['x1']) / 2 <= x1
and y + tolerance < (c['top'] + c['bottom']) / 2 < lower_limit]
if below:
reasons.append('text_below_candidate_in_table')
# Both sides must be anchored to a vertical segment spanning this band.
side_anchors = 0
if row_top is not None:
for x in (x0, x1):
if any(abs(e['x0'] - x) <= tolerance and e['top'] <= row_top + tolerance
and e['bottom'] >= y - tolerance for e in verticals):
side_anchors += 1
if side_anchors != 2:
reasons.append('missing_side_anchor')
candidates.append({
'y': round(y, 4), 'x0': round(x0, 4), 'x1': round(x1, 4),
'support': len(connected_xs), 'accepted': not reasons,
'reasons': reasons or ['aligned_endpoints_and_populated_final_band'],
'evidence': {'row_top': round(row_top, 4) if row_top is not None else None,
'populated_columns': populated, 'side_anchors': side_anchors,
'text_crossings': len(crossing), 'text_below': len(below),
'support_x': [round(x, 4) for x in connected_xs],
'table_bbox': [round(x, 4) for x in bbox]},
})
# Multiple distinct candidates in one table are ambiguous; do not guess.
accepted_counts = Counter(tuple(c['evidence']['table_bbox']) for c in candidates if c['accepted'])
for candidate in candidates:
if candidate['accepted'] and accepted_counts[tuple(candidate['evidence']['table_bbox'])] > 1:
candidate['accepted'] = False
candidate['reasons'] = ['multiple_bottom_candidates_in_table']
return candidates
def _table_data(table, text_settings):
return {'bbox': [round(x, 4) for x in table.bbox],
'rows': table.extract(**text_settings),
'cell_bboxes': [[None if cell is None else [round(x, 4) for x in cell]
for cell in row.cells] for row in table.rows]}
def _check_unaffected_cells(baseline, proposed, candidates):
"""Ensure adding a boundary does not change cells outside that boundary."""
proposed_cells = {}
for table in proposed:
for values, boxes in zip(table['rows'], table['cell_bboxes']):
for value, bbox in zip(values, boxes):
if bbox is not None:
proposed_cells[tuple(bbox)] = value
checked = 0
failures = []
for table in baseline:
for values, boxes in zip(table['rows'], table['cell_bboxes']):
for value, bbox in zip(values, boxes):
if bbox is None:
continue
affected = any(bbox[1] < c['y'] < bbox[3]
and c['x1'] > bbox[0] and c['x0'] < bbox[2]
for c in candidates)
if affected:
continue
checked += 1
if tuple(bbox) not in proposed_cells or proposed_cells[tuple(bbox)] != value:
failures.append({'bbox': bbox, 'baseline': value,
'proposed': proposed_cells.get(tuple(bbox)),
'missing_bbox': tuple(bbox) not in proposed_cells})
return {'checked_cells': checked, 'failures': failures, 'passed': not failures}
def analyze_page(page, table_settings=None):
from pdfplumber.table import TableFinder, TableSettings
settings = dict(table_settings or {})
resolved = TableSettings.resolve(settings)
finder = TableFinder(page, settings)
baseline = [_table_data(t, resolved.text_settings) for t in finder.tables]
result = {'page': page.page_number, 'width': page.width, 'height': page.height,
'status': 'unchanged', 'reason': '未发现满足规则的缺失底边候选。',
'candidates': [], 'baseline_tables': baseline,
'proposed_tables': baseline, 'warnings': []}
if not page.chars:
result.update(status='review', reason='页面没有可用文字层,未执行自动边界推断。')
result['warnings'].append('未实现 OCR;扫描页需要其他处理。')
return result
if resolved.vertical_strategy not in ('lines', 'lines_strict') or resolved.horizontal_strategy not in ('lines', 'lines_strict'):
result.update(status='review', reason='自动推断仅支持基于表格线的提取策略。')
return result
candidates = infer_from_geometry(finder.edges, page.chars, [t.bbox for t in finder.tables], page.width, page.height)
result['candidates'] = candidates
accepted = [c for c in candidates if c['accepted']]
if accepted:
extra = [dict(object_type='line', x0=c['x0'], x1=c['x1'], top=c['y'], bottom=c['y'],
y0=page.height - c['y'], y1=page.height - c['y'],
width=c['x1'] - c['x0'], height=0) for c in accepted]
proposal_settings = {**settings, 'explicit_horizontal_lines': list(settings.get('explicit_horizontal_lines', [])) + extra}
proposal_finder = TableFinder(page, proposal_settings)
proposed = [_table_data(t, resolved.text_settings) for t in proposal_finder.tables]
preservation = _check_unaffected_cells(baseline, proposed, accepted)
result['preservation_check'] = preservation
if not preservation['passed']:
for candidate in accepted:
candidate['accepted'] = False
candidate['reasons'] = ['unaffected_cells_changed']
result.update(status='review', reason='候选边界影响到其他原有单元格,已撤回提取候选。')
result['warnings'].append('原始提取结果已保留;未采用发生旁侧变化的候选。')
return result
result['proposed_tables'] = proposed
# Exact row data equality is relevant here; bboxes can change without
# changing text. Such geometric-only proposals remain reviewable.
if proposed != baseline:
result.update(status='proposal', reason='已生成基于边界证据的提取候选,请对照原页核验。')
else:
result.update(status='review', reason='发现边界候选,但加入后没有改变提取结果。')
result['warnings'].append('候选结果未经自动真值认证;请检查列对应关系和原文,原 PDF 未修改。')
elif candidates:
result.update(status='review', reason='发现可疑边界,但证据不足,保留原提取结果。')
if not baseline:
result.update(status='review', reason='未找到可作为边界推断依据的有线表格。')
return result
def analyze_pdf(path, pages=None, table_settings=None):
import pdfplumber
source = Path(path).expanduser().resolve()
if not source.is_file():
raise FileNotFoundError(f'PDF not found: {source}')
with source.open('rb') as stream:
digest = hashlib.file_digest(stream, 'sha256').hexdigest() if hasattr(hashlib, 'file_digest') else hashlib.sha256(stream.read()).hexdigest()
results = []
with pdfplumber.open(source) as pdf:
selected = list(range(1, len(pdf.pages) + 1)) if pages is None else list(dict.fromkeys(pages))
if not selected or any(not isinstance(p, int) or isinstance(p, bool) or p < 1 or p > len(pdf.pages) for p in selected):
raise ValueError(f'Page numbers must be integers from 1 to {len(pdf.pages)}')
for number in selected:
page = pdf.pages[number - 1]
results.append(analyze_page(page, table_settings))
page.close()
page_count = len(pdf.pages)
statuses = Counter(r['status'] for r in results)
return {'schema_version': 1, 'tool_version': TOOL_VERSION,
'pdfplumber_version': pdfplumber.__version__,
'source': {'filename': source.name, 'sha256': digest, 'pages': page_count},
'settings': {'table_settings': table_settings or {}, 'endpoint_tolerance_points': TOLERANCE,
'scope': 'digital_ruled_tables_final_band', 'source_modified': False},
'results': results,
'summary': {'pages_analyzed': len(results), 'proposal_pages': statuses['proposal'],
'unchanged_pages': statuses['unchanged'], 'review_pages': statuses['review'],
'accepted_candidates': sum(c['accepted'] for r in results for c in r['candidates'])}}
def parse_pages(text):
output = []
for part in text.split(','):
if '-' in part:
ends = part.split('-')
if len(ends) != 2:
raise ValueError('Use page lists such as 1,3,7-9')
start, end = map(int, ends)
if start < 1 or end < start or end - start > 10000:
raise ValueError('Invalid or excessive page range')
output.extend(range(start, end + 1))
else:
value = int(part)
if value < 1:
raise ValueError('Pages are 1-based')
output.append(value)
return list(dict.fromkeys(output))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('pdf', type=Path)
parser.add_argument('--pages', help='1-based pages, for example 1,3,7-9; default all pages')
parser.add_argument('--settings', type=Path, help='Optional pdfplumber table settings JSON')
parser.add_argument('--output', type=Path, default=Path('output/report.json'))
args = parser.parse_args()
try:
settings = json.loads(args.settings.read_text(encoding='utf-8')) if args.settings else None
if settings is not None and not isinstance(settings, dict):
raise ValueError('Settings must be a JSON object')
report = analyze_pdf(args.pdf, parse_pages(args.pages) if args.pages else None, settings)
if args.output.resolve() == args.pdf.resolve():
raise ValueError('Output must not overwrite the source PDF')
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
print(json.dumps(report['summary'], ensure_ascii=False))
print(f'Report saved: {args.output.resolve()}')
except Exception as error:
parser.exit(1, f'{type(error).__name__}: {error}\n')
if __name__ == '__main__':
main()