feat(shipping-notice): 添加货代履约策略管理功能,支持策略创建、发布及版本控制,增强订单冻结和预约管理逻辑

This commit is contained in:
hugo committed 2026-07-23 12:06:34 +08:00
1 parent abd8fc1e16
commit d62f5107b2
82 files changed
+4914 -514

No files matched your search

@@ -17,8 +17,8 @@ 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)
_LINE_NUMBER_PATTERN = re.compile(r'^(?:0{2,}\d+|\d{1,6})$')
_DELETED_PATTERN = re.compile(r'^\*+itemdeleted\*+$', re.IGNORECASE)
class CoordinateReconstructionModel(BaseModel):
@@ -32,6 +32,7 @@ class CoordinateColumnAnchor(CoordinateReconstructionModel):
column_index: int = Field(ge=0)
bbox: LayoutBBox
field_code: str | None = None
class ReconstructedCell(CoordinateReconstructionModel):
@@ -44,10 +45,10 @@ class ReconstructedCell(CoordinateReconstructionModel):
class ReconstructedRow(CoordinateReconstructionModel):
"""一个 y-band 形成的视觉行;删除标记只能附着在前一强锚定行。"""
"""一个 y-band 形成的视觉行;其角色供后续逻辑明细合并使用。"""
row_index: int = Field(ge=0)
role: Literal['data', 'continuation', 'deleted', 'needs_review']
role: Literal['data', 'continuation', 'deleted', 'header', 'summary', 'needs_review']
cells: list[ReconstructedCell] = Field(min_length=1)
@model_validator(mode='after')
@@ -67,11 +68,128 @@ class CoordinateTableReconstruction(CoordinateReconstructionModel):
issues: list[str] = Field(default_factory=list)
_HEADER_TERMS = frozenset({
'item', 'material', 'description', 'date', 'price', 'quantity', 'amount',
'brand', 'manufacturer', 'delivery', 'shipping', 'drawing', 'rev',
})
_SUMMARY_PATTERN = re.compile(
r'(?:total\s*amount|incl\.?\s*tax|subtotal|invoice\s*bill|terms?\s*and\s*conditions?)',
re.IGNORECASE,
)
class CoordinateSubrowLayout(CoordinateReconstructionModel):
"""一条逻辑明细内某类物理子行的独立列边界与固定字段语义。"""
role: Literal['main', 'continuation']
row_offset: int = Field(ge=0)
column_boundaries: list[float] = Field(min_length=2)
column_field_codes: list[str | None]
@model_validator(mode='after')
def validate_layout(self) -> 'CoordinateSubrowLayout':
"""确保子行边界覆盖整表,且每个区间恰好对应一个字段或忽略项。"""
if self.column_boundaries[0] != 0 or self.column_boundaries[-1] != 1:
raise ValueError('coordinate subrow boundaries must start at 0 and end at 1')
if any(left >= right for left, right in zip(self.column_boundaries, self.column_boundaries[1:])):
raise ValueError('coordinate subrow boundaries must be strictly increasing')
if len(self.column_field_codes) != len(self.column_boundaries) - 1:
raise ValueError('coordinate subrow field codes must match column count')
return self
class ReconstructedLogicalRow(CoordinateReconstructionModel):
"""多子行版式合并后的单条逻辑订单明细及来源物理行。"""
role: Literal['data', 'deleted']
fields: dict[str, str] = Field(default_factory=dict)
source_row_indices: list[int] = Field(min_length=1)
class CoordinateSubrowSuggestion(CoordinateReconstructionModel):
"""从实际字符坐标生成的单种物理行版式建议,不包含绝对坐标。"""
role: Literal['main', 'continuation']
row_offset: int = Field(ge=0)
column_boundaries: list[float] = Field(min_length=2)
column_samples: list[list[str]]
suggested_field_codes: list[str | None]
def suggest_multi_subrow_layouts(
*,
characters: list[PositionedCharacter | dict[str, Any]],
table_bbox: LayoutBBox | dict[str, Any],
) -> list[CoordinateSubrowSuggestion]:
"""
从实际物理行和文本起始位置自动建议动态多行版式。
AI/调用方触发时机:管理员打开坐标重建且不清楚相对边界时调用。算法只负责把
同一明细中的第 1..N 行分组并建议列区间;除可确定的 ``line_no`` 外不猜业务字段,
建议结果仍须管理员结合示例文字确认。
Args:
characters: 当前表格冻结的 PDF 原生或 OCR 字符坐标。
table_bbox: 当前数据表范围。
Returns:
按 row_offset 排列的动态行建议;找不到可靠主行时返回空列表。
"""
bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox)
glyphs = _table_glyphs(characters, bbox)
if not glyphs:
return []
bands = _group_visual_rows(glyphs)
groups: list[list[list[tuple[int, PositionedCharacter]]]] = []
current: list[list[tuple[int, PositionedCharacter]]] | None = None
for band in bands:
text = ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)).strip()
compact = re.sub(r'\s+', '', text)
if _SUMMARY_PATTERN.search(text):
if current:
groups.append(current)
break
if _DELETED_PATTERN.fullmatch(compact):
if current:
groups.append(current)
current = None
continue
if _band_starts_item(band, bbox):
if current:
groups.append(current)
current = [band]
elif current is not None:
current.append(band)
if current:
groups.append(current)
if not groups:
return []
max_rows = max(len(group) for group in groups)
suggestions: list[CoordinateSubrowSuggestion] = []
for row_offset in range(max_rows):
samples = [group[row_offset] for group in groups if row_offset < len(group)]
boundaries, column_samples, line_column = _suggest_band_boundaries(
samples, bbox, detect_line_number=row_offset == 0,
)
suggestions.append(CoordinateSubrowSuggestion(
role='main' if row_offset == 0 else 'continuation',
row_offset=row_offset,
column_boundaries=boundaries,
column_samples=column_samples,
suggested_field_codes=[
'line_no' if row_offset == 0 and index == line_column else None
for index in range(len(boundaries) - 1)
],
))
return suggestions
def reconstruct_table_from_positioned_text(
*,
characters: list[PositionedCharacter | dict[str, Any]],
table_bbox: LayoutBBox,
column_anchors: list[CoordinateColumnAnchor | dict[str, Any]],
line_start_column_index: int = 0,
) -> CoordinateTableReconstruction:
"""
以 x 列锚点、y 视觉行和内容/邻接辅助规则重建保守候选。
@@ -83,7 +201,8 @@ def reconstruct_table_from_positioned_text(
Args:
characters: 表格范围内外的 PDF 原生字符及 source_index。
table_bbox: 当前表格的真实页面范围。
column_anchors: 从可信表头得到的列区间,至少两列且不可重叠。
column_anchors: 管理员确认的列区间及可选固定字段编码,至少两列且不可重叠。
line_start_column_index: 出现有效行号时代表新明细的列,默认第一列。
Returns:
带 glyph 索引的视觉行候选;status 始终为 needs_review。
"""
@@ -95,14 +214,19 @@ def reconstruct_table_from_positioned_text(
issues: set[str] = set()
rows: list[ReconstructedRow] = []
previous_has_line_number = False
data_region_started = 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)
previous_column: int | None = None
for text_run in _group_text_runs(band):
run_bbox = _run_bbox(text_run)
run_text = ''.join(glyph.text for _, glyph in text_run).strip()
column = _assign_column(run_bbox, run_text, anchors, previous_column=previous_column)
if column is None:
issues.add('coordinate_reconstruction_column_ambiguous')
continue
cells.setdefault(column, []).append((glyph_index, glyph))
cells.setdefault(column, []).extend(text_run)
previous_column = column
if not cells:
continue
rebuilt = [
@@ -110,27 +234,225 @@ def reconstruct_table_from_positioned_text(
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'] = (
has_line_number = any(
cell.column_index == line_start_column_index
and _LINE_NUMBER_PATTERN.fullmatch(cell.text.replace(' ', ''))
for cell in rebuilt
)
compact_text = re.sub(r'\s+', '', text)
if _SUMMARY_PATTERN.search(text):
role: Literal['data', 'continuation', 'deleted', 'header', 'summary', 'needs_review'] = 'summary'
previous_has_line_number = False
elif _DELETED_PATTERN.fullmatch(compact_text):
role = (
'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'
data_region_started = True
elif not data_region_started and _looks_like_header(text):
role = 'header'
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)
previous_has_line_number = has_line_number or (role in {'continuation', 'deleted'} and previous_has_line_number)
if not rows:
issues.add('coordinate_reconstruction_rows_missing')
return CoordinateTableReconstruction(rows=rows, issues=sorted(issues))
def reconstruct_multi_subrow_table(
*,
characters: list[PositionedCharacter | dict[str, Any]],
table_bbox: LayoutBBox,
subrow_layouts: list[CoordinateSubrowLayout | dict[str, Any]],
line_start_field_code: str = 'line_no',
) -> list[ReconstructedLogicalRow]:
"""
使用每种子行的独立边界,将重叠版式的多条物理行合并为订单明细。
核心逻辑:每个视觉行先按主行布局寻找行号;命中后开始新明细。后续物理行按
``row_offset`` 选择第 2..N 行布局,将值直接合并到固定字段,而不是沿用首行列号。
Args:
characters: 表格范围内的原生或 OCR 字符坐标。
table_bbox: 当前数据表页面范围。
subrow_layouts: 主行、补充行和属性行的独立边界及字段映射。
line_start_field_code: 标记新明细的固定字段,默认 ``line_no``。
Returns:
合并后的逻辑明细;纯表头、说明和合计区域不会返回。
"""
layouts = [
item if isinstance(item, CoordinateSubrowLayout) else CoordinateSubrowLayout.model_validate(item)
for item in subrow_layouts
]
by_offset = {item.row_offset: item for item in layouts}
main = by_offset.get(0)
if main is None or not any(code == line_start_field_code for code in main.column_field_codes):
raise ValueError('multi-subrow reconstruction requires a main row line-start field')
glyphs = _table_glyphs(characters, table_bbox)
if not glyphs:
return []
anchors = {item.row_offset: _layout_anchors(item, table_bbox) for item in layouts}
max_offset = max(by_offset)
logical_rows: list[ReconstructedLogicalRow] = []
current_fields: dict[str, str] | None = None
current_sources: list[int] = []
continuation_offset = 0
current_deleted = False
def flush() -> None:
"""将当前已聚合子行固化为一条逻辑明细。"""
nonlocal current_fields, current_sources, current_deleted
if current_fields is not None and current_sources:
logical_rows.append(ReconstructedLogicalRow(
role='deleted' if current_deleted else 'data',
fields=current_fields,
source_row_indices=current_sources,
))
current_fields = None
current_sources = []
current_deleted = False
for row_index, band in enumerate(_group_visual_rows(glyphs)):
raw_text = ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)).strip()
compact_text = re.sub(r'\s+', '', raw_text)
if _SUMMARY_PATTERN.search(raw_text):
flush()
break
if _DELETED_PATTERN.fullmatch(compact_text):
if current_fields is not None:
current_deleted = True
current_sources.append(row_index)
continue
main_values = _band_field_values(band, anchors[0])
line_value = re.sub(r'\s+', '', main_values.get(line_start_field_code, ''))
if _LINE_NUMBER_PATTERN.fullmatch(line_value):
flush()
current_fields = main_values
current_sources = [row_index]
continuation_offset = 0
continue
if current_fields is None:
continue
continuation_offset += 1
selected_offset = continuation_offset if continuation_offset in by_offset else max_offset
values = _band_field_values(band, anchors[selected_offset])
for field_code, value in values.items():
previous = current_fields.get(field_code, '').strip()
current_fields[field_code] = f'{previous} {value}'.strip()
current_sources.append(row_index)
flush()
return logical_rows
def _layout_anchors(layout: CoordinateSubrowLayout, table_bbox: LayoutBBox) -> list[CoordinateColumnAnchor]:
"""将子行相对边界转换为当前表格绝对列区间。"""
width = table_bbox.x1 - table_bbox.x0
return [CoordinateColumnAnchor(
column_index=index,
field_code=layout.column_field_codes[index],
bbox=LayoutBBox(
x0=table_bbox.x0 + width * layout.column_boundaries[index], y0=table_bbox.y0,
x1=table_bbox.x0 + width * layout.column_boundaries[index + 1], y1=table_bbox.y1,
),
) for index in range(len(layout.column_field_codes))]
def _band_field_values(
band: list[tuple[int, PositionedCharacter]],
anchors: list[CoordinateColumnAnchor],
) -> dict[str, str]:
"""先形成独立文本片段,再以片段中心落入子行区间,避免字段在边界处被拆字。"""
values: dict[str, str] = {}
for text_run in _group_text_runs(band):
bbox = _run_bbox(text_run)
center = (bbox.x0 + bbox.x1) / 2
candidates = [
anchor.column_index for anchor in anchors
if anchor.bbox.x0 <= center <= anchor.bbox.x1
]
if len(candidates) != 1:
continue
column = candidates[0]
field_code = anchors[column].field_code
text = ''.join(glyph.text for _, glyph in text_run).strip()
if not field_code or not text:
continue
previous = values.get(field_code, '').strip()
values[field_code] = f'{previous} {text}'.strip()
return values
def _looks_like_header(text: str) -> bool:
"""以有限英文表头词识别数据区之前的多层表头,避免把表头并入首条明细。"""
words = set(re.findall(r'[a-z]+', text.lower()))
return len(words & _HEADER_TERMS) >= 2
def _band_starts_item(
band: list[tuple[int, PositionedCharacter]], table_bbox: LayoutBBox,
) -> bool:
"""以左侧文本片段的行号形态识别新明细,不依赖已经配置的列边界。"""
width = table_bbox.x1 - table_bbox.x0
for run in _group_text_runs(band):
bbox = _run_bbox(run)
relative_center = ((bbox.x0 + bbox.x1) / 2 - table_bbox.x0) / width
text = re.sub(r'\s+', '', ''.join(glyph.text for _, glyph in run))
if relative_center <= 0.25 and _LINE_NUMBER_PATTERN.fullmatch(text):
return True
return False
def _suggest_band_boundaries(
bands: list[list[tuple[int, PositionedCharacter]]],
table_bbox: LayoutBBox,
*,
detect_line_number: bool,
) -> tuple[list[float], list[list[str]], int | None]:
"""聚合相同 row_offset 的文本起始位置,以相邻列中心中点生成稳定相对边界。"""
width = table_bbox.x1 - table_bbox.x0
runs: list[tuple[float, str, bool]] = []
for band in bands:
for run in _group_text_runs(band):
bbox = _run_bbox(run)
center = max(0.0, min(1.0, ((bbox.x0 + bbox.x1) / 2 - table_bbox.x0) / width))
text = ''.join(glyph.text for _, glyph in run).strip()
if text:
runs.append((center, text, bool(_LINE_NUMBER_PATTERN.fullmatch(re.sub(r'\s+', '', text)))))
if not runs:
return [0.0, 1.0], [[]], None
centers: list[float] = []
clusters: list[list[tuple[float, str, bool]]] = []
for item in sorted(runs, key=lambda value: value[0]):
nearest = min(range(len(centers)), key=lambda index: abs(centers[index] - item[0])) if centers else None
if nearest is not None and abs(centers[nearest] - item[0]) <= 0.045:
clusters[nearest].append(item)
centers[nearest] = median(value[0] for value in clusters[nearest])
else:
centers.append(item[0])
clusters.append([item])
ordered = sorted(zip(centers, clusters), key=lambda item: item[0])
centers = [item[0] for item in ordered]
clusters = [item[1] for item in ordered]
boundaries = [0.0] + [round((left + right) / 2, 4) for left, right in zip(centers, centers[1:])] + [1.0]
column_samples = [list(dict.fromkeys(value[1] for value in cluster))[:3] for cluster in clusters]
line_column = next((
index for index, cluster in enumerate(clusters)
if detect_line_number and any(value[2] for value in cluster)
), None)
return boundaries, column_samples, line_column
def _validated_anchors(raw: list[CoordinateColumnAnchor | dict[str, Any]]) -> list[CoordinateColumnAnchor]:
"""校验列锚点数量、排序与不重叠,防止错误表头诱导列归属。"""
anchors = sorted(
@@ -175,16 +497,87 @@ def _group_visual_rows(glyphs: list[tuple[int, PositionedCharacter]]) -> list[li
return bands
def _assign_column(bbox: LayoutBBox, anchors: list[CoordinateColumnAnchor]) -> int | None:
"""优先最大 x-overlap,只有唯一最佳候选才允许归属;中心距离仅作无重叠时的后备。"""
def _group_text_runs(
band: list[tuple[int, PositionedCharacter]],
) -> list[list[tuple[int, PositionedCharacter]]]:
"""将同一视觉行的相邻字符组成文本片段,使字段格式评分可看到完整值。"""
ordered = sorted(band, key=lambda item: (item[1].bbox.x0, item[0]))
widths = [glyph.bbox.x1 - glyph.bbox.x0 for _, glyph in ordered]
gap_limit = max(2.0, median(widths) * 1.8)
runs: list[list[tuple[int, PositionedCharacter]]] = []
for item in ordered:
if runs and item[1].bbox.x0 - runs[-1][-1][1].bbox.x1 <= gap_limit:
runs[-1].append(item)
else:
runs.append([item])
return runs
def _run_bbox(run: list[tuple[int, PositionedCharacter]]) -> LayoutBBox:
"""汇总文本片段 bbox,供列重叠与中心距离共同评分。"""
boxes = [glyph.bbox for _, glyph in run]
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 _assign_column(
bbox: LayoutBBox,
text: str,
anchors: list[CoordinateColumnAnchor],
*,
previous_column: int | None,
) -> 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
if best_overlap > 0:
candidates = [index for index, overlap in enumerate(overlaps) if overlap >= best_overlap * 0.8]
if len(candidates) == 1:
return anchors[candidates[0]].column_index
scores = []
for index in candidates:
adjacency = 0.0
if previous_column is not None:
if anchors[index].column_index < previous_column:
adjacency = -1.0
elif anchors[index].column_index in {previous_column, previous_column + 1}:
adjacency = 0.25
scores.append(
overlaps[index]
+ _field_content_score(text, anchors[index].field_code) * max(bbox.x1 - bbox.x0, 1.0) * 0.25
+ adjacency
)
best_score = max(scores)
return anchors[candidates[scores.index(best_score)]].column_index if scores.count(best_score) == 1 else None
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
candidates = [index for index, distance in enumerate(distances) if distance == nearest]
if previous_column is not None:
ordered_candidates = [index for index in candidates if anchors[index].column_index >= previous_column]
candidates = ordered_candidates or candidates
return anchors[candidates[0]].column_index if len(candidates) == 1 else None
def _field_content_score(text: str, field_code: str | None) -> float:
"""对固定订单字段执行有限格式评分;未知字段不影响几何归列。"""
value = str(text or '').strip()
if not value or not field_code:
return 0.0
compact = value.replace(',', '').replace(' ', '')
if field_code == 'line_no':
return 1.0 if _LINE_NUMBER_PATTERN.fullmatch(compact) else -1.0
if field_code in {'qty', 'unit_price', 'amount'}:
return 1.0 if re.fullmatch(r'[-+]?\d+(?:\.\d+)?', compact) else -1.0
if field_code == 'uom':
return 1.0 if re.fullmatch(r'[A-Za-z]{1,6}', compact) else -0.5
if field_code == 'required_date':
return 1.0 if re.fullmatch(r'\d{1,4}[-/]\d{1,2}[-/]\d{1,4}', compact) else -0.5
if field_code in {'part_number', 'customer_part_number', 'aws_part_number'}:
return 0.75 if re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._/-]{2,}', compact) else 0.0
return 0.0
def _cell_from_glyphs(column_index: int, glyphs: list[tuple[int, PositionedCharacter]]) -> ReconstructedCell:
@@ -3,12 +3,13 @@ backend/app/services/shipping_notice/document_layout/order_profile.py
用途:定义订单文档模板级解析 Profile 纯契约,覆盖全局 Schema 无法表达的模板列语义。
依赖:Pydantic、HTML 网格、订单字段规则和既有 TEMP 复合料号规则。
逻辑:Profile 只在精确结构指纹命中时按固定列执行注册解析器;行结构已丢失的模板显式阻断,不做相似匹配。
逻辑:普通 Profile 按精确表头指纹匹配;坐标 Profile 先合并物理续行并生成稳定虚拟表头,再按固定列执行注册解析器。
"""
from __future__ import annotations
import hashlib
import html
import json
import re
from decimal import Decimal
@@ -17,6 +18,7 @@ from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, model_validator
from app.core.errors import ValidationError
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.html_table import HtmlGrid, parse_html_grid
from app.services.shipping_notice.notice_line_values import parse_number
from app.services.shipping_notice.notice_lines import resolve_composite_part_numbers
@@ -66,6 +68,45 @@ class OrderProfileColumnRule(OrderProfileModel):
return self
class CoordinateReconstructionProfile(OrderProfileModel):
"""冻结管理员确认的相对列边界;同版 PDF 表格据此重建并仍受 Profile 精确指纹门禁。"""
method: Literal['native_pdf_coordinates.v1', 'ocr_pdf_coordinates.v1'] = 'native_pdf_coordinates.v1'
column_boundaries: list[float] = Field(default_factory=list)
column_field_codes: list[str | None] = Field(default_factory=list)
line_start_column_index: int = Field(default=0, ge=0)
subrow_layouts: list[dict[str, Any]] = Field(default_factory=list)
@model_validator(mode='after')
def validate_boundaries(self) -> 'CoordinateReconstructionProfile':
"""边界须覆盖整表且严格递增,禁止由错误 HTML 反向猜列。"""
if self.subrow_layouts:
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import CoordinateSubrowLayout
layouts = [CoordinateSubrowLayout.model_validate(item) for item in self.subrow_layouts]
offsets = [item.row_offset for item in layouts]
roles = [item.role for item in layouts]
if len(offsets) != len(set(offsets)) or sorted(offsets) != list(range(len(offsets))) or roles.count('main') != 1:
raise ValueError('coordinate subrow layouts require contiguous offsets and one main row')
if next(item for item in layouts if item.role == 'main').row_offset != 0:
raise ValueError('coordinate main row must use offset zero')
if any(item.row_offset > 0 and item.role != 'continuation' for item in layouts):
raise ValueError('coordinate rows after the main row must be continuations')
return self
if len(self.column_boundaries) < 3:
raise ValueError('coordinate reconstruction requires column boundaries')
if self.column_boundaries[0] != 0 or self.column_boundaries[-1] != 1:
raise ValueError('coordinate reconstruction boundaries must start at 0 and end at 1')
if any(left >= right for left, right in zip(self.column_boundaries, self.column_boundaries[1:])):
raise ValueError('coordinate reconstruction boundaries must be strictly increasing')
column_count = len(self.column_boundaries) - 1
if self.column_field_codes and len(self.column_field_codes) != column_count:
raise ValueError('coordinate reconstruction field codes must match column count')
if self.line_start_column_index >= column_count:
raise ValueError('coordinate reconstruction line start column is out of range')
return self
class OrderDocumentProfile(OrderProfileModel):
"""保存不可变模板结构、列覆盖、数据起始行和质量策略。"""
@@ -77,6 +118,7 @@ class OrderDocumentProfile(OrderProfileModel):
data_start_row_index: int = Field(ge=1)
row_structure: Literal['preserved', 'unsupported_row_structure'] = 'preserved'
column_rules: list[OrderProfileColumnRule] = Field(default_factory=list)
coordinate_reconstruction: CoordinateReconstructionProfile | None = None
drop_zero_qty: bool = True
@model_validator(mode='after')
@@ -171,6 +213,104 @@ def order_profile_structure_fingerprint(
return hashlib.sha256(encoded).hexdigest()
def reconstruct_order_profile_html(
*, characters: list[dict[str, Any]], table_bbox: dict[str, Any],
reconstruction: CoordinateReconstructionProfile,
) -> str:
"""
利用冻结坐标证据生成带稳定虚拟表头的逻辑明细 HTML。
核心逻辑:先按 x/y 重建物理行,再将 continuation 按列并入最近 data 行;deleted
回写最近明细状态,summary 终止数据区。虚拟表头只表达列序,不依赖数据页表头是否完整。
Args:
characters: 当前表格 bbox 内的原生或 OCR 字符坐标。
table_bbox: 当前表格页面坐标。
reconstruction: 管理员确认的相对列边界。
Returns:
可由既有 Profile 解析器消费的 HTML;行角色保存在 ``data-row-role`` 属性中。
"""
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
CoordinateColumnAnchor,
reconstruct_multi_subrow_table,
reconstruct_table_from_positioned_text,
)
bbox = LayoutBBox.model_validate(table_bbox)
if reconstruction.subrow_layouts:
logical_rows = reconstruct_multi_subrow_table(
characters=characters,
table_bbox=bbox,
subrow_layouts=reconstruction.subrow_layouts,
)
field_codes = []
for layout in reconstruction.subrow_layouts:
for code in layout.get('column_field_codes') or []:
if code and code not in field_codes:
field_codes.append(code)
header = '<tr data-row-role="header">' + ''.join(
f'<th>{html.escape(code)}</th>' for code in field_codes
) + '</tr>'
body = ''.join(
'<tr data-row-role="{}" data-source-rows="{}">{}</tr>'.format(
row.role, ','.join(str(index) for index in row.source_row_indices),
''.join(f'<td>{html.escape(row.fields.get(code, ""))}</td>' for code in field_codes),
)
for row in logical_rows
)
return f'<table>{header}{body}</table>'
boundaries = reconstruction.column_boundaries
width = bbox.x1 - bbox.x0
anchors = [CoordinateColumnAnchor(
column_index=index,
field_code=(reconstruction.column_field_codes[index] if reconstruction.column_field_codes else None),
bbox=LayoutBBox(
x0=bbox.x0 + width * boundaries[index], y0=bbox.y0,
x1=bbox.x0 + width * boundaries[index + 1], y1=bbox.y1,
),
) for index in range(len(boundaries) - 1)]
result = reconstruct_table_from_positioned_text(
characters=characters, table_bbox=bbox, column_anchors=anchors,
line_start_column_index=reconstruction.line_start_column_index,
)
if not result.rows:
raise ValidationError(
'No coordinate reconstruction rows were produced',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE',
)
logical_rows: list[dict[str, Any]] = []
for row in result.rows:
values = {cell.column_index: cell.text for cell in row.cells}
if row.role == 'data':
logical_rows.append({'role': 'data', 'values': values, 'source_rows': [row.row_index]})
elif row.role == 'continuation' and logical_rows:
current = logical_rows[-1]
for column_index, value in values.items():
previous = str(current['values'].get(column_index) or '').strip()
current['values'][column_index] = f'{previous} {value}'.strip()
current['source_rows'].append(row.row_index)
elif row.role == 'deleted' and logical_rows:
logical_rows[-1]['role'] = 'deleted'
logical_rows[-1]['source_rows'].append(row.row_index)
elif row.role == 'summary':
break
header = '<tr data-row-role="header">' + ''.join(
f'<th>coordinate_column_{index + 1}</th>' for index in range(len(anchors))
) + '</tr>'
body = ''.join(
'<tr data-row-role="{}" data-source-rows="{}">{}</tr>'.format(
row['role'], ','.join(str(index) for index in row['source_rows']),
''.join(
f'<td>{html.escape(str(row["values"].get(index, "")))}</td>'
for index in range(len(anchors))
),
)
for row in logical_rows
)
return f'<table>{header}{body}</table>'
def parse_html_table_with_order_profile(
html: str,
*,
@@ -210,15 +350,19 @@ def parse_html_table_with_order_profile(
profile_version=profile.version,
issues=['order_profile_column_out_of_range'],
)
row_roles = _profile_html_row_roles(html)
rows = [
_parse_profile_row(
grid,
row_index=index,
profile=profile,
contract=contract,
source_role=row_roles[index] if index < len(row_roles) else 'data',
)
for index in range(profile.data_start_row_index, grid.row_count)
]
if not rows:
return OrderProfileParseResult(matched=False)
return OrderProfileParseResult(
matched=True,
profile_code=profile.profile_code,
@@ -233,8 +377,9 @@ def _parse_profile_row(
row_index: int,
profile: OrderDocumentProfile,
contract: TableHeaderContract,
source_role: str = 'data',
) -> OrderProfileRowResult:
"""执行一条 preserved 模板行;零 Qty 删除,非法字段保留机器问题码。"""
"""执行一条逻辑模板行;坐标重建删除状态和零 Qty 均映射为 deleted。"""
fields: dict[str, Any] = {}
issues: list[str] = []
explicit_qty: float | None = None
@@ -258,7 +403,7 @@ def _parse_profile_row(
issues.append(f'order_profile_field_invalid:{code}')
continue
fields[code] = _profile_json_value(value)
if profile.drop_zero_qty and explicit_qty == 0:
if source_role == 'deleted' or (profile.drop_zero_qty and explicit_qty == 0):
return OrderProfileRowResult(row_index=row_index, status='deleted')
required_build = {'part_number', 'qty'}
if not required_build.issubset(fields):
@@ -271,6 +416,16 @@ def _parse_profile_row(
)
def _profile_html_row_roles(source_html: str) -> list[str]:
"""读取坐标重建写入的受控行角色;普通 MinerU HTML 默认按 data 处理。"""
from bs4 import BeautifulSoup
table = BeautifulSoup(source_html or '', 'html.parser').find('table')
if table is None:
return []
return [str(row.get('data-row-role') or 'data') for row in table.find_all('tr')]
def _apply_profile_extractor(extractor_key: str, raw: str) -> dict[str, Any]:
"""执行代码注册的有限解析器;未知 key 不允许运行。"""
if extractor_key == 'temp_internal_parts':
@@ -289,11 +444,16 @@ def _apply_profile_extractor(extractor_key: str, raw: str) -> dict[str, Any]:
def _normalize_profile_value(raw: Any, config: dict[str, Any] | None) -> Any:
"""按冻结 Schema 类型和 validator 规范化模板字段;非法值返回 None。"""
"""按冻结 Schema 类型和 validator 规范化模板字段;模板日期兼容常见美式订单格式。"""
if config is None:
return None
value_type = str(config.get('value_type') or 'string')
candidate = raw
if value_type == 'date':
text = str(raw or '').strip()
matched = re.fullmatch(r'(\d{1,2})/(\d{1,2})/(\d{4})', text)
if matched:
candidate = f'{matched.group(3)}-{int(matched.group(1)):02d}-{int(matched.group(2)):02d}'
if value_type in {'decimal', 'integer'}:
candidate = parse_number(raw)
if candidate is None:
@@ -167,6 +167,7 @@ def build_mineru_table_snapshot(
try:
from app.services.shipping_notice.document_layout.native_pdf import (
build_native_pdf_layout_candidate,
extract_native_pdf_pages,
)
layout = build_native_pdf_layout_candidate(
@@ -174,6 +175,10 @@ def build_mineru_table_snapshot(
content=content, mineru=candidate,
)
snapshot['layout_candidate'] = layout.model_dump(mode='json')
# 仅保存表格范围内的原生字符坐标,供管理员确认后的坐标模板在 Run 冻结快照中复现。
snapshot['coordinate_evidence'] = _table_coordinate_evidence(
content=content, tables=tables,
)
except Exception:
snapshot['issues'] = sorted(set(
list(snapshot['issues']) + ['native_pdf_layout_candidate_invalid'],
@@ -181,6 +186,34 @@ def build_mineru_table_snapshot(
return snapshot
def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]]) -> dict[str, Any]:
"""按 MinerU 整表 bbox 截取 PDF 字符证据;非表格正文与页面图像绝不持久化。"""
from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages
pages = {item.page_no: item for item in extract_native_pdf_pages(content)}
evidence: dict[str, list[dict[str, Any]]] = {}
for table in tables:
table_id = str(table.get('table_id') or '')
raw_bbox = table.get('bbox')
page = pages.get(int(table.get('page_no') or 0))
if not table_id or page is None or not isinstance(raw_bbox, dict):
continue
try:
x0, y0 = float(raw_bbox['x0']), float(raw_bbox['y0'])
x1, y1 = float(raw_bbox['x1']), float(raw_bbox['y1'])
except (KeyError, TypeError, ValueError):
continue
glyphs = []
for item in page.characters:
center_x = (item.bbox.x0 + item.bbox.x1) / 2
center_y = (item.bbox.y0 + item.bbox.y1) / 2
if x0 <= center_x <= x1 and y0 <= center_y <= y1:
glyphs.append(item.model_dump(mode='json'))
if glyphs:
evidence[table_id] = glyphs
return {'version': 'shipping_order_coordinate_evidence.v1', 'tables': evidence}
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 {}