feat(shipping-notice): 添加 MinerU 订单附件表格结构化功能,更新环境配置和数据模型以支持新布局解析和文档模板管理

This commit is contained in:
hugo committed 2026-07-22 18:52:43 +08:00
1 parent c4095b08da
commit c35223d49d
148 files changed
+15709 -1353

No files matched your search

@@ -45,6 +45,29 @@ from app.services.shipping_notice.document_layout.html_table import (
map_html_table_to_schema,
parse_html_grid,
)
from app.services.shipping_notice.document_layout.text_cell_alignment import (
PositionedCharacter,
TextAlignedCell,
TextCellAlignmentResult,
align_html_cells_from_positioned_text,
)
from app.services.shipping_notice.document_layout.native_pdf import (
NativePdfPage,
build_native_pdf_layout_candidate,
extract_native_pdf_pages,
)
from app.services.shipping_notice.document_layout.html_layout import build_html_layout_candidate
from app.services.shipping_notice.document_layout.ocr_pdf import (
OcrCellEvidence,
OcrLine,
OcrTableEvidence,
build_ocr_table_evidence,
extract_ocr_lines,
)
from app.services.shipping_notice.document_layout.schema_mapping import (
layout_table_to_grid,
map_layout_document_to_schema,
)
__all__ = [
'LAYOUT_SCHEMA_VERSION',
@@ -67,6 +90,21 @@ __all__ = [
'MinerUClientConfig',
'MinerUParseCandidate',
'MinerUTextCandidate',
'PositionedCharacter',
'TextAlignedCell',
'TextCellAlignmentResult',
'NativePdfPage',
'build_native_pdf_layout_candidate',
'extract_native_pdf_pages',
'build_html_layout_candidate',
'OcrCellEvidence',
'OcrLine',
'OcrTableEvidence',
'build_ocr_table_evidence',
'extract_ocr_lines',
'layout_table_to_grid',
'map_layout_document_to_schema',
'align_html_cells_from_positioned_text',
'canonical_layout_checksum',
'evaluate_layout',
'inspect_mineru_capabilities',
@@ -1,9 +1,10 @@
"""
backend/app/services/shipping_notice/document_layout/evaluation.py
用途:定义版面解析人工真值格式并计算阶段 L0/L2/L3 的表格与单元格质量指标。
用途:定义版面和 PDF 订单行人工真值格式,并计算阶段 L0/L2/L3 的质量指标与安全门禁。
依赖:Pydantic 2、document_layout.contracts。
逻辑:人工标注保存期望表格/单元格位置;候选解析结果按页与几何交并比匹配,输出可审计指标而非业务订单值。
逻辑:人工标注保存期望表格/单元格位置及订单行事实;候选解析结果按页与几何交并比匹配,
再由匿名聚合指标验证删除项和高风险字段不会被错误自动放行。
"""
from __future__ import annotations
@@ -19,6 +20,15 @@ from app.services.shipping_notice.document_layout.contracts import (
ANNOTATION_SCHEMA_VERSION = 'shipping_document_layout_annotation.v1'
PDF_ORDER_TRUTH_SCHEMA_VERSION = 'shipping_pdf_order_truth.v1'
REQUIRED_PDF_ORDER_SAMPLE_CATEGORIES = frozenset({
'normal_multi_line', 'continued_row', 'deleted_line', 'cross_page_header',
'scanned_ocr', 'unreadable_pdf',
})
HIGH_RISK_PDF_ORDER_FIELDS = frozenset({
'line_no', 'part_number', 'customer_part_number', 'aws_part_number',
'reservation_id', 'qty', 'unit_price', 'amount', 'required_date',
})
class LayoutAnnotationModel(BaseModel):
@@ -27,6 +37,139 @@ class LayoutAnnotationModel(BaseModel):
model_config = ConfigDict(extra='forbid', validate_assignment=True)
class AnnotatedOrderField(LayoutAnnotationModel):
"""保存一项高风险订单字段真值及其版面单元格证据引用。"""
field_code: str = Field(min_length=1, max_length=80)
value: str | int | float
evidence_cell_ids: list[str] = Field(min_length=1)
@model_validator(mode='after')
def validate_high_risk_evidence(self) -> 'AnnotatedOrderField':
"""高风险字段必须能回指至少一个人工确认的版面单元格。"""
if self.field_code not in HIGH_RISK_PDF_ORDER_FIELDS:
raise ValueError('order truth may only contain high-risk field codes')
if len(self.evidence_cell_ids) != len(set(self.evidence_cell_ids)):
raise ValueError('order field evidence_cell_ids must be unique')
return self
class AnnotatedOrderLine(LayoutAnnotationModel):
"""记录视觉行块、删除归属及可自动放行前必须校验的订单字段真值。"""
line_id: str = Field(min_length=1, max_length=160)
table_annotation_id: str = Field(min_length=1, max_length=160)
line_cell_ids: list[str] = Field(min_length=1)
status: str = Field(pattern=r'^(active|deleted|needs_review)$')
fields: list[AnnotatedOrderField] = Field(default_factory=list)
deletion_marker_cell_id: str | None = None
@model_validator(mode='after')
def validate_line_status(self) -> 'AnnotatedOrderLine':
"""删除项必须有独立删除证据;待复核项不能被伪装成可放行字段。"""
if len(self.line_cell_ids) != len(set(self.line_cell_ids)):
raise ValueError('order line cell ids must be unique')
if self.status == 'deleted' and not self.deletion_marker_cell_id:
raise ValueError('deleted order line requires deletion_marker_cell_id')
if self.status != 'deleted' and self.deletion_marker_cell_id:
raise ValueError('only deleted order line may reference deletion marker')
codes = [item.field_code for item in self.fields]
if len(codes) != len(set(codes)):
raise ValueError('order line field codes must be unique')
return self
class PdfOrderTruthAnnotation(LayoutAnnotationModel):
"""保存脱敏 PDF 订单真值,驱动行重建、删除归属和自动放行的阶段 Review。"""
schema_version: str = PDF_ORDER_TRUTH_SCHEMA_VERSION
sample_id: str = Field(min_length=1, max_length=160)
content_hash: str = Field(pattern=r'^[0-9a-f]{64}$')
categories: list[str] = Field(min_length=1)
lines: list[AnnotatedOrderLine] = Field(min_length=1)
@model_validator(mode='after')
def validate_pdf_order_truth(self) -> 'PdfOrderTruthAnnotation':
"""保证样本类别、行标识和删除项审计引用在真值录入时即可发现错误。"""
if self.schema_version != PDF_ORDER_TRUTH_SCHEMA_VERSION:
raise ValueError('unsupported PDF order truth schema_version')
if len(self.categories) != len(set(self.categories)):
raise ValueError('PDF order truth categories must be unique')
line_ids = [item.line_id for item in self.lines]
if len(line_ids) != len(set(line_ids)):
raise ValueError('PDF order truth line ids must be unique')
return self
class PdfOrderQualityMetrics(LayoutAnnotationModel):
"""汇总脱敏真值集的行级结果,不包含 PDF 原文、字段值或用户身份。"""
active_truth_lines: int = Field(ge=0)
deleted_truth_lines: int = Field(ge=0)
active_lines_auto_released: int = Field(ge=0)
active_lines_misdeleted: int = Field(ge=0)
high_risk_auto_released_fields: int = Field(ge=0)
incorrect_high_risk_auto_released_fields: int = Field(ge=0)
unreliable_truth_lines: int = Field(ge=0)
unreliable_lines_sent_to_review: int = Field(ge=0)
@model_validator(mode='after')
def validate_metric_totals(self) -> 'PdfOrderQualityMetrics':
"""拒绝分子大于分母的指标,避免用无效数据错误开启自动放行。"""
if self.active_lines_misdeleted > self.active_truth_lines:
raise ValueError('misdeleted active lines exceed active truth lines')
if self.incorrect_high_risk_auto_released_fields > self.high_risk_auto_released_fields:
raise ValueError('incorrect high-risk fields exceed auto-released fields')
if self.unreliable_lines_sent_to_review > self.unreliable_truth_lines:
raise ValueError('reviewed unreliable lines exceed unreliable truth lines')
return self
class PdfOrderQualityGate(LayoutAnnotationModel):
"""表达安全优先的 PDF 自动放行结论及其不可绕过的失败原因。"""
passed: bool
reasons: list[str]
def review_pdf_order_quality_gate(
annotations: list[dict | PdfOrderTruthAnnotation],
metrics: dict | PdfOrderQualityMetrics,
) -> PdfOrderQualityGate:
"""
审查 PDF 订单 IDP 的阶段质量门禁。
核心逻辑:要求六类脱敏真值样本齐全;并强制有效行零误删、高风险自动放行字段零错误、
所有不可靠行均已转人工复核。覆盖率不设最低值,避免为提高自动化比例降低安全边界。
Args:
annotations: 业务确认的 PDF 订单真值;每个样本仅保存 hash、类别和脱敏行事实。
metrics: 对同一真值集计算的匿名行级质量计数。
Returns:
PdfOrderQualityGate: passed 为 True 才允许后续阶段尝试自动放行。
"""
truth = [
item if isinstance(item, PdfOrderTruthAnnotation) else PdfOrderTruthAnnotation.model_validate(item)
for item in annotations
]
quality = metrics if isinstance(metrics, PdfOrderQualityMetrics) else PdfOrderQualityMetrics.model_validate(metrics)
reasons: list[str] = []
if not truth:
reasons.append('pdf_order_truth_set_missing')
categories = {category for item in truth for category in item.categories}
missing_categories = sorted(REQUIRED_PDF_ORDER_SAMPLE_CATEGORIES - categories)
if missing_categories:
reasons.append(f"pdf_order_truth_categories_missing:{','.join(missing_categories)}")
if quality.active_lines_misdeleted:
reasons.append('active_order_line_misdeleted')
if quality.incorrect_high_risk_auto_released_fields:
reasons.append('incorrect_high_risk_field_auto_released')
if quality.unreliable_lines_sent_to_review != quality.unreliable_truth_lines:
reasons.append('unreliable_order_line_not_sent_to_review')
return PdfOrderQualityGate(passed=not reasons, reasons=reasons)
class AnnotatedCell(LayoutAnnotationModel):
"""记录人工确认的单元格位置、列归属和可选业务字段,不保存邮件身份信息。"""
@@ -0,0 +1,119 @@
"""
backend/app/services/shipping_notice/document_layout/html_layout.py
用途:把 EML 正文中受控 HTML table 转换为统一 shipping_document_layout.v1 逻辑布局候选。
依赖:BeautifulSoup HTML 网格解析、布局契约。
逻辑:DOM 直接证明 rowspan/colspan;坐标仅表示逻辑行列,不冒充屏幕像素,结果固定 needs_review。
"""
from __future__ import annotations
from app.services.shipping_notice.document_layout.contracts import (
LayoutBBox,
LayoutCell,
LayoutDocument,
LayoutIssue,
LayoutPage,
LayoutParserInfo,
LayoutQuality,
LayoutRow,
LayoutTable,
normalize_layout_text,
stable_layout_id,
)
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
def build_html_layout_candidate(
*, document_id: int, content_hash: str, tables: list[str],
) -> LayoutDocument:
"""
将已清洗 HTML 表格列表转换为逻辑坐标布局。
Args:
document_id: email_body Document 主键。
content_hash: 正文文本哈希,用于稳定对象 ID。
tables: 只包含 table/tr/th/td 及跨度属性的清洗片段。
Returns:
DOM 行列可追溯但没有浏览器像素证据的 needs_review 布局。
"""
parsed = []
issues: list[LayoutIssue] = [LayoutIssue(
code='html_logical_coordinates_only', severity='blocking', page_no=1,
)]
for index, html in enumerate(tables):
table_ref = stable_layout_id('html-source-table', content_hash, index)
try:
parsed.append((index, parse_html_grid(html, table_id=table_ref)))
except Exception:
issues.append(LayoutIssue(
code='html_table_invalid', severity='blocking', page_no=1,
table_id=table_ref,
))
page_width = float(max((grid.column_count for _index, grid in parsed), default=1))
page_height = float(max(
sum(grid.row_count for _index, grid in parsed) + max(len(parsed) - 1, 0), 1,
))
offset = 0.0
layout_tables: list[LayoutTable] = []
for table_index, grid in parsed:
table_id = stable_layout_id('table', content_hash, 1, table_index)
table_bbox = LayoutBBox(
x0=0, y0=offset, x1=float(grid.column_count), y1=offset + grid.row_count,
)
rows: list[LayoutRow] = []
for row_index in range(grid.row_count):
source_cells = [item for item in grid.cells if item.row_index == row_index]
if not source_cells:
continue
role = 'header' if all(item.is_header for item in source_cells) else 'data'
cells = []
for source in sorted(source_cells, key=lambda item: item.column_index):
bbox = LayoutBBox(
x0=float(source.column_index), y0=offset + source.row_index,
x1=float(source.column_index + source.column_span),
y1=offset + source.row_index + source.row_span,
)
cells.append(LayoutCell(
cell_id=stable_layout_id(
'cell', content_hash, 1, table_index,
source.row_index, source.column_index,
),
row_index=source.row_index, column_index=source.column_index,
row_span=source.row_span, column_span=source.column_span,
text=source.text, normalized_text=normalize_layout_text(source.text),
bbox=bbox,
normalized_bbox=_normalized(bbox, page_width, page_height),
source='html', confidence=1, role=role,
))
rows.append(LayoutRow(
row_id=stable_layout_id('row', content_hash, 1, table_index, row_index),
row_index=row_index, cells=cells, role=role,
))
layout_tables.append(LayoutTable(
table_id=table_id, bbox=table_bbox,
normalized_bbox=_normalized(table_bbox, page_width, page_height),
rows=rows,
header_row_indices=[item.row_index for item in rows if item.role == 'header'],
confidence=1, status='needs_review',
))
offset += grid.row_count + 1
if not layout_tables:
issues.append(LayoutIssue(code='html_table_structure_missing', severity='blocking', page_no=1))
return LayoutDocument(
document_id=document_id, content_hash=content_hash,
parser=LayoutParserInfo(name='eml-html-dom', version='v1'),
pages=[LayoutPage(
page_no=1, width=page_width, height=page_height,
tokens=[], tables=layout_tables,
)],
quality=LayoutQuality(status='needs_review', confidence=0, issues=issues),
)
def _normalized(bbox: LayoutBBox, width: float, height: float) -> LayoutBBox:
"""将 DOM 逻辑网格坐标转换为 0..1。"""
return LayoutBBox(
x0=bbox.x0 / width, y0=bbox.y0 / height,
x1=bbox.x1 / width, y1=bbox.y1 / height,
)
@@ -230,6 +230,28 @@ def map_html_table_to_schema(
包含列诊断、有效/删除/汇总行和 evidence_ref 的映射结果。
"""
grid = parse_html_grid(html, table_id=table_id)
return map_html_grid_to_schema(
grid, page_no=page_no, table_id=table_id, contract=contract,
)
def map_html_grid_to_schema(
grid: HtmlGrid,
*,
page_no: int,
table_id: str,
contract: TableHeaderContract,
) -> HtmlTableMappingResult:
"""
按冻结 Schema 映射已验证网格,并保留网格自身 cell_id 作为证据身份。
Args:
grid: 来自 HTML 或 layout.v1 的固定矩形网格。
page_no/table_id: 当前布局契约中的来源位置。
contract: Run 冻结 Schema 编译出的精确表头契约。
Returns:
复用统一安全规则的列、行和字段候选。
"""
header_index, score = _select_header_row(grid, contract)
if header_index is None:
return HtmlTableMappingResult(
@@ -271,6 +293,7 @@ def map_html_table_to_schema(
for row_index in range(grid.row_count)
if row_index > header_index
]
issues.extend(_apply_exclusive_deletion_markers(grid, mapped_rows))
required_codes = {
code for code, config in contract.fields_by_code.items()
if config.get('scope') == 'line' and config.get('required')
@@ -423,6 +446,12 @@ def _normalize_html_value(raw: str, config: dict[str, Any] | None) -> Any:
"""按冻结字段类型、normalizer 和 validator 转换 HTML 单元格;非法值留空不跨列补偿。"""
if config is None:
return None
# [STEP] 表格错列时,典型 SAP 项次会落入 Reservation ID 列;不能只靠数字长度放行。
if (
str(config.get('field_code') or '') == 'reservation_id'
and _is_probable_sap_line_number(raw)
):
return None
value_type = str(config.get('value_type') or 'string')
candidate: Any = raw
if value_type in {'decimal', 'integer'}:
@@ -440,6 +469,11 @@ def _normalize_html_value(raw: str, config: dict[str, Any] | None) -> Any:
return None
def _is_probable_sap_line_number(value: Any) -> bool:
"""识别典型五位 SAP 项次,防止 PDF 表格错列将 00010/00020 误作预约号。"""
return bool(re.fullmatch(r'0{3,4}[1-9]\d?', str(value or '').strip()))
def _has_explicit_zero_quantity(
row: list[HtmlGridSlot | None], *, columns: list[HtmlColumnMapping],
) -> bool:
@@ -460,6 +494,40 @@ def _has_explicit_zero_quantity(
return value is not None and value == 0
def _apply_exclusive_deletion_markers(
grid: HtmlGrid, rows: list[HtmlMappedRow],
) -> list[str]:
"""将独占删除标记归属到唯一相邻明细;存在零数量竞争行时保留有效行并转复核。"""
issues: list[str] = []
for index, marker_row in enumerate(rows):
if not _is_exclusive_deletion_marker_row(grid, marker_row.row_index):
continue
previous = rows[index - 1] if index else None
if previous is None or previous.role != 'data' or not previous.fields:
issues.append('deletion_marker_without_unique_previous_line')
continue
# A zero-Qty row before a positive adjacent row is stronger deletion evidence than
# a displaced marker. Do not silently delete the positive row in that situation.
if any(item.role == 'deleted' for item in rows[:index - 1]):
issues.append('deletion_marker_target_ambiguous')
continue
rows[index - 1] = previous.model_copy(update={'role': 'deleted', 'fields': []})
return issues
def _is_exclusive_deletion_marker_row(grid: HtmlGrid, row_index: int) -> bool:
"""仅接受整行只表达删除含义的标记,避免把描述列中的普通文字误当删除指令。"""
texts = [
normalize_table_header(slot.text)
for slot in grid.rows[row_index]
if slot is not None and slot.text.strip()
]
if not texts:
return False
markers = {'item deleted', 'deleted item', '项目已删除', '項目已刪除'}
return all(text in markers for text in texts)
def _header_candidates(grid: HtmlGrid, *, row_index: int, column_index: int) -> list[str]:
"""生成叶表头、上层合并表头和组合路径的标准化候选,保持精确匹配。"""
displays = _header_display_path(grid, row_index, column_index)
@@ -0,0 +1,405 @@
"""
backend/app/services/shipping_notice/document_layout/lifecycle.py
用途:管理 ShippingNoticeDocument 的版面版本、checksum、大小门禁和当前成功快照。
依赖:ShippingDocumentLayoutVersion、Flask 配置、SQLAlchemy Session。
逻辑:相同内容/parser/checksum 幂等复用;失败版本保留审计,只有可用终态更新 Document 当前引用。
"""
from __future__ import annotations
import hashlib
import json
from datetime import datetime
from typing import Any
from flask import current_app
from sqlalchemy import and_, func, or_, update
from app.extensions import db
from app.models import ShippingDocumentLayoutVersion, ShippingNoticeDocument
LAYOUT_PARSER_NAME = 'mineru'
LAYOUT_BACKEND = 'pipeline'
LAYOUT_CONTRACT_VERSION = 'shipping_document_table_snapshot.v1'
CURRENT_LAYOUT_STATUSES = frozenset({'ready', 'needs_review'})
TERMINAL_LAYOUT_STATUSES = frozenset({'ready', 'needs_review', 'failed', 'unsupported'})
def current_layout_parser_key() -> str:
"""生成运维可轮转的 parser 身份;Provider/模型升级必须提升 revision 防止复用旧结果。"""
revision = str(current_app.config.get(
'SHIPPING_NOTICE_LAYOUT_PARSER_REVISION', 'v3',
) or 'v3').strip()
return f'{LAYOUT_PARSER_NAME}:{LAYOUT_BACKEND}:{LAYOUT_CONTRACT_VERSION}:{revision}'
def canonical_layout_payload(payload: dict[str, Any]) -> tuple[str, int]:
"""返回布局 JSON 的稳定 SHA-256 和 UTF-8 大小,供幂等与容量门禁复用。"""
encoded = json.dumps(
payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'),
).encode('utf-8')
return hashlib.sha256(encoded).hexdigest(), len(encoded)
def current_layout_snapshot(document: ShippingNoticeDocument) -> dict[str, Any] | None:
"""读取 Document 当前可用冻结 payload;失败历史版本永不作为运行输入。"""
version = document.current_layout_version
if (
version is None
or str(version.status or '') not in CURRENT_LAYOUT_STATUSES
or not isinstance(version.payload_json, dict)
):
return None
return dict(version.payload_json)
def record_inline_layout_snapshot(
document: ShippingNoticeDocument,
snapshot: dict[str, Any],
*,
parser_key: str | None = None,
) -> ShippingDocumentLayoutVersion:
"""
将 Intake 解析阶段已有布局快照转为不可变版本;后续 L1 Job 会复用同一收口逻辑。
超大 payload 不落正文,只创建 failed 审计版本;相同内容/parser/checksum 重试复用旧终态。
"""
payload = dict(snapshot)
parser_key = str(parser_key or current_layout_parser_key())
checksum, payload_size = canonical_layout_payload(payload)
source_hash = str(document.content_hash or '').strip().lower()
if len(source_hash) != 64:
source_hash = hashlib.sha256(
f'document:{document.id}:{document.attachment_key}'.encode('utf-8'),
).hexdigest()
existing = (
ShippingDocumentLayoutVersion.query
.filter_by(
document_id=int(document.id),
source_content_hash=source_hash,
parser_key=parser_key,
payload_checksum=checksum,
)
.order_by(ShippingDocumentLayoutVersion.version.desc())
.first()
)
if existing is not None:
if existing.status in CURRENT_LAYOUT_STATUSES:
document.current_layout_version_id = existing.id
return existing
version_no = int(db.session.query(func.max(ShippingDocumentLayoutVersion.version)).filter_by(
document_id=int(document.id),
).scalar() or 0) + 1
now = datetime.utcnow()
provider_status = str(payload.get('status') or 'failed')
status = provider_status if provider_status in {
'ready', 'needs_review', 'failed', 'unsupported',
} else 'failed'
max_bytes = max(int(current_app.config.get(
'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000,
)), 1)
issues = sorted({str(item) for item in (payload.get('issues') or []) if str(item)})
stored_payload: dict[str, Any] | None = payload
if payload_size > max_bytes:
status = 'failed'
stored_payload = None
issues.append('shipping_document_layout_snapshot_size_exceeded')
version = ShippingDocumentLayoutVersion(
document_id=int(document.id),
version=version_no,
status=status,
source_content_hash=source_hash,
parser_key=parser_key,
parser_name=str(payload.get('provider') or LAYOUT_PARSER_NAME)[:32],
parser_version=str(payload.get('provider_version') or '')[:64] or None,
backend=str(payload.get('backend') or LAYOUT_BACKEND)[:32],
contract_version=str(payload.get('snapshot_version') or LAYOUT_CONTRACT_VERSION)[:64],
payload_json=stored_payload,
payload_checksum=checksum,
payload_size_bytes=payload_size,
quality_json=(
dict(payload['capability']) if isinstance(payload.get('capability'), dict) else None
),
issues_json=sorted(set(issues)),
attempt_count=1,
created_at=now,
updated_at=now,
finished_at=now,
)
db.session.add(version)
db.session.flush()
if status in CURRENT_LAYOUT_STATUSES:
document.current_layout_version_id = version.id
return version
def schedule_layout_version(
document: ShippingNoticeDocument,
*,
force: bool = False,
created_by_id: int | None = None,
) -> ShippingDocumentLayoutVersion | None:
"""为支持的附件创建唯一 queued 版本和 Job;相同 parser 成功版本默认幂等复用。"""
from pathlib import Path
from app.jobs.queue import enqueue
from app.jobs.types import JobType
from app.services.shipping_notice.document_layout.mineru import MINERU_SUPPORTED_EXTENSIONS
if not bool(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED', False)):
return None
if document.asset_id is None or Path(str(document.filename or '')).suffix.lower() not in MINERU_SUPPORTED_EXTENSIONS:
return None
source_hash = str(document.content_hash or '').strip().lower()
if len(source_hash) != 64:
return None
active = ShippingDocumentLayoutVersion.query.filter(
ShippingDocumentLayoutVersion.document_id == int(document.id),
ShippingDocumentLayoutVersion.status.in_({'queued', 'running'}),
).first()
if active is not None:
return active
if not force:
reusable = ShippingDocumentLayoutVersion.query.filter_by(
document_id=int(document.id), source_content_hash=source_hash,
parser_key=current_layout_parser_key(),
).filter(ShippingDocumentLayoutVersion.status.in_(tuple(CURRENT_LAYOUT_STATUSES))).order_by(
ShippingDocumentLayoutVersion.version.desc(),
).first()
if reusable is not None:
document.current_layout_version_id = reusable.id
return reusable
version_no = int(db.session.query(func.max(ShippingDocumentLayoutVersion.version)).filter_by(
document_id=int(document.id),
).scalar() or 0) + 1
version = ShippingDocumentLayoutVersion(
document_id=int(document.id), version=version_no, status='queued',
source_content_hash=source_hash, parser_key=current_layout_parser_key(),
parser_name=LAYOUT_PARSER_NAME, backend=LAYOUT_BACKEND,
contract_version=LAYOUT_CONTRACT_VERSION, issues_json=[], attempt_count=0,
)
db.session.add(version)
db.session.flush()
job_id = enqueue(
JobType.SHIPPING_DOCUMENT_LAYOUT,
{'layout_version_id': int(version.id)},
domain='shipping_notice', business_ref=f'layout:{version.id}',
created_by_id=created_by_id, message='等待解析文档版面',
max_attempts=int(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MAX_ATTEMPTS', 3)),
commit=False,
)
version.job_id = job_id
return version
def schedule_document_layouts(
documents: list[ShippingNoticeDocument], *, created_by_id: int | None = None,
) -> list[ShippingDocumentLayoutVersion]:
"""在 Document 持久化事务内为支持附件建立独立布局版本,超量文档保留 skipped 审计。"""
from pathlib import Path
from app.services.shipping_notice.document_layout.mineru import MINERU_SUPPORTED_EXTENSIONS
max_documents = max(int(current_app.config.get(
'SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', 4,
)), 0)
eligible = [
item for item in documents
if item.asset_id is not None
and Path(str(item.filename or '')).suffix.lower() in MINERU_SUPPORTED_EXTENSIONS
]
result: list[ShippingDocumentLayoutVersion] = []
for index, document in enumerate(eligible):
if index >= max_documents:
existing = ShippingDocumentLayoutVersion.query.filter_by(
document_id=int(document.id), source_content_hash=str(document.content_hash or ''),
parser_key=current_layout_parser_key(), status='unsupported',
).first()
if existing is None:
version_no = int(db.session.query(func.max(ShippingDocumentLayoutVersion.version)).filter_by(
document_id=int(document.id),
).scalar() or 0) + 1
existing = ShippingDocumentLayoutVersion(
document_id=int(document.id), version=version_no, status='unsupported',
source_content_hash=str(document.content_hash or ''),
parser_key=current_layout_parser_key(),
parser_name=LAYOUT_PARSER_NAME, backend=LAYOUT_BACKEND,
contract_version=LAYOUT_CONTRACT_VERSION,
issues_json=['mineru_intake_document_budget_exceeded'], attempt_count=0,
finished_at=datetime.utcnow(),
)
db.session.add(existing)
db.session.flush()
result.append(existing)
continue
version = schedule_layout_version(document, created_by_id=created_by_id)
if version is not None:
result.append(version)
return result
def serialize_layout_version(version: ShippingDocumentLayoutVersion) -> dict[str, Any]:
"""返回管理员诊断安全摘要,不暴露 HTML、bbox、正文或 Provider 原始响应。"""
payload = version.payload_json if isinstance(version.payload_json, dict) else {}
tables = payload.get('tables') if isinstance(payload.get('tables'), list) else []
layout_candidate = (
payload.get('layout_candidate') if isinstance(payload.get('layout_candidate'), dict) else {}
)
candidate_pages = (
layout_candidate.get('pages') if isinstance(layout_candidate.get('pages'), list) else []
)
candidate_table_count = sum(
len(page.get('tables') or [])
for page in candidate_pages
if isinstance(page, dict) and isinstance(page.get('tables'), list)
)
return {
'id': version.id, 'document_id': version.document_id, 'version': version.version,
'status': version.status, 'parser_name': version.parser_name,
'parser_version': version.parser_version, 'backend': version.backend,
'contract_version': version.contract_version,
'payload_checksum': version.payload_checksum,
'payload_size_bytes': version.payload_size_bytes,
'table_count': candidate_table_count or len(tables),
'issues': list(version.issues_json or []),
'attempt_count': version.attempt_count, 'job_id': version.job_id,
'is_current': version.document.current_layout_version_id == version.id,
'created_at': version.created_at.isoformat() if version.created_at else None,
'started_at': version.started_at.isoformat() if version.started_at else None,
'finished_at': version.finished_at.isoformat() if version.finished_at else None,
}
def list_layout_versions(document_id: int) -> list[dict[str, Any]]:
"""列出一个 Document 的布局版本安全摘要。"""
document = db.session.get(ShippingNoticeDocument, int(document_id))
if document is None:
from app.core.errors import NotFoundError
raise NotFoundError(
'Shipping notice document not found', code='SHIPPING_NOTICE.DOCUMENT_NOT_FOUND',
)
return [serialize_layout_version(item) for item in ShippingDocumentLayoutVersion.query.filter_by(
document_id=int(document.id),
).order_by(ShippingDocumentLayoutVersion.version.desc()).all()]
def request_layout_reparse(
document_id: int, *, created_by_id: int | None,
) -> dict[str, Any]:
"""管理员显式创建下一布局版本;活动版本存在时幂等返回同一版本。"""
document = db.session.get(ShippingNoticeDocument, int(document_id))
if document is None:
from app.core.errors import NotFoundError
raise NotFoundError(
'Shipping notice document not found', code='SHIPPING_NOTICE.DOCUMENT_NOT_FOUND',
)
version = schedule_layout_version(document, force=True, created_by_id=created_by_id)
if version is None:
from app.core.errors import ValidationError
raise ValidationError(
'Document is not eligible for layout parsing',
code='SHIPPING_NOTICE.LAYOUT_FILE_TYPE_UNSUPPORTED',
)
db.session.commit()
return serialize_layout_version(version)
def claim_layout_version(
version_id: int, *, job_id: int, owned_attempt: int,
) -> tuple[ShippingDocumentLayoutVersion, str] | None:
"""原子领取 queued/同 Job running 版本并轮转 lease,旧 Worker 立即失效。"""
lease = f'{int(job_id)}:{int(owned_attempt)}'
now = datetime.utcnow()
predicate = or_(
ShippingDocumentLayoutVersion.status == 'queued',
and_(
ShippingDocumentLayoutVersion.status == 'running',
ShippingDocumentLayoutVersion.job_id == int(job_id),
),
)
result = db.session.execute(
update(ShippingDocumentLayoutVersion)
.where(ShippingDocumentLayoutVersion.id == int(version_id), predicate)
.values(
status='running', job_id=int(job_id), lease_token=lease,
attempt_count=int(owned_attempt), started_at=now, updated_at=now,
)
)
if int(result.rowcount or 0) != 1:
db.session.rollback()
return None
db.session.commit()
version = db.session.get(ShippingDocumentLayoutVersion, int(version_id))
return (version, lease) if version is not None else None
def complete_layout_version(
version_id: int, *, lease_token: str, snapshot: dict[str, Any],
) -> bool:
"""按 lease 条件冻结 payload/checksum;失败版本不覆盖 Document 旧成功引用。"""
version = db.session.get(ShippingDocumentLayoutVersion, int(version_id))
if version is None or version.status != 'running' or version.lease_token != lease_token:
db.session.rollback()
return False
checksum, payload_size = canonical_layout_payload(snapshot)
max_bytes = max(int(current_app.config.get(
'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000,
)), 1)
issues = sorted({str(item) for item in (snapshot.get('issues') or []) if str(item)})
provider_status = str(snapshot.get('status') or 'failed')
status = provider_status if provider_status in TERMINAL_LAYOUT_STATUSES else 'failed'
stored_payload: dict[str, Any] | None = dict(snapshot)
if payload_size > max_bytes:
status = 'failed'
stored_payload = None
issues.append('shipping_document_layout_snapshot_size_exceeded')
now = datetime.utcnow()
version.status = status
version.parser_version = str(snapshot.get('provider_version') or '')[:64] or None
version.backend = str(snapshot.get('backend') or LAYOUT_BACKEND)[:32]
version.payload_json = stored_payload
version.payload_checksum = checksum
version.payload_size_bytes = payload_size
version.quality_json = dict(snapshot['capability']) if isinstance(snapshot.get('capability'), dict) else None
version.issues_json = sorted(set(issues))
version.lease_token = None
version.finished_at = now
version.updated_at = now
if status in CURRENT_LAYOUT_STATUSES:
version.document.current_layout_version_id = version.id
db.session.commit()
return True
def sync_layout_after_job_recovery(job: Any) -> None:
"""通用 Job 超时回收后同步布局版本,清除旧 lease 或记录最终失败。"""
version = ShippingDocumentLayoutVersion.query.filter_by(job_id=int(job.id)).first()
if version is None or version.status != 'running':
return
version.lease_token = None
version.updated_at = datetime.utcnow()
if str(job.status or '') == 'queued':
version.status = 'queued'
elif str(job.status or '') in {'failed', 'cancelled'}:
version.status = 'failed'
version.finished_at = datetime.utcnow()
version.issues_json = sorted(set(list(version.issues_json or []) + [
'shipping_document_layout_job_exhausted',
]))
def sync_layout_after_job_failure(job_id: int) -> None:
"""Handler 调用 fail_job 后立即同步版本状态,避免等待超时回收才清 lease。"""
from app.models import Job
job = db.session.get(Job, int(job_id))
if job is None:
return
sync_layout_after_job_recovery(job)
db.session.commit()
@@ -10,6 +10,7 @@ from __future__ import annotations
import hashlib
import json
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Iterable
@@ -40,6 +41,7 @@ class MinerUClientConfig:
languages: tuple[str, ...] = ('ch',)
connect_timeout_seconds: int = 10
read_timeout_seconds: int = 300
poll_interval_seconds: float = 1.0
max_upload_bytes: int = 30 * 1024 * 1024
max_response_bytes: int = 20 * 1024 * 1024
@@ -193,20 +195,7 @@ class MinerUClient:
details={'max_bytes': self.config.max_upload_bytes},
)
data = [
('backend', self.config.backend),
('parse_method', self.config.parse_method),
('formula_enable', 'false'),
('table_enable', 'true'),
('image_analysis', 'false'),
('return_md', 'false'),
('return_middle_json', 'true'),
('return_model_output', 'true'),
('return_content_list', 'true'),
('return_images', 'false'),
('response_format_zip', 'false'),
]
data.extend(('lang_list', item) for item in self.config.languages)
data = _mineru_request_data(self.config)
try:
response = self.session.post(
f'{self.base_url}/file_parse',
@@ -252,6 +241,110 @@ class MinerUClient:
)
return payload
def parse_file_async(self, *, filename: str, content: bytes) -> dict[str, Any]:
"""
通过 `/tasks` 提交异步解析并轮询终态结果,避免单条 HTTP 长连接占用 Worker。
Args:
filename: 受支持文件名,仅用于扩展名和 multipart。
content: 文件原始字节,受上传上限限制。
Returns:
与同步 `/file_parse` 相同的 completed 结果对象。
Raises:
ValidationError: 提交、状态或终态响应不符合协议。
ServiceUnavailableError: 网络、5xx 或总等待时间超限。
"""
extension = Path(str(filename or '')).suffix.lower()
if extension not in MINERU_SUPPORTED_EXTENSIONS:
raise ValidationError(
'MinerU file type is unsupported',
code='SHIPPING_NOTICE.LAYOUT_FILE_TYPE_UNSUPPORTED',
details={'extension': extension},
)
if not content:
raise ValidationError('MinerU input file is empty', code='SHIPPING_NOTICE.LAYOUT_FILE_EMPTY')
if len(content) > self.config.max_upload_bytes:
raise ValidationError(
'MinerU input file exceeds size limit',
code='SHIPPING_NOTICE.LAYOUT_FILE_TOO_LARGE',
details={'max_bytes': self.config.max_upload_bytes},
)
data = _mineru_request_data(self.config)
try:
response = self.session.post(
f'{self.base_url}/tasks',
files=[('files', (filename, content, _mime_type(extension)))],
data=data,
timeout=(self.config.connect_timeout_seconds, self.config.connect_timeout_seconds),
)
submission = _response_json(response, max_bytes=self.config.max_response_bytes)
except requests.exceptions.RequestException as exc:
raise ServiceUnavailableError(
'MinerU task submission failed', code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE',
) from exc
if response.status_code >= 500:
raise ServiceUnavailableError(
'MinerU task submission failed',
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE',
details={'status': response.status_code},
)
if response.status_code >= 400:
raise ValidationError(
'MinerU task submission was rejected',
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_PARSE_FAILED',
details={'status': response.status_code},
)
task_id = str(submission.get('task_id') or submission.get('id') or '').strip()
if not task_id:
raise ValidationError(
'MinerU task response has no task id',
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
)
deadline = time.monotonic() + max(float(self.config.read_timeout_seconds), 1.0)
while time.monotonic() < deadline:
status = self._get_async_json(f'/tasks/{task_id}')
state = str(status.get('status') or status.get('state') or '').strip().lower()
if state in {'completed', 'succeeded', 'success'}:
result = self._get_async_json(f'/tasks/{task_id}/result')
if str(result.get('status') or '').strip().lower() not in {'completed', 'succeeded', 'success'}:
result = {**result, 'status': 'completed', 'task_id': task_id}
return result
if state in {'failed', 'error', 'cancelled', 'canceled'}:
raise ValidationError(
'MinerU parse task failed',
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_PARSE_FAILED',
details={'provider_error_code': _provider_error_code(status.get('error'))},
)
time.sleep(max(float(self.config.poll_interval_seconds), 0.05))
raise ServiceUnavailableError(
'MinerU parse task timed out', code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE',
)
def _get_async_json(self, path: str) -> dict[str, Any]:
"""读取一个异步任务接口并统一网络、状态码和 JSON 容量错误。"""
try:
response = self.session.get(
f'{self.base_url}{path}',
timeout=(self.config.connect_timeout_seconds, self.config.connect_timeout_seconds),
)
payload = _response_json(response, max_bytes=self.config.max_response_bytes)
except requests.exceptions.RequestException as exc:
raise ServiceUnavailableError(
'MinerU task polling failed', code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE',
) from exc
if response.status_code >= 500:
raise ServiceUnavailableError(
'MinerU task polling failed', code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE',
details={'status': response.status_code},
)
if response.status_code >= 400:
raise ValidationError(
'MinerU task polling response is invalid',
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
details={'status': response.status_code},
)
return payload
def parse_mineru_candidate(payload: dict[str, Any]) -> MinerUParseCandidate:
"""
@@ -404,6 +497,46 @@ def _read_limited_response(response: requests.Response, *, max_bytes: int) -> by
return b''.join(chunks)
def _mineru_request_data(config: MinerUClientConfig) -> list[tuple[str, str]]:
"""生成同步/异步接口共用的 pipeline multipart 参数。"""
data = [
('backend', config.backend),
('parse_method', config.parse_method),
('formula_enable', 'false'),
('table_enable', 'true'),
('image_analysis', 'false'),
('return_md', 'false'),
('return_middle_json', 'true'),
('return_model_output', 'true'),
('return_content_list', 'true'),
('return_images', 'false'),
('response_format_zip', 'false'),
]
data.extend(('lang_list', item) for item in config.languages)
return data
def _response_json(response: requests.Response, *, max_bytes: int) -> dict[str, Any]:
"""读取有限大小 JSON 响应;兼容测试替身和 requests 非流式 GET。"""
if hasattr(response, 'iter_content'):
raw = _read_limited_response(response, max_bytes=max_bytes)
else: # pragma: no cover - requests.Response 始终实现 iter_content
raw = bytes(response.content or b'')
try:
payload = json.loads(raw.decode(response.encoding or 'utf-8'))
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
raise ValidationError(
'MinerU response is not valid JSON',
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
) from exc
if not isinstance(payload, dict):
raise ValidationError(
'MinerU response must be an object',
code='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
)
return payload
def _decode_json_field(value: Any, *, field: str) -> Any:
"""解包 MinerU 将 middle/model/content JSON 作为字符串返回的协议形式。"""
parsed = value
@@ -0,0 +1,363 @@
"""
backend/app/services/shipping_notice/document_layout/native_pdf.py
用途:用项目既有 PDFium 提取原生 PDF 字符坐标、页面渲染,并组装保守的 layout.v1 表格候选。
依赖:pypdfium2、MinerU 页面/HTML 候选、OpenCV 网格、严格文本对齐和布局契约。
逻辑:MinerU 提供整表与 HTML;PDFium提供独立字符/图像证据;只有严格匹配的 cell 才写入候选,整体仍固定 needs_review。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
import numpy as np
import pypdfium2 as pdfium
from app.services.shipping_notice.document_layout.contracts import (
LayoutBBox,
LayoutCell,
LayoutDocument,
LayoutIssue,
LayoutPage,
LayoutParserInfo,
LayoutQuality,
LayoutRow,
LayoutTable,
LayoutToken,
normalize_layout_text,
stable_layout_id,
)
from app.services.shipping_notice.document_layout.html_table import HtmlGrid, parse_html_grid
from app.services.shipping_notice.document_layout.mineru import MinerUParseCandidate
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.ocr_pdf import build_ocr_table_evidence
from app.services.shipping_notice.document_layout.text_cell_alignment import (
PositionedCharacter,
align_html_cells_from_positioned_text,
)
@dataclass(frozen=True)
class NativePdfPage:
"""保存单页原生字符和渲染图;对象仅在 Worker 内存中存在。"""
page_no: int
width: float
height: float
rotation: int
characters: list[PositionedCharacter]
image: np.ndarray
def extract_native_pdf_pages(content: bytes, *, render_scale: float = 2.0) -> list[NativePdfPage]:
"""
从 PDF bytes 提取左上原点字符坐标和页面图。
Args:
content: 原始 PDF 字节,不写文件和日志。
render_scale: OpenCV 网格检测使用的渲染倍率,必须为正数。
Returns:
连续页列表;扫描 PDF 可返回无字符页面,但仍保留页面尺寸和图像。
Raises:
ValueError: 内容为空、倍率非法或 PDFium 无法打开文件。
"""
if not content or render_scale <= 0:
raise ValueError('native PDF content and positive render scale are required')
pdf = pdfium.PdfDocument(content)
pages: list[NativePdfPage] = []
for page_index in range(len(pdf)):
page = pdf[page_index]
width, height = page.get_size()
text_page = page.get_textpage()
characters: list[PositionedCharacter] = []
for char_index in range(text_page.count_chars()):
text = text_page.get_text_range(char_index, 1)
if not text or not normalize_layout_text(text):
continue
left, bottom, right, top = text_page.get_charbox(char_index, loose=True)
if right <= left or top <= bottom:
continue
try:
characters.append(PositionedCharacter(
text=text,
bbox=LayoutBBox(
x0=left, y0=height - top, x1=right, y1=height - bottom,
),
source_index=len(characters),
))
except ValueError:
continue
rotation = int(getattr(page, 'get_rotation', lambda: 0)() or 0) % 360
pages.append(NativePdfPage(
page_no=page_index + 1,
width=float(width),
height=float(height),
rotation=rotation if rotation in {0, 90, 180, 270} else 0,
characters=characters,
image=np.asarray(page.render(scale=render_scale).to_numpy()).copy(),
))
return pages
def build_native_pdf_layout_candidate(
*,
document_id: int,
content_hash: str,
content: bytes,
mineru: MinerUParseCandidate,
) -> LayoutDocument:
"""
组合 MinerU HTML 与 PDFium 独立证据,生成始终 needs_review 的 layout.v1 候选。
Args:
document_id: 当前 ShippingNoticeDocument 主键。
content_hash: 当前附件 SHA-256,用于稳定 ID 和契约校验。
content: 原始 PDF 字节。
mineru: 同一文件的 MinerU pipeline 候选。
Returns:
通过完整布局契约校验的候选;没有可证 cell 时保留空表和 blocking issue。
"""
native_pages = extract_native_pdf_pages(content)
mineru_pages = {item.page_no: item for item in mineru.pages}
issues: list[LayoutIssue] = [LayoutIssue(
code='document_cell_truth_deferred', severity='blocking',
)]
pages: list[LayoutPage] = []
for native in native_pages:
page_candidate = mineru_pages.get(native.page_no)
tables: list[LayoutTable] = []
page_tokens: dict[str, LayoutToken] = {}
for table_index, table_candidate in enumerate(page_candidate.tables if page_candidate else []):
try:
grid = parse_html_grid(table_candidate.html, table_id=table_candidate.candidate_id)
cells, method_issues = _candidate_cells(
native=native, grid=grid, table_bbox=table_candidate.bbox,
)
except Exception:
issues.append(LayoutIssue(
code='native_pdf_table_candidate_invalid', severity='blocking', page_no=native.page_no,
table_id=table_candidate.candidate_id,
))
continue
for code in method_issues:
issues.append(LayoutIssue(
code=code, severity='blocking', page_no=native.page_no,
table_id=table_candidate.candidate_id,
))
if not cells:
continue
try:
layout_table = _layout_table(
native=native,
grid=grid,
table_bbox=table_candidate.bbox,
content_hash=content_hash,
table_index=table_index,
cells=cells,
page_tokens=page_tokens,
)
except Exception:
issues.append(LayoutIssue(
code='native_pdf_layout_table_invalid', severity='blocking',
page_no=native.page_no, table_id=table_candidate.candidate_id,
))
continue
tables.append(layout_table)
if page_candidate and page_candidate.tables and not tables:
issues.append(LayoutIssue(
code='native_pdf_table_cells_unresolved', severity='blocking', page_no=native.page_no,
))
pages.append(LayoutPage(
page_no=native.page_no, width=native.width, height=native.height,
rotation=native.rotation,
tokens=[page_tokens[token_id] for token_id in sorted(page_tokens)],
tables=tables,
))
if not any(page.tables for page in pages):
issues.append(LayoutIssue(code='native_pdf_no_resolved_tables', severity='blocking'))
return LayoutDocument(
document_id=document_id,
content_hash=content_hash,
parser=LayoutParserInfo(
name='mineru-pipeline+pdfium+rapidocr',
version=str(mineru.provider_version or 'unknown'),
),
pages=pages,
quality=LayoutQuality(status='needs_review', confidence=0, issues=issues),
)
def _candidate_cells(
*, native: NativePdfPage, grid: HtmlGrid, table_bbox: LayoutBBox,
) -> tuple[dict[str, dict[str, Any]], list[str]]:
"""优先唯一文本对齐,失败后仅对严格有框表使用 OpenCV 双门禁。"""
alignment = align_html_cells_from_positioned_text(
grid, characters=native.characters, table_bbox=table_bbox,
page_width=native.width, page_height=native.height,
)
if alignment.complete:
return {
item.cell_id: {
'bbox': item.bbox,
'tokens': [
_native_layout_token(native=native, glyph_index=index, content_hash='pending')
for index in item.glyph_indices
],
'source': 'native_text', 'confidence': 1,
}
for item in alignment.cells
}, ['native_pdf_cells_from_unique_text_candidate']
geometry = reconstruct_opencv_table_geometry(
native.image, page_width=native.width, page_height=native.height,
table_bbox=table_bbox, grid=grid,
)
validation = validate_opencv_cell_text(
geometry, grid=grid,
bounded_text_reader=lambda bbox: _text_within(native.characters, bbox),
minimum_match_rate=1.0,
required_cell_ids={item.cell_id for item in grid.cells if item.text.strip()},
)
if not validation.accepted:
ocr = build_ocr_table_evidence(
image=native.image, page_width=native.width, page_height=native.height,
table_bbox=table_bbox, grid=grid,
)
if not ocr.ready:
return {}, sorted(set(
alignment.issues + geometry.issues + validation.issues + ocr.issues,
))
ocr_lines = {index: item for index, item in enumerate(ocr.lines)}
return {
item.cell_id: {
'bbox': item.bbox,
'tokens': [
_ocr_layout_token(
native=native, line=ocr_lines[index], line_index=index,
)
for index in item.line_indices
],
'source': 'ocr',
'confidence': min(
(ocr_lines[index].confidence for index in item.line_indices), default=0,
),
}
for item in ocr.cells
}, ['ocr_pdf_cells_from_grid_candidate']
cells: dict[str, dict[str, Any]] = {}
for item in geometry.cells:
indices = _glyph_indices_within(native.characters, item.bbox)
expected = next(cell for cell in grid.cells if cell.cell_id == item.cell_id)
if expected.text.strip() and not indices:
return {}, ['native_pdf_opencv_cell_tokens_missing']
cells[item.cell_id] = {
'bbox': item.bbox,
'tokens': [
_native_layout_token(native=native, glyph_index=index, content_hash='pending')
for index in indices
],
'source': 'native_text', 'confidence': 1,
}
return cells, ['native_pdf_cells_from_opencv_candidate']
def _native_layout_token(*, native: NativePdfPage, glyph_index: int, content_hash: str) -> LayoutToken:
"""把表格区域内单个 PDF glyph 转为稳定、可引用的 LayoutToken。"""
glyph = native.characters[glyph_index]
return LayoutToken(
token_id=stable_layout_id('token', content_hash, native.page_no, glyph_index),
text=glyph.text,
normalized_text=normalize_layout_text(glyph.text),
bbox=glyph.bbox,
normalized_bbox=_normalized_bbox(glyph.bbox, native.width, native.height),
source='native_text', confidence=1, line_id=None,
)
def _ocr_layout_token(*, native: NativePdfPage, line: Any, line_index: int) -> LayoutToken:
"""把一条 OCR 行转为临时 LayoutToken;最终稳定 ID 在组表时绑定 Document/cell。"""
return LayoutToken(
token_id=stable_layout_id('ocr-token', 'pending', native.page_no, line_index),
text=line.text,
normalized_text=normalize_layout_text(line.text),
bbox=line.bbox,
normalized_bbox=_normalized_bbox(line.bbox, native.width, native.height),
source='ocr', confidence=line.confidence, line_id=None,
)
def _layout_table(
*, native: NativePdfPage, grid: HtmlGrid, table_bbox: LayoutBBox, content_hash: str,
table_index: int, cells: dict[str, dict[str, Any]], page_tokens: dict[str, LayoutToken],
) -> LayoutTable:
"""按 HTML row/column/span 组装具有真实 bbox 和 token 引用的 needs_review 表格。"""
rows: list[LayoutRow] = []
for row_index in range(grid.row_count):
source_cells = [item for item in grid.cells if item.row_index == row_index]
if not source_cells:
continue
role = 'header' if source_cells and all(item.is_header for item in source_cells) else 'data'
layout_cells = []
for source in sorted(source_cells, key=lambda item: item.column_index):
evidence = cells[source.cell_id]
tokens = [
token.model_copy(update={
'token_id': stable_layout_id(
'token', content_hash, native.page_no, table_index,
source.row_index, source.column_index, token.token_id,
),
})
for token in evidence['tokens']
]
for token in tokens:
page_tokens[token.token_id] = token
layout_cells.append(LayoutCell(
cell_id=stable_layout_id(
'cell', content_hash, native.page_no, table_index,
source.row_index, source.column_index,
),
row_index=source.row_index, column_index=source.column_index,
row_span=source.row_span, column_span=source.column_span,
text=source.text, normalized_text=normalize_layout_text(source.text),
bbox=evidence['bbox'],
normalized_bbox=_normalized_bbox(evidence['bbox'], native.width, native.height),
token_ids=[token.token_id for token in tokens],
source=evidence['source'], confidence=evidence['confidence'], role=role,
))
rows.append(LayoutRow(
row_id=stable_layout_id('row', content_hash, native.page_no, table_index, row_index),
row_index=row_index, cells=layout_cells, role=role,
))
return LayoutTable(
table_id=stable_layout_id('table', content_hash, native.page_no, table_index),
bbox=table_bbox,
normalized_bbox=_normalized_bbox(table_bbox, native.width, native.height),
rows=rows,
header_row_indices=[row.row_index for row in rows if row.role == 'header'],
confidence=0, status='needs_review',
)
def _glyph_indices_within(characters: list[PositionedCharacter], bbox: LayoutBBox) -> list[int]:
"""返回中心点落在 bbox 内的 glyph 索引,保持 PDF 文本顺序。"""
return [
index for index, item in enumerate(characters)
if bbox.x0 <= (item.bbox.x0 + item.bbox.x1) / 2 <= bbox.x1
and bbox.y0 <= (item.bbox.y0 + item.bbox.y1) / 2 <= bbox.y1
]
def _text_within(characters: list[PositionedCharacter], bbox: LayoutBBox) -> str:
"""读取 bbox 内原生字符,供 OpenCV 几何的独立文本一致性验证。"""
return ''.join(characters[index].text for index in _glyph_indices_within(characters, bbox))
def _normalized_bbox(bbox: LayoutBBox, width: float, height: float) -> LayoutBBox:
"""将页面单位 bbox 转换为布局契约 0..1 坐标。"""
return LayoutBBox(
x0=bbox.x0 / width, y0=bbox.y0 / height,
x1=bbox.x1 / width, y1=bbox.y1 / height,
)
@@ -0,0 +1,154 @@
"""
backend/app/services/shipping_notice/document_layout/ocr_pdf.py
用途:保留 RapidOCR 文本行多边形坐标,并为扫描 PDF 表格提供严格 cell 候选。
依赖:RapidOCR、OpenCV 网格、MinerU HTML、布局契约。
逻辑:OCR 只提供独立文本坐标;必须与多参数有框网格及全部非空 cell 文本一致才输出,结果仍需人工真值。
"""
from __future__ import annotations
from functools import lru_cache
from typing import Any
from pydantic import BaseModel, ConfigDict, Field
from app.services.shipping_notice.document_layout.contracts import LayoutBBox, normalize_layout_text
from app.services.shipping_notice.document_layout.html_table import HtmlGrid
from app.services.shipping_notice.document_layout.opencv_table import (
reconstruct_opencv_table_geometry,
validate_opencv_cell_text,
)
class OcrLayoutModel(BaseModel):
"""为 OCR 坐标结果启用严格字段校验。"""
model_config = ConfigDict(extra='forbid')
class OcrLine(OcrLayoutModel):
"""保存一条 RapidOCR 文本行、页面坐标和置信度。"""
text: str = Field(min_length=1)
bbox: LayoutBBox
confidence: float = Field(ge=0, le=1)
class OcrCellEvidence(OcrLayoutModel):
"""保存经几何和文本双门禁确认的 OCR cell 候选。"""
cell_id: str
bbox: LayoutBBox
line_indices: list[int] = Field(default_factory=list)
class OcrTableEvidence(OcrLayoutModel):
"""汇总扫描表候选;ready=False 时禁止暴露 cell。"""
ready: bool
lines: list[OcrLine] = Field(default_factory=list)
cells: list[OcrCellEvidence] = Field(default_factory=list)
issues: list[str] = Field(default_factory=list)
@lru_cache(maxsize=1)
def _ocr_engine() -> Any:
"""惰性创建 RapidOCR 引擎,避免未使用 OCR 时加载模型。"""
from rapidocr_onnxruntime import RapidOCR
return RapidOCR()
def extract_ocr_lines(
image: Any, *, page_width: float, page_height: float, minimum_confidence: float = 0.8,
) -> list[OcrLine]:
"""
将 RapidOCR 图像像素多边形映射为 PDF 页面坐标。
Args:
image: PDFium 渲染的页面 ndarray。
page_width/page_height: PDF 页面单位尺寸。
minimum_confidence: OCR 行最低可信度;低于阈值完全丢弃。
Returns:
保持 OCR 返回顺序的文本行坐标。
"""
if not 0 < minimum_confidence <= 1:
raise ValueError('OCR minimum confidence must be within (0, 1]')
height, width = image.shape[:2]
if width <= 0 or height <= 0 or page_width <= 0 or page_height <= 0:
raise ValueError('OCR page dimensions must be positive')
result, _elapsed = _ocr_engine()(image)
lines: list[OcrLine] = []
for item in result or []:
if len(item) < 3:
continue
polygon, raw_text, raw_confidence = item[0], item[1], item[2]
text = str(raw_text or '').strip()
confidence = float(raw_confidence or 0)
if not text or not normalize_layout_text(text) or confidence < minimum_confidence:
continue
try:
xs = [float(point[0]) for point in polygon]
ys = [float(point[1]) for point in polygon]
bbox = LayoutBBox(
x0=min(xs) * page_width / width,
y0=min(ys) * page_height / height,
x1=max(xs) * page_width / width,
y1=max(ys) * page_height / height,
)
if bbox.x1 > page_width or bbox.y1 > page_height:
continue
lines.append(OcrLine(text=text, bbox=bbox, confidence=confidence))
except (TypeError, ValueError, IndexError):
continue
return lines
def build_ocr_table_evidence(
*, image: Any, page_width: float, page_height: float,
table_bbox: LayoutBBox, grid: HtmlGrid,
) -> OcrTableEvidence:
"""对扫描表执行 OCR 行坐标、OpenCV 网格和全部非空 cell 文本三重门禁。"""
try:
lines = extract_ocr_lines(image, page_width=page_width, page_height=page_height)
except Exception:
return OcrTableEvidence(ready=False, issues=['ocr_engine_unavailable'])
if not lines:
return OcrTableEvidence(ready=False, issues=['ocr_text_missing'])
geometry = reconstruct_opencv_table_geometry(
image, page_width=page_width, page_height=page_height,
table_bbox=table_bbox, grid=grid,
)
validation = validate_opencv_cell_text(
geometry, grid=grid,
bounded_text_reader=lambda bbox: _text_within(lines, bbox),
minimum_match_rate=1,
required_cell_ids={item.cell_id for item in grid.cells if item.text.strip()},
)
if not validation.accepted:
return OcrTableEvidence(
ready=False, issues=sorted(set(geometry.issues + validation.issues)),
)
cells = []
for item in geometry.cells:
indices = _line_indices_within(lines, item.bbox)
expected = next(cell for cell in grid.cells if cell.cell_id == item.cell_id)
if expected.text.strip() and not indices:
return OcrTableEvidence(ready=False, issues=['ocr_cell_tokens_missing'])
cells.append(OcrCellEvidence(cell_id=item.cell_id, bbox=item.bbox, line_indices=indices))
return OcrTableEvidence(ready=True, lines=lines, cells=cells, issues=[])
def _line_indices_within(lines: list[OcrLine], bbox: LayoutBBox) -> list[int]:
"""返回中心点位于 cell 内的 OCR 行索引。"""
return [
index for index, item in enumerate(lines)
if bbox.x0 <= (item.bbox.x0 + item.bbox.x1) / 2 <= bbox.x1
and bbox.y0 <= (item.bbox.y0 + item.bbox.y1) / 2 <= bbox.y1
]
def _text_within(lines: list[OcrLine], bbox: LayoutBBox) -> str:
"""按 OCR 顺序读取 cell 内文本行,供独立一致性校验。"""
return ' '.join(lines[index].text for index in _line_indices_within(lines, bbox))
@@ -11,6 +11,7 @@ from __future__ import annotations
import hashlib
import json
import re
from decimal import Decimal
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, model_validator
@@ -80,6 +81,9 @@ class OrderDocumentProfile(OrderProfileModel):
columns = [item.column_index for item in self.column_rules]
if len(columns) != len(set(columns)):
raise ValueError('order profile source columns must be unique')
targets = [code for item in self.column_rules for code in item.target_field_codes]
if len(targets) != len(set(targets)):
raise ValueError('order profile target fields must be unique across columns')
if self.data_start_row_index <= self.header_row_index:
raise ValueError('order profile data rows must start after the header')
if self.row_structure == 'unsupported_row_structure' and self.column_rules:
@@ -228,7 +232,7 @@ def _parse_profile_row(
if value is None:
issues.append(f'order_profile_field_invalid:{code}')
continue
fields[code] = value.isoformat() if hasattr(value, 'isoformat') else value
fields[code] = _profile_json_value(value)
if profile.drop_zero_qty and explicit_qty == 0:
return OrderProfileRowResult(row_index=row_index, status='deleted')
required_build = {'part_number', 'qty'}
@@ -278,3 +282,10 @@ def _normalize_profile_value(raw: Any, config: dict[str, Any] | None) -> Any:
return value if value is not None and validate_order_field_value(value, config) else None
except (ArithmeticError, TypeError, ValueError, ValidationError):
return None
def _profile_json_value(value: Any) -> Any:
"""把字段规则返回值转换为数据库 JSON 可序列化标量。"""
if isinstance(value, Decimal):
return int(value) if value == value.to_integral_value() else float(value)
return value.isoformat() if hasattr(value, 'isoformat') else value
@@ -0,0 +1,238 @@
"""
backend/app/services/shipping_notice/document_layout/runtime.py
用途:在独立布局 Job 中调用 MinerU,并生成可持久化的紧凑文本、表格及原生 PDF 候选快照。
依赖:Flask 配置、MinerUClient、MinerU pipeline 候选契约、native_pdf。
逻辑:保存受字符预算限制的分页文本块、整表 HTML 和保守 layout.v1 候选;Provider 错误安全降级,不保存原始响应。
"""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Any
from flask import current_app
from app.core.errors import AppError
from app.services.shipping_notice.document_layout.mineru import (
MINERU_SUPPORTED_EXTENSIONS,
MinerUClient,
MinerUClientConfig,
parse_mineru_candidate,
)
LAYOUT_SNAPSHOT_VERSION = 'shipping_document_table_snapshot.v1'
def _enabled() -> bool:
"""读取显式 MinerU 开关;未配置时不得在上传链静默增加外部调用。"""
return bool(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED', False))
def mineru_layout_capture_enabled(filename: str) -> bool:
"""判断文件是否需要读取二进制并调用 MinerU,供上传链避免默认关闭时重复对象存储 I/O。"""
return _enabled() and Path(str(filename or '')).suffix.lower() in MINERU_SUPPORTED_EXTENSIONS
def build_mineru_table_snapshot(
*,
filename: str,
content: bytes,
read_timeout_seconds: int | None = None,
document_id: int | None = None,
content_hash: str | None = None,
) -> dict[str, Any] | None:
"""
为一个受支持附件生成紧凑 MinerU 文本与表格快照。
核心逻辑:保留分页非表格文本块和表格 HTML,分别执行字符预算;不持久化
task_id、Provider 原始响应、模型中间输出或逐字符坐标。
Args:
filename: 原附件名,仅用于扩展名和 MinerU multipart,不进入返回错误详情。
content: 原始文件字节;不写数据库和日志。
document_id/content_hash: PDF 的版本化 Document 身份;两者齐全时生成 layout.v1 候选。
Returns:
关闭/不支持时返回 None;成功或 Provider 降级均返回受控的版本化状态对象。
"""
extension = Path(str(filename or '')).suffix.lower()
if not mineru_layout_capture_enabled(filename) or not content:
return None
base_url = str(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL') or '').strip()
if not base_url:
return {
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
'provider': 'mineru',
'backend': 'pipeline',
'status': 'config_missing',
'tables': [],
'issues': ['mineru_base_url_missing'],
}
config = MinerUClientConfig(
base_url=base_url,
backend='pipeline',
connect_timeout_seconds=int(current_app.config.get(
'SHIPPING_NOTICE_LAYOUT_MINERU_CONNECT_TIMEOUT_SECONDS', 10,
)),
read_timeout_seconds=int(read_timeout_seconds or min(
int(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS', 300)),
max(int(current_app.config.get('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', 300)) - 30, 1),
)),
)
try:
candidate = parse_mineru_candidate(
MinerUClient(config).parse_file_async(filename=filename, content=content),
)
except AppError as exc:
return {
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
'provider': 'mineru',
'backend': 'pipeline',
'status': 'failed',
'tables': [],
'issues': [str(exc.code)],
}
except (TypeError, ValueError):
return {
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
'provider': 'mineru',
'backend': 'pipeline',
'status': 'failed',
'tables': [],
'issues': ['SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE'],
}
max_html_chars = max(int(current_app.config.get(
'SHIPPING_NOTICE_LAYOUT_MAX_HTML_CHARS', 1_000_000,
)), 1)
max_text_chars = max(int(current_app.config.get(
'SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS', 200_000,
) or 200_000), 1)
tables: list[dict[str, Any]] = []
text_blocks: list[dict[str, Any]] = []
total_html_chars = 0
total_text_chars = 0
issues = list(candidate.capability.issues)
for page in candidate.pages:
for block in sorted(
page.text_blocks,
key=lambda item: (
item.normalized_bbox.y0, item.normalized_bbox.x0,
item.normalized_bbox.y1, item.normalized_bbox.x1,
),
):
text = ' '.join(str(block.text or '').split()).strip()
if not text:
continue
if total_text_chars + len(text) > max_text_chars:
issues.append('mineru_text_budget_exceeded')
continue
total_text_chars += len(text)
text_blocks.append({
'page_no': block.page_no,
'normalized_bbox': block.normalized_bbox.model_dump(mode='json'),
'text': text,
'content_type': block.content_type,
})
for table in page.tables:
html = str(table.html or '')
if total_html_chars + len(html) > max_html_chars:
issues.append('mineru_table_html_budget_exceeded')
continue
total_html_chars += len(html)
tables.append({
'table_id': table.candidate_id,
'page_no': table.page_no,
'bbox': table.bbox.model_dump(mode='json'),
'normalized_bbox': table.normalized_bbox.model_dump(mode='json'),
'html': html,
'row_count': table.row_count,
'cell_count': table.cell_count,
'has_rowspan': table.has_rowspan,
'has_colspan': table.has_colspan,
})
snapshot = {
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
'provider': 'mineru',
'provider_version': candidate.provider_version,
'backend': candidate.backend or 'pipeline',
'status': 'ready',
'text_blocks': text_blocks,
'tables': tables,
'capability': candidate.capability.model_dump(mode='json'),
'issues': sorted(set(issues)),
}
if extension == '.pdf' and document_id and content_hash:
try:
from app.services.shipping_notice.document_layout.native_pdf import (
build_native_pdf_layout_candidate,
)
layout = build_native_pdf_layout_candidate(
document_id=int(document_id), content_hash=str(content_hash),
content=content, mineru=candidate,
)
snapshot['layout_candidate'] = layout.model_dump(mode='json')
except Exception:
snapshot['issues'] = sorted(set(
list(snapshot['issues']) + ['native_pdf_layout_candidate_invalid'],
))
return snapshot
def attach_mineru_layout_snapshots(result: Any, *, root_asset_bytes: bytes | None = None) -> None:
"""就地为 NoticeIntakeResult 的根文件或 EML 附件补充布局快照,失败不阻断文本解析。"""
meta = result.meta if isinstance(getattr(result, 'meta', None), dict) else {}
attachments = meta.get('attachments') if isinstance(meta.get('attachments'), list) else []
if attachments:
app = current_app._get_current_object()
eligible = [
item for item in attachments
if isinstance(item, dict)
and isinstance(item.get('_payload_bytes'), bytes)
and mineru_layout_capture_enabled(str(item.get('filename') or ''))
]
max_documents = max(int(current_app.config.get(
'SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', 4,
)), 0)
concurrency = max(int(current_app.config.get(
'SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY', 2,
)), 1)
selected = eligible[:max_documents]
for item in eligible[max_documents:]:
item['layout_snapshot'] = {
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
'provider': 'mineru', 'backend': 'pipeline', 'status': 'skipped_budget',
'tables': [], 'issues': ['mineru_intake_document_budget_exceeded'],
}
batch_count = max((len(selected) + concurrency - 1) // concurrency, 1)
configured_timeout = int(current_app.config.get(
'SHIPPING_NOTICE_LAYOUT_MINERU_READ_TIMEOUT_SECONDS', 300,
))
total_timeout = int(current_app.config.get('SHIPPING_NOTICE_PARSE_WORKER_TIMEOUT_SECONDS', 300))
per_request_timeout = max(min(configured_timeout, (max(total_timeout - 30, 1) // batch_count)), 1)
def parse_attachment(item: dict[str, Any]) -> dict[str, Any] | None:
"""在线程独立应用上下文中解析一个附件,不访问 ORM Session。"""
with app.app_context():
return build_mineru_table_snapshot(
filename=str(item.get('filename') or ''),
content=item['_payload_bytes'],
read_timeout_seconds=per_request_timeout,
)
if selected:
with ThreadPoolExecutor(max_workers=min(concurrency, len(selected))) as pool:
snapshots = list(pool.map(parse_attachment, selected))
for item, snapshot in zip(selected, snapshots, strict=True):
if snapshot is not None:
item['layout_snapshot'] = snapshot
return
if isinstance(root_asset_bytes, bytes):
snapshot = build_mineru_table_snapshot(
filename=str(getattr(result, 'filename', '') or ''), content=root_asset_bytes,
)
if snapshot is not None:
meta['layout_snapshot'] = snapshot
@@ -0,0 +1,112 @@
"""
backend/app/services/shipping_notice/document_layout/schema_mapping.py
用途:将 shipping_document_layout.v1 的真实 cell/token 证据映射到 Run 冻结订单 Schema。
依赖:布局契约、HTML 网格统一映射器、TableHeaderContract。
逻辑:只消费契约已验证行列和显式 continuation;不猜跨页、不提升质量状态、不接受无 cell 证据字段。
"""
from __future__ import annotations
from typing import Any
from app.services.shipping_notice.document_layout.contracts import LayoutDocument, LayoutTable, validate_layout_document
from app.services.shipping_notice.document_layout.html_table import (
HtmlGrid,
HtmlGridCell,
HtmlGridSlot,
map_html_grid_to_schema,
)
from app.services.shipping_notice.order_schema.table_contract import TableHeaderContract
def map_layout_document_to_schema(
layout: LayoutDocument | dict[str, Any], *, contract: TableHeaderContract,
) -> list[dict[str, Any]]:
"""
映射完整布局文档,并输出保留 cell/token 证据的安全候选。
Args:
layout: 必须通过 shipping_document_layout.v1 完整校验。
contract: 当前 Run 冻结订单 Schema 表头契约。
Returns:
每张表的映射、质量和显式跨页父表;needs_review 永不伪装 accepted。
"""
document = validate_layout_document(layout)
result: list[dict[str, Any]] = []
for page in document.pages:
for table in page.tables:
grid = layout_table_to_grid(table)
mapped = map_html_grid_to_schema(
grid, page_no=page.page_no, table_id=table.table_id, contract=contract,
)
token_ids_by_cell = {
cell.cell_id: list(cell.token_ids)
for row in table.rows for cell in row.cells
}
result.append({
'page_no': page.page_no,
'table_id': table.table_id,
'continuation_of': table.continuation_of,
'layout_status': table.status,
'mapping_status': 'candidate' if table.status != 'accepted' else 'accepted',
'header_row_index': mapped.header_row_index,
'issues': sorted(set(
list(mapped.issues)
+ ([] if table.status == 'accepted' else ['layout_table_not_accepted'])
)),
'columns': [item.model_dump(mode='json') for item in mapped.columns],
'rows': [{
**row.model_dump(mode='json'),
'fields': [{
**field.model_dump(mode='json'),
'token_ids': token_ids_by_cell.get(field.cell_id, []),
'evidence_ref': (
f'layout:{document.document_id}:p{page.page_no}:'
f'{table.table_id}:{field.cell_id}'
),
} for field in row.fields],
} for row in mapped.rows],
})
return result
def layout_table_to_grid(table: LayoutTable) -> HtmlGrid:
"""把 layout.v1 Table 转换为矩形 Grid,同时保留真实 cell_id、span 和角色。"""
occupied: dict[tuple[int, int], HtmlGridSlot] = {}
cells: list[HtmlGridCell] = []
max_row = 0
max_column = 0
for row in table.rows:
for cell in row.cells:
is_header = cell.role == 'header' or row.role == 'header'
cells.append(HtmlGridCell(
cell_id=cell.cell_id,
row_index=cell.row_index,
column_index=cell.column_index,
row_span=cell.row_span,
column_span=cell.column_span,
text=cell.text,
normalized_text=cell.normalized_text,
is_header=is_header,
))
for row_index in range(cell.row_index, cell.row_index + cell.row_span):
for column_index in range(cell.column_index, cell.column_index + cell.column_span):
occupied[(row_index, column_index)] = HtmlGridSlot(
row_index=row_index, column_index=column_index,
cell_id=cell.cell_id, text=cell.text,
normalized_text=cell.normalized_text, is_header=is_header,
origin_row_index=cell.row_index,
origin_column_index=cell.column_index,
)
max_row = max(max_row, row_index + 1)
max_column = max(max_column, column_index + 1)
return HtmlGrid(
row_count=max_row,
column_count=max_column,
rows=[
[occupied.get((row_index, column_index)) for column_index in range(max_column)]
for row_index in range(max_row)
],
cells=cells,
)
@@ -0,0 +1,212 @@
"""
backend/app/services/shipping_notice/document_layout/text_cell_alignment.py
用途:用原生 PDF 字符坐标为 MinerU HTML cell 生成严格、可追溯的几何候选。
依赖:document_layout contracts/html_table、Pydantic。
逻辑:只接受表格区域内唯一且不重叠的规范化文本匹配;重复、空白或冲突 cell 不猜框。
"""
from __future__ import annotations
import re
import unicodedata
from typing import Any
from pydantic import BaseModel, ConfigDict, Field, ValidationError as PydanticValidationError, model_validator
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.html_table import HtmlGrid
class TextCellAlignmentModel(BaseModel):
"""为字符和 cell 候选启用严格字段校验,防止评测辅助结果静默漂移。"""
model_config = ConfigDict(extra='forbid')
class PositionedCharacter(TextCellAlignmentModel):
"""保存 PDF 原生文本层的单个可见字符及页面坐标。"""
text: str = Field(min_length=1, max_length=8)
bbox: LayoutBBox
source_index: int | None = Field(default=None, ge=0)
class TextAlignedCell(TextCellAlignmentModel):
"""保存唯一文本匹配得到的 HTML cell 候选框;仍需人工视觉确认。"""
cell_id: str
row_index: int = Field(ge=0)
column_index: int = Field(ge=0)
bbox: LayoutBBox
normalized_bbox: LayoutBBox
glyph_indices: list[int] = Field(default_factory=list)
class TextCellAlignmentResult(TextCellAlignmentModel):
"""汇总严格文本对齐覆盖率和不准入原因,不复制文档原文。"""
complete: bool
expected_cell_count: int = Field(ge=0)
matched_cell_count: int = Field(ge=0)
cells: list[TextAlignedCell] = Field(default_factory=list)
issues: list[str] = Field(default_factory=list)
@model_validator(mode='after')
def validate_completeness(self) -> 'TextCellAlignmentResult':
"""完整结果必须覆盖所有原始 cell;不完整结果不得伪报 complete。"""
expected = self.expected_cell_count > 0 and self.matched_cell_count == self.expected_cell_count
if self.complete != expected:
raise ValueError('text cell alignment completeness is inconsistent')
if self.matched_cell_count != len(self.cells):
raise ValueError('text cell alignment count is inconsistent')
return self
def align_html_cells_from_positioned_text(
grid: HtmlGrid,
*,
characters: list[PositionedCharacter | dict[str, Any]],
table_bbox: LayoutBBox,
page_width: float,
page_height: float,
) -> TextCellAlignmentResult:
"""
在整表区域内按唯一规范化文本匹配 HTML 原始 cell,并合并字符 bbox。
Args:
grid: 已展开但仍保留原始 cell 身份的 HTML 网格。
characters: PDF 原生文本层字符及左上原点页面坐标。
table_bbox: MinerU 整表页面 bbox,仅在该范围内搜索。
page_width/page_height: 页面尺寸,用于生成 0..1 标准化坐标。
Returns:
可供人工叠框 Review 的候选;任何歧义都保留 issue,绝不进入生产证据。
"""
if page_width <= 0 or page_height <= 0:
raise ValueError('text cell alignment page dimensions must be positive')
if table_bbox.x1 > page_width or table_bbox.y1 > page_height:
raise ValueError('text cell alignment table bbox must be within the page')
glyphs: list[PositionedCharacter] = []
invalid_character_bbox = False
for item in characters:
try:
glyph = item if isinstance(item, PositionedCharacter) else PositionedCharacter.model_validate(item)
except PydanticValidationError:
invalid_character_bbox = True
continue
if glyph.bbox.x1 > page_width or glyph.bbox.y1 > page_height:
invalid_character_bbox = True
continue
glyphs.append(glyph)
glyphs = [item for item in glyphs if _bbox_center_within(table_bbox, item.bbox)]
normalized_stream, stream_to_glyph = _normalized_character_stream(glyphs)
used_glyphs: set[int] = set()
matched: list[TextAlignedCell] = []
issues: set[str] = set()
if invalid_character_bbox:
issues.add('text_cell_alignment_invalid_character_bbox')
for cell in grid.cells:
expected = _normalize_text(cell.text)
if not expected:
issues.add('text_cell_alignment_empty_cell')
continue
starts = [match.start() for match in re.finditer(re.escape(expected), normalized_stream)]
if len(starts) != 1:
issues.add(
'text_cell_alignment_text_not_found'
if not starts else 'text_cell_alignment_text_not_unique'
)
continue
indices = set(stream_to_glyph[starts[0]:starts[0] + len(expected)])
if not indices or indices & used_glyphs:
issues.add('text_cell_alignment_glyph_overlap')
continue
matched_glyphs = [glyphs[index] for index in sorted(indices)]
if not _glyphs_form_contiguous_text(matched_glyphs):
issues.add('text_cell_alignment_geometry_discontinuous')
continue
bbox = _union_bbox([item.bbox for item in matched_glyphs])
used_glyphs.update(indices)
matched.append(TextAlignedCell(
cell_id=cell.cell_id,
row_index=cell.row_index,
column_index=cell.column_index,
bbox=bbox,
normalized_bbox=LayoutBBox(
x0=bbox.x0 / page_width,
y0=bbox.y0 / page_height,
x1=bbox.x1 / page_width,
y1=bbox.y1 / page_height,
),
glyph_indices=sorted(
glyphs[index].source_index if glyphs[index].source_index is not None else index
for index in indices
),
))
return TextCellAlignmentResult(
complete=bool(grid.cells) and len(matched) == len(grid.cells),
expected_cell_count=len(grid.cells),
matched_cell_count=len(matched),
cells=matched,
issues=sorted(issues),
)
def _normalized_character_stream(
characters: list[PositionedCharacter],
) -> tuple[str, list[int]]:
"""生成规范化字符流,并保留每个输出字符到原 glyph 的反向索引。"""
stream: list[str] = []
mapping: list[int] = []
for index, item in enumerate(characters):
normalized = _normalize_text(item.text)
stream.extend(normalized)
mapping.extend([index] * len(normalized))
return ''.join(stream), mapping
def _normalize_text(value: Any) -> str:
"""以 NFKC/casefold 保留字母数字和中日韩字符,忽略版面空白及标点。"""
text = unicodedata.normalize('NFKC', str(value or '')).casefold()
return re.sub(r'[^0-9a-z\u4e00-\u9fff]+', '', text)
def _bbox_center_within(parent: LayoutBBox, child: LayoutBBox) -> bool:
"""使用字符中心点筛选整表区域,允许字体 bbox 轻微越过表格边界。"""
center_x = (child.x0 + child.x1) / 2
center_y = (child.y0 + child.y1) / 2
return parent.x0 <= center_x <= parent.x1 and parent.y0 <= center_y <= parent.y1
def _union_bbox(boxes: list[LayoutBBox]) -> LayoutBBox:
"""合并唯一匹配字符范围;调用方保证列表非空。"""
return LayoutBBox(
x0=min(item.x0 for item in boxes),
y0=min(item.y0 for item in boxes),
x1=max(item.x1 for item in boxes),
y1=max(item.y1 for item in boxes),
)
def _glyphs_form_contiguous_text(characters: list[PositionedCharacter]) -> bool:
"""要求匹配字符处于同一视觉行且水平间距连续,禁止跨 cell/跨行拼接。"""
if not characters:
return False
heights = [item.bbox.y1 - item.bbox.y0 for item in characters]
median_height = sorted(heights)[len(heights) // 2]
allowed_vertical_drift = max(2.0, median_height * 0.75)
center_y = sum((item.bbox.y0 + item.bbox.y1) / 2 for item in characters) / len(characters)
if any(abs((item.bbox.y0 + item.bbox.y1) / 2 - center_y) > allowed_vertical_drift for item in characters):
return False
ordered = sorted(characters, key=lambda item: item.bbox.x0)
if characters != ordered:
return False
widths = [item.bbox.x1 - item.bbox.x0 for item in characters]
median_width = sorted(widths)[len(widths) // 2]
allowed_gap = max(4.0, median_width * 3.0)
return all(
right.bbox.x0 - left.bbox.x1 <= allowed_gap
for left, right in zip(characters, characters[1:])
)