Repository navigation
Expand file tree
/
Copy pathbatch.py
More file actions
193 lines (172 loc) · 11.2 KB
/
Copy pathbatch.py
File metadata and controls
193 lines (172 loc) · 11.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
"""Process a bounded PDF batch locally, with a separate review for each input."""
from __future__ import annotations
import argparse
from collections import Counter
from datetime import datetime
import hashlib
from html import escape
import json
from pathlib import Path
import re
from urllib.parse import quote
import webbrowser
from launch import run_job
from tablepatch import parse_pages
ROOT = Path(__file__).resolve().parent
MAX_FILES = 100
MAX_PAGES = 200
MAX_INPUT_BYTES = 100 * 1024 * 1024
def input_digest(source: Path) -> str:
if not source.is_file():
raise FileNotFoundError(f'PDF not found: {source}')
digest = hashlib.sha256()
total = 0
with source.open('rb') as stream:
for chunk in iter(lambda: stream.read(1024 * 1024), b''):
total += len(chunk)
if total > MAX_INPUT_BYTES:
raise ValueError('Input exceeds the batch limit of 100 MiB per file.')
digest.update(chunk)
return digest.hexdigest()
def selected_pages(pages):
if pages is None:
return None
values = list(pages)
if not values or any(type(value) is not int or value < 1 for value in values):
raise ValueError('Pages must be positive integers, or None for all pages.')
values = list(dict.fromkeys(values))
if len(values) > MAX_PAGES:
raise ValueError(f'Choose at most {MAX_PAGES} pages per file.')
return values
def preflight(source, pages):
import pdfplumber
with pdfplumber.open(source) as pdf:
count = len(pdf.pages)
if count == 0:
raise ValueError('PDF has no pages.')
if pages is None and count > MAX_PAGES:
raise ValueError(f'PDF has {count} pages; select at most {MAX_PAGES} with --pages.')
if pages is not None and max(pages) > count:
raise ValueError(f'Requested page {max(pages)} exceeds this PDF\'s {count} pages.')
return count
def file_id(position, name):
stem = re.sub(r'[^A-Za-z0-9_-]+', '-', Path(name).stem).strip('-_')[:48] or 'document'
return f'{position:03d}-{stem}'
def render_index(manifest):
summary = manifest['summary']
cards = []
labels = {'completed': '处理完成,待核验', 'failed': '处理失败', 'pending': '尚未处理'}
for item in manifest['files']:
state = item['status']
details = ''
if state == 'completed':
counts = item['pages']
details = (f'<p>已分析 {counts["analyzed"]} 页 · 存在提案 {counts["proposal"]} 页 · '
f'保留原样 {counts["unchanged"]} 页 · 需要核验 {counts["review"]} 页</p>'
f'<div class="links"><a href="{quote(item["review_html"], safe="/")}">打开对照审核</a>'
f'<a href="{quote(item["report_json"], safe="/")}">查看提取 JSON</a></div>')
elif state == 'failed':
details = f'<pre class="error">{escape(item["error"]["type"])}: {escape(item["error"]["message"])}</pre>'
digest = item['input_sha256'] or '未取得输入校验值'
cards.append(f'<article class="card {state}"><div class="card-top"><h2>{item["position"]:03d} · '
f'{escape(item["input_name"])}</h2><span class="status">{labels[state]}</span></div>'
f'<p class="path">{escape(item["input"])}</p>{details}'
f'<details><summary>输入文件 SHA256</summary><code>{escape(digest)}</code></details></article>')
page_label = '全部页面(每个文件最多 200 页)' if manifest['requested_pages'] is None else ', '.join(map(str, manifest['requested_pages']))
return f'''<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>TablePatch · 批次审核</title><style>
:root{{color-scheme:light;font-family:system-ui,-apple-system,"Segoe UI",sans-serif;color:#18323f;background:#f4f3ed}}
*{{box-sizing:border-box}}body{{margin:0}}header{{background:#17313e;color:#fff;padding:42px max(20px,calc((100% - 1040px)/2))}}
.eyebrow{{letter-spacing:.16em;font-size:12px;color:#bed1d6}}h1{{font-size:clamp(28px,4vw,42px);margin:12px 0}}header p{{line-height:1.7;color:#d9e4e5;max-width:760px}}
main{{max-width:1080px;margin:auto;padding:24px 20px 44px}}.summary{{display:flex;flex-wrap:wrap;gap:10px;margin-bottom:20px}}
.summary span{{background:#fff;border:1px solid #d5dfdd;border-radius:7px;padding:10px 16px}}.summary strong{{font-size:22px;margin-right:6px}}
.meta{{display:flex;align-items:center;justify-content:space-between;gap:14px;flex-wrap:wrap;margin:20px 0;color:#52676d}}
.card{{background:#fff;border:1px solid #d9e0dc;border-left:5px solid #3d7d72;border-radius:9px;margin:14px 0;padding:20px}}
.card.failed{{border-left-color:#bb593a}}.card.pending{{border-left-color:#93a0a0}}.card-top{{display:flex;align-items:baseline;justify-content:space-between;gap:12px;flex-wrap:wrap}}
h2{{font-size:19px;margin:0;overflow-wrap:anywhere}}.status{{font-size:13px;background:#edf3ef;padding:5px 9px;border-radius:20px;white-space:nowrap}}
.failed .status{{background:#f9eae2;color:#8b361e}}.path{{color:#65787e;font-size:13px;overflow-wrap:anywhere}}p{{line-height:1.6}}
a{{color:#8c4024;text-underline-offset:3px}}.links{{display:flex;gap:18px;flex-wrap:wrap;margin:14px 0}}.links a:first-child{{font-weight:650}}
details{{font-size:12px;color:#66777d;margin-top:16px}}summary{{cursor:pointer}}code{{display:block;margin-top:8px;overflow-wrap:anywhere}}
.error{{font:13px/1.6 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;color:#8b361e;background:#fff5ee;padding:12px;border-radius:5px}}
footer{{font-size:12px;line-height:1.7;color:#64777c;margin-top:28px}}@media(max-width:480px){{header{{padding:28px 18px}}main{{padding:18px 12px}}.card{{padding:16px}}}}
</style></head><body><header><div class="eyebrow">TABLEPATCH / LOCAL BATCH REVIEW</div>
<h1>逐份查看提取结果</h1><p>每个文件有独立的原图与前后对照。“处理完成”表示报告已生成,提取内容仍需核验。失败文件不会阻止其他文件继续处理。</p></header>
<main><div class="summary"><span><strong>{summary['total']}</strong>个文件</span><span><strong>{summary['completed']}</strong>已完成</span>
<span><strong>{summary['failed']}</strong>失败</span><span><strong>{summary['pending']}</strong>待处理</span></div>
<div class="meta"><span>请求页码:{page_label}</span><a href="manifest.json">查看批次清单 JSON</a></div>
{''.join(cards)}<footer>结果在本机生成,没有上传 PDF。各文件的审核备注需要在对应页面导出后保存。若要移动或发送本批次,请保留整个文件夹及其子目录。</footer>
</main></body></html>'''
def write_manifest(output_dir, manifest):
statuses = Counter(item['status'] for item in manifest['files'])
manifest['summary'] = {'total': len(manifest['files']), 'completed': statuses['completed'],
'failed': statuses['failed'], 'pending': statuses['pending']}
documents = {'manifest.json': json.dumps(manifest, ensure_ascii=False, sort_keys=True, indent=2) + '\n',
'index.html': render_index(manifest)}
for filename, content in documents.items():
temporary = output_dir / ('.' + filename + '.tmp')
temporary.write_text(content, encoding='utf-8', newline='\n')
temporary.replace(output_dir / filename)
def run_batch(sources, output_dir, pages=(1,)):
sources = [Path(source).expanduser() for source in sources]
if not 1 <= len(sources) <= MAX_FILES:
raise ValueError(f'Provide between 1 and {MAX_FILES} PDF inputs.')
pages = selected_pages(pages)
output_dir = Path(output_dir).expanduser().resolve()
# This check is enforced by mkdir itself, including empty existing paths.
output_dir.mkdir(parents=True, exist_ok=False)
(output_dir / 'files').mkdir()
manifest = {'schema_version': 1, 'kind': 'tablepatch_batch', 'requested_pages': pages,
'core_sha256': hashlib.sha256((ROOT / 'tablepatch.py').read_bytes()).hexdigest(),
'files': [{'position': position, 'id': file_id(position, source.name),
'input': source.as_posix(), 'input_name': source.name, 'input_sha256': None,
'status': 'pending', 'report_json': None, 'review_html': None,
'pages': None, 'error': None}
for position, source in enumerate(sources, 1)]}
write_manifest(output_dir, manifest)
for source, item in zip(sources, manifest['files']):
try:
item['input_sha256'] = input_digest(source)
preflight(source, pages)
relative_dir = Path('files') / item['id']
destination = output_dir / relative_dir
destination.mkdir(exist_ok=False)
review = Path(run_job(source, pages, destination))
expected_review = destination / 'index.html'
if review.resolve() != expected_review or not expected_review.is_file():
raise ValueError('Processing did not produce the expected review HTML.')
report = json.loads((destination / 'report.json').read_text(encoding='utf-8'))
if report['source']['sha256'] != item['input_sha256'] or input_digest(source) != item['input_sha256']:
raise ValueError('Input PDF changed during batch processing; generated output is not marked complete.')
counts = Counter(result['status'] for result in report['results'])
item.update(status='completed', report_json=(relative_dir / 'report.json').as_posix(),
review_html=(relative_dir / 'index.html').as_posix(),
pages={'analyzed': len(report['results']), 'proposal': counts['proposal'],
'unchanged': counts['unchanged'], 'review': counts['review']})
except Exception as error:
item['status'] = 'failed'
item['error'] = {'type': type(error).__name__,
'message': str(error).replace(str(output_dir), '<batch-output>')}
write_manifest(output_dir, manifest)
return manifest
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('pdfs', nargs='+', type=Path, help='PDF files, processed in the supplied order')
parser.add_argument('--pages', default='1', help='Common page list, e.g. 1,3-5, or all; default: 1')
parser.add_argument('--output', type=Path, help='New batch directory; an existing path is rejected')
parser.add_argument('--open', action='store_true', help='Open the batch index after processing')
args = parser.parse_args(argv)
try:
pages = None if args.pages.lower() == 'all' else parse_pages(args.pages)
output_dir = args.output or ROOT / 'runs' / ('batch-' + datetime.now().strftime('%Y%m%d-%H%M%S-%f'))
manifest = run_batch(args.pdfs, output_dir, pages)
except (ValueError, OSError) as error:
parser.error(str(error))
print(json.dumps(manifest['summary'], ensure_ascii=False))
index = output_dir.expanduser().resolve() / 'index.html'
print('Batch review:', index)
if args.open:
webbrowser.open(index.as_uri())
return 1 if manifest['summary']['failed'] else 0
if __name__ == '__main__':
raise SystemExit(main())