feat(shipping-notice): 添加 MinerU 订单附件表格结构化功能,更新环境配置和数据模型以支持新布局解析和文档模板管理
This commit is contained in:
1 parent
c4095b08da
commit
c35223d49d
148 files changed
+15709
-1353
No files matched your search
@@ -0,0 +1,291 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
backend/scripts/build_shipping_layout_truth_workbench.py
|
||||
|
||||
用途:从受控 EML 样本生成仓库外的离线 PDF cell 真值标注工作台,并校验导出结果。
|
||||
依赖:MinerU adapter、pypdfium2、Pillow、OpenCV 候选和 layout annotation 契约。
|
||||
逻辑:附件仅在内存中解析;页面图、候选文本和人工 JSON 只写显式仓库外目录,控制台只输出哈希与计数。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import html
|
||||
import json
|
||||
import sys
|
||||
from email import policy
|
||||
from email.parser import BytesParser
|
||||
from hashlib import sha256
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import pypdfium2 as pdfium
|
||||
from PIL import Image
|
||||
|
||||
BACKEND_ROOT = Path(__file__).resolve().parents[1]
|
||||
REPOSITORY_ROOT = BACKEND_ROOT.parent
|
||||
if str(BACKEND_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(BACKEND_ROOT))
|
||||
|
||||
from app.services.shipping_notice.document_layout.evaluation import LayoutAnnotation
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.mineru import (
|
||||
MinerUClient,
|
||||
MinerUClientConfig,
|
||||
parse_mineru_candidate,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.opencv_table import (
|
||||
reconstruct_opencv_table_geometry,
|
||||
validate_opencv_cell_text,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.text_cell_alignment import (
|
||||
align_html_cells_from_positioned_text,
|
||||
)
|
||||
|
||||
|
||||
def _external_output_path(raw: str | Path) -> Path:
|
||||
"""解析并验证输出目录必须位于 Git 仓库外,避免真实样本被误提交。"""
|
||||
path = Path(raw).expanduser().resolve()
|
||||
try:
|
||||
path.relative_to(REPOSITORY_ROOT.resolve())
|
||||
except ValueError:
|
||||
return path
|
||||
raise ValueError('layout truth workbench output must be outside the repository')
|
||||
|
||||
|
||||
def _iter_pdf_attachments(eml_dir: Path):
|
||||
"""从 EML 内存读取唯一 PDF 附件;不把文件名或邮件正文写入输出。"""
|
||||
seen: set[str] = set()
|
||||
for eml_path in sorted(eml_dir.glob('*.eml')):
|
||||
message = BytesParser(policy=policy.default).parsebytes(eml_path.read_bytes())
|
||||
for part in message.walk():
|
||||
filename = str(part.get_filename() or '')
|
||||
if not filename.lower().endswith('.pdf'):
|
||||
continue
|
||||
content = part.get_payload(decode=True) or b''
|
||||
digest = sha256(content).hexdigest()
|
||||
if not content or digest in seen:
|
||||
continue
|
||||
seen.add(digest)
|
||||
yield digest, content
|
||||
|
||||
|
||||
def _positioned_characters(text_page: Any, *, page_height: float) -> list[dict[str, Any]]:
|
||||
"""把 PDFium 左下原点字符框转换为版面契约使用的左上原点坐标。"""
|
||||
result: list[dict[str, Any]] = []
|
||||
for index in range(text_page.count_chars()):
|
||||
text = text_page.get_text_range(index, 1)
|
||||
if not text:
|
||||
continue
|
||||
left, bottom, right, top = text_page.get_charbox(index, loose=True)
|
||||
if right <= left or top <= bottom:
|
||||
continue
|
||||
result.append({
|
||||
'text': text,
|
||||
'bbox': {'x0': left, 'y0': page_height - top, 'x1': right, 'y1': page_height - bottom},
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def _candidate_tables(parse_candidate: Any, pdf: Any, *, image_scale: float) -> tuple[list[dict], list[dict]]:
|
||||
"""生成页面图片元数据和严格 cell 候选;候选不等同人工真值。"""
|
||||
pages: list[dict[str, Any]] = []
|
||||
tables: list[dict[str, Any]] = []
|
||||
page_map = {item.page_no: item for item in parse_candidate.pages}
|
||||
for page_no in range(1, len(pdf) + 1):
|
||||
page = pdf[page_no - 1]
|
||||
width, height = page.get_size()
|
||||
pages.append({'page_no': page_no, 'width': width, 'height': height})
|
||||
candidate_page = page_map.get(page_no)
|
||||
if candidate_page is None or not candidate_page.tables:
|
||||
continue
|
||||
bitmap = page.render(scale=image_scale)
|
||||
image = np.asarray(bitmap.to_numpy()).copy()
|
||||
text_page = page.get_textpage()
|
||||
characters = _positioned_characters(text_page, page_height=height)
|
||||
for table_index, table in enumerate(candidate_page.tables):
|
||||
grid = parse_html_grid(table.html, table_id=table.candidate_id)
|
||||
geometry = reconstruct_opencv_table_geometry(
|
||||
image,
|
||||
page_width=width,
|
||||
page_height=height,
|
||||
table_bbox=table.bbox,
|
||||
grid=grid,
|
||||
)
|
||||
cell_boxes: dict[str, dict[str, float]] = {}
|
||||
candidate_source = 'none'
|
||||
if geometry.ready:
|
||||
def bounded_text_reader(box):
|
||||
return text_page.get_text_bounded(
|
||||
left=box.x0,
|
||||
bottom=height - box.y1,
|
||||
right=box.x1,
|
||||
top=height - box.y0,
|
||||
)
|
||||
|
||||
validation = validate_opencv_cell_text(
|
||||
geometry,
|
||||
grid=grid,
|
||||
bounded_text_reader=bounded_text_reader,
|
||||
)
|
||||
if validation.accepted:
|
||||
cell_boxes = {item.cell_id: item.normalized_bbox.model_dump() for item in geometry.cells}
|
||||
candidate_source = 'opencv_text_validated'
|
||||
if not cell_boxes:
|
||||
alignment = align_html_cells_from_positioned_text(
|
||||
grid,
|
||||
characters=characters,
|
||||
table_bbox=table.bbox,
|
||||
page_width=width,
|
||||
page_height=height,
|
||||
)
|
||||
cell_boxes = {item.cell_id: item.normalized_bbox.model_dump() for item in alignment.cells}
|
||||
candidate_source = 'native_text_partial' if cell_boxes else 'none'
|
||||
tables.append({
|
||||
'annotation_id': f'table-p{page_no}-{table_index}',
|
||||
'page_no': page_no,
|
||||
'table_index': table_index,
|
||||
'normalized_bbox': table.normalized_bbox.model_dump(),
|
||||
'candidate_source': candidate_source,
|
||||
'cells': [{
|
||||
'annotation_id': f'cell-p{page_no}-{table_index}-{index}',
|
||||
'page_no': page_no,
|
||||
'table_index': table_index,
|
||||
'row_index': cell.row_index,
|
||||
'column_index': cell.column_index,
|
||||
'normalized_bbox': cell_boxes.get(cell.cell_id),
|
||||
'normalized_text': cell.text,
|
||||
'role': 'header' if cell.is_header else 'data',
|
||||
'expected_field_code': None,
|
||||
} for index, cell in enumerate(grid.cells)],
|
||||
})
|
||||
return pages, tables
|
||||
|
||||
|
||||
def _write_page_images(pdf: Any, sample_dir: Path, *, image_scale: float) -> None:
|
||||
"""渲染清晰页面图供人工框选;只写仓库外样本目录。"""
|
||||
for page_index in range(len(pdf)):
|
||||
image = pdf[page_index].render(scale=image_scale).to_pil().convert('RGB')
|
||||
image.save(sample_dir / f'page-{page_index + 1}.png', optimize=True)
|
||||
|
||||
|
||||
def _workbench_html(manifest: dict[str, Any]) -> str:
|
||||
"""生成无外部依赖的离线标注页面,导出结果符合 annotation.v1。"""
|
||||
payload = json.dumps(manifest, ensure_ascii=False).replace('</', '<\\/')
|
||||
return f'''<!doctype html>
|
||||
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<title>Shipping Layout Truth Workbench</title><style>
|
||||
body{{margin:0;font:14px system-ui;background:#f1f5f9;color:#0f172a}} header{{padding:12px 18px;background:#0f172a;color:white}}
|
||||
main{{display:grid;grid-template-columns:300px 1fr 320px;height:calc(100vh - 48px)}} aside{{overflow:auto;padding:12px;background:white;border-right:1px solid #cbd5e1}}
|
||||
#stage{{overflow:auto;padding:18px}} #canvasWrap{{position:relative;display:inline-block;background:white;box-shadow:0 2px 12px #94a3b8}}
|
||||
canvas{{display:block;cursor:crosshair}} button,input,select{{box-sizing:border-box;margin:3px 0;padding:7px;border:1px solid #94a3b8;border-radius:6px}}
|
||||
button{{cursor:pointer;background:white}} button.primary{{background:#2563eb;color:white}} .item{{padding:7px;margin:4px 0;border:1px solid #e2e8f0;border-radius:6px;cursor:pointer}}
|
||||
.item.active{{border-color:#2563eb;background:#eff6ff}} .bad{{color:#b91c1c}} label{{display:block;margin-top:8px;color:#475569}} .row{{display:flex;gap:6px;flex-wrap:wrap}}
|
||||
</style></head><body><header>订单 PDF Cell 真值标注 - 样本 {html.escape(manifest['sample_id'])}</header>
|
||||
<main><aside><div id="pages"></div><hr><div class="row"><button id="addTable">新增表格</button><button id="addCell">新增 Cell</button></div><div id="items"></div></aside>
|
||||
<section id="stage"><div id="canvasWrap"><canvas id="canvas"></canvas></div></section>
|
||||
<aside><div id="editor"></div><hr><button class="primary" id="export">导出 annotation.json</button><button id="validate">本地完整性检查</button><pre id="status"></pre></aside></main>
|
||||
<script>const state={payload},canvas=document.querySelector('#canvas'),ctx=canvas.getContext('2d');let page=1,selected=null,drawing=null,img=new Image();
|
||||
const pageData=()=>state.pages.find(x=>x.page_no===page), tables=()=>state.tables.filter(x=>x.page_no===page), boxPx=b=>[b.x0*canvas.width,b.y0*canvas.height,b.x1*canvas.width,b.y1*canvas.height];
|
||||
function loadPage(n){{page=n;img=new Image();img.onload=()=>{{canvas.width=img.width;canvas.height=img.height;draw()}};img.src=`page-${{n}}.png`;renderLists()}}
|
||||
function draw(){{ctx.drawImage(img,0,0);for(const t of tables()){{drawBox(t.normalized_bbox,'#2563eb',t===selected?5:2);for(const c of t.cells)if(c.normalized_bbox)drawBox(c.normalized_bbox,c===selected?'#dc2626':'#f59e0b',c===selected?5:2)}}if(drawing)drawBox(drawing,'#16a34a',3)}}
|
||||
function drawBox(b,color,w){{const [x0,y0,x1,y1]=boxPx(b);ctx.strokeStyle=color;ctx.lineWidth=w;ctx.strokeRect(x0,y0,x1-x0,y1-y0)}}
|
||||
function renderLists(){{document.querySelector('#pages').innerHTML='<b>页面</b>'+state.pages.map(p=>`<button onclick="loadPage(${{p.page_no}})">${{p.page_no}}</button>`).join('');document.querySelector('#items').innerHTML=tables().map(t=>`<div class="item ${{t===selected?'active':''}}" onclick="pick('${{t.annotation_id}}')">表 ${{t.table_index}} (${{t.candidate_source}})</div>`+t.cells.map(c=>`<div class="item ${{c===selected?'active':''}}" onclick="pick('${{c.annotation_id}}')">r${{c.row_index}} c${{c.column_index}} ${{c.normalized_bbox?'':'<span class=bad>待画框</span>'}}</div>`).join('')).join('');renderEditor();draw()}}
|
||||
window.pick=id=>{{selected=state.tables.find(t=>t.annotation_id===id)||state.tables.flatMap(t=>t.cells).find(c=>c.annotation_id===id);renderLists()}};window.loadPage=loadPage;
|
||||
function renderEditor(){{const e=document.querySelector('#editor');if(!selected){{e.innerHTML='请选择表格或 Cell';return}}const cell='row_index'in selected;e.innerHTML=`<b>${{cell?'Cell':'表格'}}</b><label>normalized_text</label><input id="txt" value="${{esc(selected.normalized_text||'')}}" ${{cell?'':'disabled'}}><label>role</label><select id="role" ${{cell?'':'disabled'}}>${{['header','data','summary','deleted','empty'].map(x=>`<option ${{selected.role===x?'selected':''}}>${{x}}</option>`).join('')}}</select><label>expected_field_code</label><input id="field" value="${{esc(selected.expected_field_code||'')}}" ${{cell?'':'disabled'}}><div class=row><button id="redraw">重画框</button><button id="remove">删除</button></div>`;if(cell){{e.querySelector('#txt').oninput=x=>selected.normalized_text=x.target.value;e.querySelector('#role').onchange=x=>selected.role=x.target.value;e.querySelector('#field').oninput=x=>selected.expected_field_code=x.target.value||null}}e.querySelector('#redraw').onclick=()=>{{drawing='armed';status('请在页面拖拽矩形')}};e.querySelector('#remove').onclick=()=>{{for(const t of state.tables){{if(t===selected)state.tables=state.tables.filter(x=>x!==t);else t.cells=t.cells.filter(x=>x!==selected)}}selected=null;renderLists()}}}}
|
||||
function esc(v){{return String(v).replace(/[&<>"']/g,x=>({{'&':'&','<':'<','>':'>','"':'"',"'":'''}}[x]))}}
|
||||
canvas.onpointerdown=e=>{{if(drawing!=='armed')return;const r=canvas.getBoundingClientRect();drawing={{x0:(e.clientX-r.left)/r.width,y0:(e.clientY-r.top)/r.height,x1:0,y1:0}}}};canvas.onpointermove=e=>{{if(!drawing||drawing==='armed')return;const r=canvas.getBoundingClientRect();drawing.x1=(e.clientX-r.left)/r.width;drawing.y1=(e.clientY-r.top)/r.height;draw()}};canvas.onpointerup=()=>{{if(!drawing||drawing==='armed'||!selected)return;selected.normalized_bbox={{x0:Math.min(drawing.x0,drawing.x1),y0:Math.min(drawing.y0,drawing.y1),x1:Math.max(drawing.x0,drawing.x1),y1:Math.max(drawing.y0,drawing.y1)}};drawing=null;renderLists()}};
|
||||
document.querySelector('#addTable').onclick=()=>{{const i=state.tables.length;const t={{annotation_id:`table-manual-${{i}}`,page_no:page,table_index:tables().length,normalized_bbox:null,candidate_source:'manual',cells:[]}};state.tables.push(t);selected=t;drawing='armed';renderLists()}};
|
||||
document.querySelector('#addCell').onclick=()=>{{const t=tables()[0];if(!t)return status('当前页需先有表格');const i=t.cells.length,c={{annotation_id:`cell-manual-${{page}}-${{t.table_index}}-${{i}}`,page_no:page,table_index:t.table_index,row_index:0,column_index:0,normalized_bbox:null,normalized_text:'',role:'data',expected_field_code:null}};t.cells.push(c);selected=c;drawing='armed';renderLists()}};
|
||||
function annotation(){{return{{schema_version:'shipping_document_layout_annotation.v1',layout_schema_version:'shipping_document_layout.v1',sample_id:state.sample_id,content_hash:state.content_hash,categories:state.categories,tables:state.tables.map(t=>({{annotation_id:t.annotation_id,page_no:t.page_no,table_index:t.table_index,normalized_bbox:t.normalized_bbox,cells:t.cells.map(c=>({{annotation_id:c.annotation_id,page_no:c.page_no,table_index:c.table_index,row_index:+c.row_index,column_index:+c.column_index,normalized_bbox:c.normalized_bbox,normalized_text:c.normalized_text,role:c.role,expected_field_code:c.expected_field_code||null}})),continuation_of:t.continuation_of||null}}))}}}}
|
||||
function problems(){{const a=annotation(),p=[];for(const t of a.tables){{if(!t.normalized_bbox)p.push(`${{t.annotation_id}} 缺表框`);for(const c of t.cells)if(!c.normalized_bbox)p.push(`${{c.annotation_id}} 缺 cell 框`)}}return p}}
|
||||
document.querySelector('#validate').onclick=()=>{{const p=problems();status(p.length?p.join('\n'):'浏览器基础检查通过;请再运行脚本 validate')}};document.querySelector('#export').onclick=()=>{{const p=problems();if(p.length)return status(p.join('\n'));const blob=new Blob([JSON.stringify(annotation(),null,2)],{{type:'application/json'}}),a=document.createElement('a');a.href=URL.createObjectURL(blob);a.download=`${{state.sample_id}}.annotation.json`;a.click();URL.revokeObjectURL(a.href)}};function status(v){{document.querySelector('#status').textContent=v}}loadPage(1);
|
||||
</script></body></html>'''
|
||||
|
||||
|
||||
def build_workbench(args: argparse.Namespace) -> int:
|
||||
"""调用 MinerU 并为每个唯一 PDF 生成仓库外离线标注页面。"""
|
||||
source = Path(args.eml_dir).expanduser().resolve()
|
||||
output = _external_output_path(args.output_dir)
|
||||
output.mkdir(parents=True, exist_ok=True)
|
||||
index_rows: list[str] = []
|
||||
count = 0
|
||||
for digest, content in _iter_pdf_attachments(source):
|
||||
if args.limit and count >= args.limit:
|
||||
break
|
||||
client = MinerUClient(MinerUClientConfig(
|
||||
base_url=args.mineru_url,
|
||||
backend='pipeline',
|
||||
read_timeout_seconds=args.timeout,
|
||||
poll_interval_seconds=1,
|
||||
))
|
||||
candidate = parse_mineru_candidate(client.parse_file_async(filename='sample.pdf', content=content))
|
||||
pdf = pdfium.PdfDocument(content)
|
||||
sample_id = f'pdf-{digest[:12]}'
|
||||
sample_dir = output / sample_id
|
||||
sample_dir.mkdir(parents=True, exist_ok=True)
|
||||
_write_page_images(pdf, sample_dir, image_scale=args.image_scale)
|
||||
pages, tables = _candidate_tables(candidate, pdf, image_scale=args.image_scale)
|
||||
manifest = {
|
||||
'sample_id': sample_id,
|
||||
'content_hash': digest,
|
||||
'categories': ['native_pdf', 'eml_attachment'],
|
||||
'pages': pages,
|
||||
'tables': tables,
|
||||
}
|
||||
(sample_dir / 'workbench.html').write_text(_workbench_html(manifest), encoding='utf-8')
|
||||
index_rows.append(f'<li><a href="{sample_id}/workbench.html">{sample_id}</a> - {len(pages)} pages, {len(tables)} tables</li>')
|
||||
count += 1
|
||||
print(f'generated sample={sample_id} pages={len(pages)} tables={len(tables)}')
|
||||
(output / 'index.html').write_text(
|
||||
'<!doctype html><meta charset="utf-8"><h1>Shipping Layout Truth Workbench</h1><ol>'
|
||||
+ ''.join(index_rows) + '</ol>',
|
||||
encoding='utf-8',
|
||||
)
|
||||
print(f'generated_count={count} output={output}')
|
||||
return 0
|
||||
|
||||
|
||||
def validate_annotations(args: argparse.Namespace) -> int:
|
||||
"""使用正式 annotation.v1 契约校验单个 JSON 或目录中的全部导出。"""
|
||||
target = Path(args.path).expanduser().resolve()
|
||||
files = [target] if target.is_file() else sorted(target.rglob('*.annotation.json'))
|
||||
if not files:
|
||||
print('no annotation files found', file=sys.stderr)
|
||||
return 2
|
||||
failed = 0
|
||||
for path in files:
|
||||
try:
|
||||
annotation = LayoutAnnotation.model_validate_json(path.read_text(encoding='utf-8'))
|
||||
print(f'valid sample={annotation.sample_id} tables={len(annotation.tables)} cells={sum(len(t.cells) for t in annotation.tables)}')
|
||||
except Exception as exc:
|
||||
failed += 1
|
||||
print(f'invalid file={path.name} error={type(exc).__name__}', file=sys.stderr)
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
"""解析 build/validate 子命令,MinerU URL 只接受运行参数,不写项目配置。"""
|
||||
parser = argparse.ArgumentParser(description='Build or validate shipping layout truth workbench')
|
||||
subparsers = parser.add_subparsers(dest='command', required=True)
|
||||
build = subparsers.add_parser('build')
|
||||
build.add_argument('--eml-dir', required=True)
|
||||
build.add_argument('--output-dir', required=True)
|
||||
build.add_argument('--mineru-url', required=True)
|
||||
build.add_argument('--timeout', type=int, default=300)
|
||||
build.add_argument('--image-scale', type=float, default=2.0)
|
||||
build.add_argument('--limit', type=int, default=0)
|
||||
validate = subparsers.add_parser('validate')
|
||||
validate.add_argument('path')
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""执行离线工作台生成或人工真值契约校验。"""
|
||||
args = parse_args()
|
||||
return build_workbench(args) if args.command == 'build' else validate_annotations(args)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user