feat(shipping-notice): 添加订单文档 Profile 盲测集和样本管理功能,支持创建、执行和批准盲测,增强订单冻结和库存核验功能

This commit is contained in:
hugo committed 2026-07-23 00:15:34 +08:00
1 parent c35223d49d
commit abd8fc1e16
98 files changed
+4629 -528

No files matched your search

@@ -0,0 +1,202 @@
"""
从 PDF 原生字符坐标重建被 HTML 网格错误拆分的订单表格候选。
依赖:布局 bbox 契约和 PositionedCharacter。调用方必须先提供已人工确认的列锚点;本模块
只按几何、有限内容形态和相邻行连续性生成可审计的 needs_review 候选,绝不自动接受。
"""
from __future__ import annotations
import re
from statistics import median
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, model_validator
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter
_LINE_NUMBER_PATTERN = re.compile(r'^0{2,}\d+$')
_DELETED_PATTERN = re.compile(r'^\*+\s*item\s+deleted\s*\*+$', re.IGNORECASE)
class CoordinateReconstructionModel(BaseModel):
"""为坐标重建的中间证据启用严格契约,禁止调用方注入未定义字段。"""
model_config = ConfigDict(extra='forbid')
class CoordinateColumnAnchor(CoordinateReconstructionModel):
"""人工确认表头后冻结的列几何区间;不从错误的 HTML 表头自行猜测。"""
column_index: int = Field(ge=0)
bbox: LayoutBBox
class ReconstructedCell(CoordinateReconstructionModel):
"""一段按 x 归属的原生文本及其证据 glyph 索引。"""
column_index: int = Field(ge=0)
text: str = Field(min_length=1)
bbox: LayoutBBox
glyph_indices: list[int] = Field(min_length=1)
class ReconstructedRow(CoordinateReconstructionModel):
"""一个 y-band 形成的视觉行;删除标记只能附着在前一强锚定行。"""
row_index: int = Field(ge=0)
role: Literal['data', 'continuation', 'deleted', 'needs_review']
cells: list[ReconstructedCell] = Field(min_length=1)
@model_validator(mode='after')
def validate_columns(self) -> 'ReconstructedRow':
"""确保同一视觉行中的列按几何顺序且无重复,方便人工复核。"""
columns = [cell.column_index for cell in self.cells]
if columns != sorted(columns) or len(columns) != len(set(columns)):
raise ValueError('reconstructed row columns must be unique and ascending')
return self
class CoordinateTableReconstruction(CoordinateReconstructionModel):
"""坐标重建输出,固定为 needs_review 并给出不含文档原文的诊断码。"""
status: Literal['needs_review'] = 'needs_review'
rows: list[ReconstructedRow] = Field(default_factory=list)
issues: list[str] = Field(default_factory=list)
def reconstruct_table_from_positioned_text(
*,
characters: list[PositionedCharacter | dict[str, Any]],
table_bbox: LayoutBBox,
column_anchors: list[CoordinateColumnAnchor | dict[str, Any]],
) -> CoordinateTableReconstruction:
"""
以 x 列锚点、y 视觉行和内容/邻接辅助规则重建保守候选。
AI/调用方触发时机:仅当 MinerU 网格已确认行列关系错误、且 PDF 原生 glyph 坐标和
人工确认列锚点均存在时调用。没有锚点、越界 glyph、列归属并列或删除行无前序明细时,
必须保留 needs_review,不能用本函数替代人工确认。
Args:
characters: 表格范围内外的 PDF 原生字符及 source_index。
table_bbox: 当前表格的真实页面范围。
column_anchors: 从可信表头得到的列区间,至少两列且不可重叠。
Returns:
带 glyph 索引的视觉行候选;status 始终为 needs_review。
"""
anchors = _validated_anchors(column_anchors)
glyphs = _table_glyphs(characters, table_bbox)
if not glyphs:
return CoordinateTableReconstruction(issues=['coordinate_reconstruction_text_missing'])
issues: set[str] = set()
rows: list[ReconstructedRow] = []
previous_has_line_number = False
for row_index, band in enumerate(_group_visual_rows(glyphs)):
cells: dict[int, list[tuple[int, PositionedCharacter]]] = {}
for glyph_index, glyph in band:
column = _assign_column(glyph.bbox, anchors)
if column is None:
issues.add('coordinate_reconstruction_column_ambiguous')
continue
cells.setdefault(column, []).append((glyph_index, glyph))
if not cells:
continue
rebuilt = [
_cell_from_glyphs(column, value)
for column, value in sorted(cells.items())
]
text = ' '.join(cell.text for cell in rebuilt)
has_line_number = any(_LINE_NUMBER_PATTERN.fullmatch(cell.text.replace(' ', '')) for cell in rebuilt)
if _DELETED_PATTERN.fullmatch(text.strip()):
role: Literal['data', 'continuation', 'deleted', 'needs_review'] = (
'deleted' if previous_has_line_number else 'needs_review'
)
if role == 'needs_review':
issues.add('coordinate_reconstruction_deleted_row_unattached')
elif has_line_number:
role = 'data'
else:
role = 'continuation' if previous_has_line_number else 'needs_review'
if role == 'needs_review':
issues.add('coordinate_reconstruction_row_unanchored')
rows.append(ReconstructedRow(row_index=row_index, role=role, cells=rebuilt))
previous_has_line_number = has_line_number or (role == 'continuation' and previous_has_line_number)
if not rows:
issues.add('coordinate_reconstruction_rows_missing')
return CoordinateTableReconstruction(rows=rows, issues=sorted(issues))
def _validated_anchors(raw: list[CoordinateColumnAnchor | dict[str, Any]]) -> list[CoordinateColumnAnchor]:
"""校验列锚点数量、排序与不重叠,防止错误表头诱导列归属。"""
anchors = sorted(
[item if isinstance(item, CoordinateColumnAnchor) else CoordinateColumnAnchor.model_validate(item) for item in raw],
key=lambda item: item.column_index,
)
if len(anchors) < 2 or [item.column_index for item in anchors] != list(range(len(anchors))):
raise ValueError('coordinate reconstruction requires contiguous column anchors')
if any(right.bbox.x0 < left.bbox.x1 for left, right in zip(anchors, anchors[1:])):
raise ValueError('coordinate reconstruction column anchors must not overlap')
return anchors
def _table_glyphs(
raw: list[PositionedCharacter | dict[str, Any]], table_bbox: LayoutBBox,
) -> list[tuple[int, PositionedCharacter]]:
"""只保留中心落在表格内的有效 glyph,并以 y/x/source 顺序稳定排序。"""
glyphs: list[tuple[int, PositionedCharacter]] = []
for index, item in enumerate(raw):
glyph = item if isinstance(item, PositionedCharacter) else PositionedCharacter.model_validate(item)
center_x = (glyph.bbox.x0 + glyph.bbox.x1) / 2
center_y = (glyph.bbox.y0 + glyph.bbox.y1) / 2
if table_bbox.x0 <= center_x <= table_bbox.x1 and table_bbox.y0 <= center_y <= table_bbox.y1:
glyphs.append((glyph.source_index if glyph.source_index is not None else index, glyph))
return sorted(glyphs, key=lambda item: ((item[1].bbox.y0 + item[1].bbox.y1) / 2, item[1].bbox.x0, item[0]))
def _group_visual_rows(glyphs: list[tuple[int, PositionedCharacter]]) -> list[list[tuple[int, PositionedCharacter]]]:
"""按自适应 y 阈值形成视觉行,阈值来自字体高度而不是固定页面像素。"""
heights = [glyph.bbox.y1 - glyph.bbox.y0 for _, glyph in glyphs]
tolerance = max(2.0, median(heights) * 0.75)
bands: list[list[tuple[int, PositionedCharacter]]] = []
centers: list[float] = []
for item in glyphs:
center = (item[1].bbox.y0 + item[1].bbox.y1) / 2
if bands and abs(center - centers[-1]) <= tolerance:
bands[-1].append(item)
centers[-1] = sum((glyph.bbox.y0 + glyph.bbox.y1) / 2 for _, glyph in bands[-1]) / len(bands[-1])
else:
bands.append([item])
centers.append(center)
return bands
def _assign_column(bbox: LayoutBBox, anchors: list[CoordinateColumnAnchor]) -> int | None:
"""优先最大 x-overlap,只有唯一最佳候选才允许归属;中心距离仅作无重叠时的后备。"""
overlaps = [max(0.0, min(bbox.x1, item.bbox.x1) - max(bbox.x0, item.bbox.x0)) for item in anchors]
best_overlap = max(overlaps)
if best_overlap > 0 and overlaps.count(best_overlap) == 1:
return anchors[overlaps.index(best_overlap)].column_index
center = (bbox.x0 + bbox.x1) / 2
distances = [abs(center - (item.bbox.x0 + item.bbox.x1) / 2) for item in anchors]
nearest = min(distances)
return anchors[distances.index(nearest)].column_index if distances.count(nearest) == 1 else None
def _cell_from_glyphs(column_index: int, glyphs: list[tuple[int, PositionedCharacter]]) -> ReconstructedCell:
"""合并同一视觉行、同一列的 glyph,保留按页面位置排序的证据索引。"""
ordered = sorted(glyphs, key=lambda item: item[1].bbox.x0)
boxes = [item.bbox for _, item in ordered]
return ReconstructedCell(
column_index=column_index,
text=''.join(item.text for _, item in ordered).strip(),
bbox=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),
),
glyph_indices=[index for index, _ in ordered],
)
@@ -32,6 +32,10 @@ from app.services.shipping_notice.order_schema.table_contract import (
ORDER_PROFILE_VERSION = 'shipping_order_document_profile.v1'
PROFILE_EXTRACTORS = frozenset({'direct', 'temp_internal_parts'})
HEADER_LINE_ITEM_VALUE_PATTERN = re.compile(
r'\b(?:item|line)\s*(?:no\.?|number|#)?\s*[:#-]?\s*0{2,}\d+\b',
re.IGNORECASE,
)
class OrderProfileModel(BaseModel):
@@ -112,6 +116,27 @@ class OrderProfileParseResult(OrderProfileModel):
issues: list[str] = Field(default_factory=list)
def diagnose_order_profile_header(grid: HtmlGrid, *, header_row_index: int) -> list[str]:
"""
诊断管理员所选表头是否已经混入明显的订单明细值。
只有在表头 cell 同时出现 Item/Line 标签和零填充行号时才判定污染;普通的
``Item No`` 表头不会触发。该诊断是建 Profile 前的硬门禁,避免把错误网格固化。
Args:
grid: 已展开的 MinerU HTML 网格。
header_row_index: 管理员选择的最后一行表头索引。
Returns:
稳定、无原文的诊断码列表,供预览和服务端阻断共用。
"""
if header_row_index < 0 or header_row_index >= grid.row_count:
raise ValueError('order profile header row index is invalid')
header_slots = (slot for row in grid.rows[:header_row_index + 1] for slot in row if slot)
if any(HEADER_LINE_ITEM_VALUE_PATTERN.search(slot.text or '') for slot in header_slots):
return ['order_profile_header_contaminated_by_data']
return []
def order_profile_structure_fingerprint(
grid: HtmlGrid, *, header_row_index: int,
) -> str: