feat(shipping-order): 迭代货代订单提取与履约全流程功能

添加订单字段自动标注配置,默认仅关键字段参与自动框选
完善字段规范化逻辑,支持更多日期格式解析
添加订单候选人工采纳、驳回的完整流程,包含API、前端交互与状态管理
完善盲测功能,支持订单级字段真值校验,调整盲测集唯一性约束
加固库存校验逻辑,防止重复预约与数量不一致问题
优化坐标匹配逻辑,支持表格外的锚点定位
新增上传结果未知的状态处理,完善任务状态机
更新多语言文案与文档说明,补充功能细节
修复订单合并、重解析的边缘情况问题
补充相关测试用例,完善质量保障
This commit is contained in:
hugo committed 2026-07-27 20:48:40 +08:00
1 parent 11079910ec
commit 90f77634d6
76 files changed
+5056 -338

No files matched your search

@@ -612,18 +612,6 @@ def create_shipping_batch_from_candidates(
)
if intake.expires_at and intake.expires_at < now:
raise ConflictError(code='SHIPPING_NOTICE.INTAKE_EXPIRED', message='接入记录已过期')
if not candidate.selected:
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_NOT_SELECTED', message='订单候选未选中')
if not candidate.is_current_version:
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_SUPERSEDED', message='订单候选已被重新识别版本替代')
if candidate.consumed_task_id is not None:
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选已被消费')
if str(candidate.validation_status or '') != 'ready' or candidate.conflicts_json:
raise ConflictError(
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
message='订单候选仍有字段冲突或未完成审核',
details={'candidate_no': candidate.candidate_no, 'conflicts': list(candidate.conflicts_json or [])},
)
document = db.session.get(ShippingNoticeDocument, int(candidate.primary_document_id))
if document is None or document.parse_status != 'parsed':
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_DOCUMENT_INVALID', message='订单候选主附件不可用')
@@ -728,6 +716,8 @@ def create_shipping_batch_from_candidates(
})
candidate.updated_at = now
continue
from app.services.shipping_notice.candidate_service import ensure_candidate_fulfillment_ready
ensure_candidate_fulfillment_ready(candidate)
create_items.append(candidate_to_notice_item(candidate, intake, document))
create_candidates.append(candidate)
@@ -905,6 +895,7 @@ def create_shipping_batch_from_intakes(
ShippingNoticeIntake.user_id == int(user_id),
ShippingNoticeIntake.intake_no.in_(normalized),
ShippingNoticeCandidate.selected.is_(True),
ShippingNoticeCandidate.candidate_status == 'accepted',
ShippingNoticeCandidate.consumed_task_id.is_(None),
)
.order_by(ShippingNoticeCandidate.id.asc())
@@ -23,6 +23,26 @@ from app.services.shipping_notice.intake_service import can_force_create_shippin
_ACTIONS = frozenset({'open_existing', 'create_revision', 'force_create'})
def ensure_candidate_fulfillment_ready(candidate: ShippingNoticeCandidate) -> None:
"""统一履约门禁:只有已接受、当前且无阻断问题的 Candidate 才能建单。"""
if str(candidate.candidate_status or '') != 'accepted':
raise ConflictError(
code='SHIPPING_NOTICE.CANDIDATE_ACCEPTANCE_REQUIRED',
message='订单候选尚未被接受,不能进入履约',
)
if not candidate.selected:
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_NOT_SELECTED', message='订单候选未选中')
if not candidate.is_current_version:
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_SUPERSEDED', message='订单候选已被重新识别版本替代')
if candidate.consumed_task_id is not None:
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选已被消费')
if str(candidate.validation_status or '') != 'ready' or candidate.conflicts_json:
raise ConflictError(
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
message='订单候选仍有字段冲突或未完成审核',
)
def _candidate_for_user(candidate_no: str, user_id: int, *, lock: bool = False) -> tuple[ShippingNoticeCandidate, ShippingNoticeIntake, ShippingNoticeDocument]:
"""按候选编号和用户加载 Candidate、Intake、Document;写路径可加行锁。"""
query = (
@@ -97,7 +117,8 @@ def update_candidate(*, user_id: int, candidate_no: str, selected: bool | None =
if selected is not None:
if not isinstance(selected, bool):
raise ValidationError(code='VALIDATION.INVALID_PARAM', message='selected 必须为布尔值')
candidate.selected = selected
# Selection is retained for legacy batch APIs but may not bypass acceptance.
candidate.selected = selected if candidate.candidate_status == 'accepted' else False
if business_summary is not None:
if not isinstance(business_summary, dict):
raise ValidationError(code='VALIDATION.INVALID_PARAM', message='business_summary 必须为对象')
@@ -126,6 +147,66 @@ def update_candidate(*, user_id: int, candidate_no: str, selected: bool | None =
return _serialize_candidate_brief(candidate)
def _append_candidate_decision_history(candidate: ShippingNoticeCandidate, *, action: str, user_id: int, reason: str | None = None) -> None:
"""记录人工采纳或驳回事件,便于审核回放。"""
structured = dict(candidate.structured_result_json or {})
history = list(structured.get('manual_review_history') or [])
history.append({
'action': action,
'actor_user_id': int(user_id),
'reason': str(reason or '').strip() or None,
'decided_at': datetime.utcnow().isoformat(),
})
structured['manual_review_history'] = history
candidate.structured_result_json = structured
def promote_candidate(*, user_id: int, candidate_no: str) -> dict[str, Any]:
"""人工采纳 Dify 兜底 Candidate;重复采纳请求保持幂等。"""
candidate, intake, document = _candidate_for_user(candidate_no, user_id, lock=True)
if candidate.candidate_status == 'accepted':
return _serialize_candidate_brief(candidate)
if candidate.candidate_status != 'provisional':
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_DECISION_FINAL', message='订单候选已被驳回或过期')
if str(candidate.extraction_source or '') not in {'dify_workflow', 'manual'}:
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_PROMOTION_FORBIDDEN', message='仅 Dify 兜底候选允许人工采纳')
if candidate.consumed_task_id is not None or not candidate.is_current_version:
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选不可再采纳')
_refresh_candidate(candidate, intake, document)
if candidate.validation_status != 'ready' or candidate.conflicts_json or candidate.duplicate_status not in {'none', 'unchecked'}:
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED', message='请先完成字段和重复审核')
candidate.candidate_status = 'accepted'
candidate.acceptance_mode = 'manual'
candidate.accepted_at = datetime.utcnow()
candidate.accepted_by_id = int(user_id)
candidate.acceptance_reason = 'dify_candidate_promoted'
candidate.acceptance_policy_version = 'manual-review-v1'
candidate.selected = True
_append_candidate_decision_history(candidate, action='promoted', user_id=user_id)
db.session.commit()
return _serialize_candidate_brief(candidate)
def reject_candidate(*, user_id: int, candidate_no: str, reason: str | None = None) -> dict[str, Any]:
"""人工驳回未消费 Candidate,并保留审计原因。"""
candidate, intake, _document = _candidate_for_user(candidate_no, user_id, lock=True)
if candidate.candidate_status == 'rejected':
return _serialize_candidate_brief(candidate)
if candidate.candidate_status != 'provisional' or candidate.consumed_task_id is not None or not candidate.is_current_version:
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_DECISION_FINAL', message='订单候选不可再驳回')
candidate.candidate_status = 'rejected'
candidate.selected = False
candidate.acceptance_mode = None
candidate.accepted_at = None
candidate.accepted_by_id = None
candidate.acceptance_reason = str(reason or '').strip() or 'manual_rejected'
candidate.acceptance_policy_version = 'manual-review-v1'
candidate.updated_at = datetime.utcnow()
_append_candidate_decision_history(candidate, action='rejected', user_id=user_id, reason=reason)
db.session.commit()
return _serialize_candidate_brief(candidate)
def refresh_candidate_duplicate(*, user_id: int, candidate_no: str) -> dict[str, Any]:
"""刷新单个 Candidate 的重复检测结果并清除陈旧决策。"""
candidate, intake, document = _candidate_for_user(candidate_no, user_id, lock=True)
@@ -19,6 +19,7 @@ CP_CUSTOMER_REVIEW = "customer_review"
CP_TASK_EXISTS = "task_exists"
CP_RSV_REQ = "rsv_req"
CP_UPLOAD_FAILED = "upload_failed"
CP_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown"
CP_WAITING_UPLOAD = "waiting_upload"
CP_REJECTED = "rejected"
# Derived UI checkpoints (no separate pending_human_reason; from process_status)
@@ -51,3 +52,4 @@ PH_INVENTORY_SOURCE_UNRESOLVED = "inventory_source_unresolved"
PH_NOTICE_TEXT_EXTRACTION_FAILED = CP_NOTICE_TEXT_EXTRACTION_FAILED
PH_UPLOAD_RPA_FAILED = "upload_rpa_failed"
PH_UPLOAD_RPA_PENDING = "upload_rpa_pending"
PH_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown"
@@ -233,8 +233,9 @@ def _upsert_candidate(
intake_id=int(intake.id),
primary_document_id=int(document.id),
candidate_key=str(candidate_key),
selected=True,
selected=False,
validation_status='pending',
candidate_status='provisional',
)
db.session.add(row)
row.primary_document_id = int(document.id)
@@ -336,6 +337,11 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
else {}
)
document = db.session.get(ShippingNoticeDocument, int(cand.primary_document_id))
action_buttons: list[str] = []
if cand.candidate_status == 'provisional' and cand.consumed_task_id is None and cand.is_current_version:
action_buttons.extend(['edit', 'evidence', 'reject'])
if cand.validation_status == 'ready' and not blocking:
action_buttons.append('promote')
return {
'candidate_no': cand.candidate_no,
'primary_document_id': cand.primary_document_id,
@@ -343,6 +349,14 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
'po_number': cand.po_number,
'confidence': cand.confidence,
'validation_status': cand.validation_status,
'candidate_status': cand.candidate_status,
'acceptance_mode': cand.acceptance_mode,
'accepted_at': cand.accepted_at.isoformat() if cand.accepted_at else None,
'accepted_by_id': cand.accepted_by_id,
'acceptance_reason': cand.acceptance_reason,
'acceptance_policy_version': cand.acceptance_policy_version,
'extraction_source': cand.extraction_source,
'action_buttons': action_buttons,
'selected': bool(cand.selected),
'business_fingerprint': cand.business_fingerprint,
'fingerprint_strength': cand.fingerprint_strength,
@@ -132,6 +132,8 @@ class CoordinateHeaderFieldRegionSuggestion(CoordinateReconstructionModel):
region: LayoutBBox
text: str = ''
field_code: str | None = None
confidence: Literal['exact_alias', 'ambiguous', 'unmapped'] = 'unmapped'
class HeaderFieldSuggestion(CoordinateReconstructionModel):
@@ -0,0 +1,489 @@
"""
backend/app/services/shipping_notice/document_layout/order_field_extraction.py
用途:从冻结的整页 PDF/OCR 字符坐标中确定性提取独立订单级字段。
依赖:OrderCoordinateProfileV2、冻结 Schema 字段规则和 LayoutBBox。
逻辑:订单工作流先唯一匹配模板,再调用本模块;本模块仅返回可追溯候选,绝不回读资产、数据库或调用模型。
"""
from __future__ import annotations
import re
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.order_profile import (
AnchorRelativeRegion,
AnchorRule,
OrderCoordinateProfileV2,
OrderFieldLayout,
RelativeRegion,
)
from app.services.shipping_notice.order_schema.field_rules import (
normalize_order_field_value,
validate_order_field_value,
)
class OrderFieldExtraction(BaseModel):
"""表示单个订单字段的脱敏运行期候选及其最小坐标证据。"""
model_config = ConfigDict(extra='forbid')
field_id: str
field_code: str
value: Any = None
status: Literal['confirmed', 'needs_review', 'unavailable']
source: Literal['pdf_coordinate', 'ocr_coordinate'] | None = None
page_no: int | None = Field(default=None, ge=1)
anchor_bbox: LayoutBBox | None = None
value_bbox: LayoutBBox | None = None
glyph_indices: list[int] = Field(default_factory=list)
issues: list[str] = Field(default_factory=list)
def extract_order_fields(
*, profile: OrderCoordinateProfileV2, schema_fields: dict[str, dict[str, Any]],
coordinate_evidence: dict[str, Any],
) -> list[OrderFieldExtraction]:
"""
用唯一文字锚点和相对值区读取订单字段,缺少页级证据时严格失败关闭。
Args:
profile: Run 冻结的 v2 坐标模板,不得包含待重新绑定字段。
schema_fields: 以 stable field_id 为键的冻结启用 Schema 字段。
coordinate_evidence: 冻结页尺寸、page_glyphs 与来源;不接受表格内 glyph 兜底。
Returns:
每个已绑定布局对应一个候选,按模板声明顺序返回。
"""
return [
_extract_layout(layout=layout, schema_fields=schema_fields, coordinate_evidence=coordinate_evidence)
for layout in profile.order_field_layouts
]
def _extract_layout(
*, layout: OrderFieldLayout, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any],
) -> OrderFieldExtraction:
"""处理一个订单字段布局,并把任何不确定性保留为 Review/Unavailable 而非猜测。"""
config = schema_fields.get(layout.field_id)
if config is None or not config.get('enabled', True) or config.get('scope') != 'header':
return _unavailable(layout, 'order_field_schema_binding_invalid')
pages = coordinate_evidence.get('pages') if isinstance(coordinate_evidence.get('pages'), dict) else {}
glyph_pages = coordinate_evidence.get('page_glyphs') if isinstance(coordinate_evidence.get('page_glyphs'), dict) else {}
sources = coordinate_evidence.get('sources') if isinstance(coordinate_evidence.get('sources'), dict) else {}
page_sources = sources.get('pages') if isinstance(sources.get('pages'), dict) else {}
candidates: list[tuple[int, list[dict[str, Any]], float, float, str]] = []
for raw_page_no, page in pages.items():
try:
page_no, width, height = int(raw_page_no), float(page['width']), float(page['height'])
except (KeyError, TypeError, ValueError):
continue
if not _layout_applies_to_page(layout, page_no) or width <= 0 or height <= 0:
continue
glyphs = glyph_pages.get(str(page_no))
source = str(page_sources.get(str(page_no)) or '')
if isinstance(glyphs, list) and source in {'pdf_coordinate', 'ocr_coordinate'}:
valid_glyphs = []
for item in glyphs:
if not isinstance(item, dict):
continue
try:
_glyph_bbox(item)
except Exception:
continue
valid_glyphs.append(item)
candidates.append((page_no, valid_glyphs, width, height, source))
if not candidates:
return _unavailable(layout, 'order_field_page_coordinate_evidence_missing')
results: list[OrderFieldExtraction] = []
for page_no, glyphs, width, height, source in candidates:
if not _source_allowed(layout, config=config, source=source):
results.append(_unavailable(layout, 'order_field_coordinate_source_not_allowed', page_no=page_no, source=source))
continue
if layout.anchor is None:
results.append(_read_value_region(
layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source,
region=_absolute_relative_region(layout.fallback_value_region, width=width, height=height), anchor_bbox=None,
fallback=True,
))
continue
matches = _find_anchor_matches(glyphs, layout.anchor, page_width=width, page_height=height)
if not matches:
reference_anchor = (
_anchor_from_reference_region(
glyphs, anchor=layout.anchor, page_width=width, page_height=height,
)
if _is_placeholder_anchor_text(layout.anchor.text) else None
)
if reference_anchor is not None:
# Legacy manual regions can contain a placeholder label rather than
# the PDF text. The reference box is evidence of administrator
# intent, but it must remain review-only until the label is fixed.
results.append(_read_value_region(
layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source,
region=_absolute_anchor_region(layout.value_region, reference_anchor),
anchor_bbox=reference_anchor, fallback=False,
review_issue='order_field_anchor_text_mismatch',
))
continue
results.append(_unavailable(layout, 'order_field_anchor_missing', page_no=page_no, source=source))
continue
if len(matches) != 1:
results.append(OrderFieldExtraction(
field_id=layout.field_id, field_code=layout.field_code, status='needs_review', source=source,
page_no=page_no, issues=['order_field_anchor_ambiguous'],
))
continue
anchor_bbox, _indices = matches[0]
results.append(_read_value_region(
layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source,
region=_absolute_anchor_region(layout.value_region, anchor_bbox), anchor_bbox=anchor_bbox, fallback=False,
))
usable = [item for item in results if item.status != 'unavailable']
if len(usable) == 1:
return usable[0]
if not usable:
return results[0] if results else _unavailable(layout, 'order_field_page_coordinate_evidence_missing')
values = {repr(item.value) for item in usable if item.value is not None}
# Repeated page headers are corroborating evidence, not a second business value.
# An ambiguous value on any selected page must still stop automatic acceptance.
if len(values) == 1 and not any(item.status == 'needs_review' for item in usable):
return usable[0]
first = usable[0].model_copy(deep=True)
first.status = 'needs_review'
first.issues = sorted(set(first.issues + ['order_field_page_value_conflict']))
return first
def _read_value_region(
*, layout: OrderFieldLayout, config: dict[str, Any], glyphs: list[dict[str, Any]], page_no: int,
source: str, region: LayoutBBox, anchor_bbox: LayoutBBox | None, fallback: bool,
review_issue: str | None = None,
) -> OrderFieldExtraction:
"""按视觉行合并值区文字,多行模式先以停止标签截断,再执行 Schema 规范化与校验。
``right_of_anchor`` 使用锚点右侧的同一连续文本段,而不是严格依赖值框的
左边界;这能避免标签后的冒号进入值,也能容忍框选末尾少量字符。
"""
selected = (
_inline_right_of_anchor_glyphs(glyphs=glyphs, anchor_bbox=anchor_bbox, region=region)
if layout.value_mode == 'right_of_anchor' and anchor_bbox is not None
else [(index, item) for index, item in enumerate(glyphs) if _glyph_center_inside(item, region)]
)
if layout.value_mode == 'multi_line':
selected = _stop_before_anchor(
selected, glyphs=glyphs, stop_anchors=layout.stop_anchors, anchor_bbox=anchor_bbox,
)
text = _render_value(selected, multi_line=layout.value_mode == 'multi_line')
if layout.value_mode != 'multi_line':
text = text.split('\n', 1)[0].strip()
if layout.value_mode == 'right_of_anchor':
text = text.lstrip(':: ').strip()
if str(config.get('value_type') or '') == 'date':
text = _recover_trailing_date_glyph(text=text, glyphs=glyphs, region=region)
if not text:
return _unavailable(layout, 'order_field_value_missing', page_no=page_no, source=source, anchor_bbox=anchor_bbox, value_bbox=region)
try:
value = normalize_order_field_value(text, config)
except Exception:
return _review(layout, 'order_field_normalization_failed', page_no, source, anchor_bbox, region, selected)
if value is None or not validate_order_field_value(value, config):
return _review(layout, 'order_field_validation_failed', page_no, source, anchor_bbox, region, selected)
status: Literal['confirmed', 'needs_review'] = 'needs_review' if fallback or source != 'pdf_coordinate' or review_issue else 'confirmed'
issues = ['order_field_fallback_value_region'] if fallback else []
if source == 'ocr_coordinate':
issues.append('order_field_ocr_coordinate_needs_review')
if review_issue:
issues.append(review_issue)
return OrderFieldExtraction(
field_id=layout.field_id, field_code=layout.field_code, value=value, status=status, source=source,
page_no=page_no, anchor_bbox=anchor_bbox, value_bbox=region,
glyph_indices=[index for index, _item in selected], issues=issues,
)
def _inline_right_of_anchor_glyphs(
*, glyphs: list[dict[str, Any]], anchor_bbox: LayoutBBox, region: LayoutBBox,
) -> list[tuple[int, dict[str, Any]]]:
"""读取值框内标签右侧的文本,仅在框尾补齐被截断的同一个词。
管理员的值框是字段分隔的主证据,不能按整行连续文本扩展。仅当框尾
截在英文/数字词中间时,才追加紧邻字符直至一个正常词间隔;这不会吞入
下一个字段,即使两个字段落在同一视觉行。
Args:
glyphs: 当前页面冻结的字符坐标。
anchor_bbox: 已唯一定位的标签字符联合框。
region: 管理员配置的相对值区投影框。
Returns:
值框内文本及其被截断的当前词的原始 glyph 索引和字符。
"""
anchor_center_y = (anchor_bbox.y0 + anchor_bbox.y1) / 2
same_line = [
(index, glyph) for index, glyph in enumerate(glyphs)
if _glyph_bbox(glyph).x0 >= anchor_bbox.x1
and region.y0 <= (_glyph_bbox(glyph).y0 + _glyph_bbox(glyph).y1) / 2 <= region.y1
and abs(((_glyph_bbox(glyph).y0 + _glyph_bbox(glyph).y1) / 2) - anchor_center_y)
<= max(anchor_bbox.y1 - anchor_bbox.y0, _glyph_bbox(glyph).y1 - _glyph_bbox(glyph).y0) * .55
]
ordered = sorted(same_line, key=lambda item: _glyph_bbox(item[1]).x0)
selected = [item for item in ordered if _glyph_center_inside(item[1], region)]
if not selected:
return []
last_position = next(
(position for position in range(len(ordered) - 1, -1, -1) if ordered[position][0] == selected[-1][0]),
-1,
)
previous = _glyph_bbox(selected[-1][1])
for item in ordered[last_position + 1:]:
bbox = _glyph_bbox(item[1])
typical_width = max((previous.x1 - previous.x0 + bbox.x1 - bbox.x0) / 2, .01)
# A normal word gap terminates the only permitted overrun. This admits
# ``Corporati`` -> ``Corporation`` but not a following address/field.
if bbox.x0 - previous.x1 > typical_width * .75:
break
selected.append(item)
previous = bbox
return selected
def _recover_trailing_date_glyph(*, text: str, glyphs: list[dict[str, Any]], region: LayoutBBox) -> str:
"""补入紧贴日期值框右缘的单个数字,容忍管理员框选少一个字宽但不扩展到下一字段。"""
compact = re.sub(r'\s+', '', text)
if not re.fullmatch(r'(?:\d{4}[-/.]\d{1,2}[-/.]\d{1,2}|\d{1,2}[-/.]\d{1,2}[-/.]\d{1,3})', compact):
return text
candidates = []
for glyph in glyphs:
try:
bbox = _glyph_bbox(glyph)
except Exception:
continue
if not str(glyph.get('text') or '').isdigit() or bbox.y1 < region.y0 or bbox.y0 > region.y1:
continue
glyph_width = max(bbox.x1 - bbox.x0, .01)
if 0 <= bbox.x0 - region.x1 <= glyph_width * 1.5:
candidates.append((bbox.x0, str(glyph.get('text') or '')))
if len(candidates) != 1:
return text
return f'{text}{candidates[0][1]}'
def _find_anchor_matches(
glyphs: list[dict[str, Any]], anchor: AnchorRule, *, page_width: float | None = None, page_height: float | None = None,
) -> list[tuple[LayoutBBox, list[int]]]:
"""在每个视觉行内执行精确标签匹配,返回去重后的字符联合框。"""
expected = [anchor.text, *anchor.aliases]
matches: list[tuple[LayoutBBox, list[int]]] = []
for row in _visual_rows(list(enumerate(glyphs))):
# PDFium does not emit whitespace glyphs consistently, so labels are compared
# after whitespace folding while preserving a mapping back to real characters.
compact: list[tuple[int, dict[str, Any]]] = [
pair for pair in row if str(pair[1].get('text') or '').strip()
]
row_text = ''.join(str(item.get('text') or '') for _index, item in compact)
folded = row_text.casefold()
for label in expected:
normalized = re.sub(r'\s+', '', label).casefold()
start = 0
while normalized and (position := folded.find(normalized, start)) >= 0:
consumed = compact[position:position + len(normalized)]
if len(consumed) == len(normalized) and _anchor_occurrence_is_exact(
compact, position=position, length=len(normalized), anchor=anchor,
):
bbox = _union_bbox([item for _index, item in consumed])
if _anchor_bbox_in_reference_region(
bbox, anchor=anchor, page_width=page_width, page_height=page_height,
):
matches.append((bbox, [index for index, _item in consumed]))
start = position + max(len(label), 1)
unique: dict[tuple[float, float, float, float], tuple[LayoutBBox, list[int]]] = {}
for bbox, indices in matches:
unique[(bbox.x0, bbox.y0, bbox.x1, bbox.y1)] = (bbox, indices)
return list(unique.values())
def _anchor_occurrence_is_exact(
row: list[tuple[int, dict[str, Any]]], *, position: int, length: int, anchor: AnchorRule,
) -> bool:
"""精确模式拒绝嵌入其他字母数字串的标签,contains 模式才允许局部命中。"""
if anchor.match_mode != 'exact':
return True
before = row[position - 1][1] if position else None
first = row[position][1]
last = row[position + length - 1][1]
after = row[position + length][1] if position + length < len(row) else None
return not (
(before is not None and str(before.get('text') or '').isalnum() and not _glyph_gap_is_word_boundary(before, first))
or (after is not None and str(after.get('text') or '').isalnum() and not _glyph_gap_is_word_boundary(last, after))
)
def _glyph_gap_is_word_boundary(left: dict[str, Any], right: dict[str, Any]) -> bool:
"""PDFium 常省略空白 glyph;相邻字符间的大间隔仍视为精确标签的词边界。"""
left_bbox, right_bbox = _glyph_bbox(left), _glyph_bbox(right)
typical_width = max(((left_bbox.x1 - left_bbox.x0) + (right_bbox.x1 - right_bbox.x0)) / 2, 0.01)
return right_bbox.x0 - left_bbox.x1 > typical_width * 0.75
def _anchor_bbox_in_reference_region(
bbox: LayoutBBox, *, anchor: AnchorRule, page_width: float | None, page_height: float | None,
) -> bool:
"""锚点配置了参考区时只接受该页相对位置内的命中,避免页眉重复标签干扰。"""
if anchor.region is None:
return True
if page_width is None or page_height is None or page_width <= 0 or page_height <= 0:
return False
region = _absolute_relative_region(anchor.region, width=page_width, height=page_height)
return _glyph_center_inside({'bbox': bbox.model_dump(mode='json')}, region)
def _anchor_from_reference_region(
glyphs: list[dict[str, Any]], *, anchor: AnchorRule, page_width: float, page_height: float,
) -> LayoutBBox | None:
"""为历史占位标签保留参考框内的实际标签几何,且调用方必须降级为人工复核。"""
if anchor.region is None:
return None
region = _absolute_relative_region(anchor.region, width=page_width, height=page_height)
selected = [glyph for glyph in glyphs if _glyph_center_inside(glyph, region)]
return _union_bbox(selected) if selected else None
def _is_placeholder_anchor_text(value: str) -> bool:
"""仅兼容工作台历史默认名;任何管理员自定义标签不匹配时仍必须失败关闭。"""
return re.fullmatch(r'订单字段标签\s*\d*', value.strip()) is not None
def _stop_before_anchor(
selected: list[tuple[int, dict[str, Any]]], *, glyphs: list[dict[str, Any]], stop_anchors: list[AnchorRule],
anchor_bbox: LayoutBBox | None,
) -> list[tuple[int, dict[str, Any]]]:
"""多行值仅在当前锚点之后遇到首个停止标签时截断,避免页眉同名标签误伤。"""
stop_y: float | None = None
for anchor in stop_anchors:
for bbox, _indices in _find_anchor_matches(glyphs, anchor):
if anchor_bbox is not None and bbox.y0 <= anchor_bbox.y1:
continue
stop_y = bbox.y0 if stop_y is None else min(stop_y, bbox.y0)
return selected if stop_y is None else [item for item in selected if _glyph_bbox(item[1]).y0 < stop_y]
def _render_value(selected: list[tuple[int, dict[str, Any]]], *, multi_line: bool) -> str:
"""按 y 聚类、x 排序渲染字符,保留多行字段的换行而不伪造空格。"""
rows = _visual_rows(selected)
rendered = [_render_visual_row(row) for row in rows]
return ('\n' if multi_line else ' ').join(item for item in rendered if item).strip()
def _render_visual_row(row: list[tuple[int, dict[str, Any]]]) -> str:
"""以字距推断缺失的 PDF 空白;仅大于常规字符间隔时补一个普通空格。"""
rendered: list[str] = []
previous: LayoutBBox | None = None
for _index, glyph in row:
bbox = _glyph_bbox(glyph)
if previous is not None:
typical_width = max((previous.x1 - previous.x0 + bbox.x1 - bbox.x0) / 2, 0.01)
if bbox.x0 - previous.x1 > typical_width * 0.75:
rendered.append(' ')
rendered.append(str(glyph.get('text') or ''))
previous = bbox
return ''.join(rendered).strip()
def _visual_rows(items: list[tuple[int, dict[str, Any]]]) -> list[list[tuple[int, dict[str, Any]]]]:
"""将 bbox 中心 y 接近的字符归为视觉行,避免扫描页的微小坐标抖动拆行。"""
rows: list[list[tuple[int, dict[str, Any]]]] = []
for item in sorted(items, key=lambda pair: (_glyph_bbox(pair[1]).y0, _glyph_bbox(pair[1]).x0)):
bbox = _glyph_bbox(item[1])
if rows:
previous = rows[-1]
reference = _glyph_bbox(previous[0][1])
tolerance = max((reference.y1 - reference.y0), (bbox.y1 - bbox.y0)) * 0.55
if abs(((bbox.y0 + bbox.y1) / 2) - ((reference.y0 + reference.y1) / 2)) <= tolerance:
previous.append(item)
continue
rows.append([item])
return [sorted(row, key=lambda pair: _glyph_bbox(pair[1]).x0) for row in rows]
def _layout_applies_to_page(layout: OrderFieldLayout, page_no: int) -> bool:
"""执行订单字段页域;后续页重复值只在 all_pages 明确声明时作为冲突证据读取。"""
return (
(layout.page_scope == 'first_page' and page_no == 1)
or layout.page_scope == 'all_pages'
or (layout.page_scope == 'exact_page' and page_no == layout.page_no)
)
def _source_allowed(layout: OrderFieldLayout, *, config: dict[str, Any], source: str) -> bool:
"""同时满足布局和 Schema 的坐标来源授权,OCR 永远不提升为 confirmed。"""
allowed = set(config.get('allowed_sources') or [])
if source not in allowed:
return False
required_levels = [layout.minimum_evidence_level]
if layout.anchor is not None:
required_levels.append(layout.anchor.minimum_evidence_level)
return not ('coordinate' in required_levels and source != 'pdf_coordinate')
def _absolute_relative_region(region: RelativeRegion | None, *, width: float, height: float) -> LayoutBBox:
"""将固定低可靠度归一化页区投影为当前页面绝对框。"""
if region is None:
raise ValueError('fallback order field region is required')
return LayoutBBox(x0=region.x0 * width, y0=region.y0 * height, x1=region.x1 * width, y1=region.y1 * height)
def _absolute_anchor_region(region: AnchorRelativeRegion | None, anchor: LayoutBBox) -> LayoutBBox:
"""用标签框宽高投影相对值区,使整页平移或缩放不改变读取关系。"""
if region is None:
raise ValueError('anchored order field region is required')
width, height = anchor.x1 - anchor.x0, anchor.y1 - anchor.y0
return LayoutBBox(
x0=anchor.x0 + region.x0 * width, y0=anchor.y0 + region.y0 * height,
x1=anchor.x0 + region.x1 * width, y1=anchor.y0 + region.y1 * height,
)
def _glyph_bbox(glyph: dict[str, Any]) -> LayoutBBox:
"""严格解析一枚冻结 glyph 的 bbox;坏坐标不会被修正后参与提取。"""
return LayoutBBox.model_validate(glyph.get('bbox'))
def _glyph_center_inside(glyph: dict[str, Any], region: LayoutBBox) -> bool:
"""判断字符中心是否处于值区,边界字符仍归属到管理员确认的区域。"""
try:
bbox = _glyph_bbox(glyph)
except Exception:
return False
return region.x0 <= (bbox.x0 + bbox.x1) / 2 <= region.x1 and region.y0 <= (bbox.y0 + bbox.y1) / 2 <= region.y1
def _union_bbox(glyphs: list[dict[str, Any]]) -> LayoutBBox:
"""求连续标签字符的最小联合框,作为相对值区投影的唯一参考。"""
boxes = [_glyph_bbox(item) for item in glyphs]
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 _unavailable(
layout: OrderFieldLayout, issue: str, *, page_no: int | None = None, source: str | None = None,
anchor_bbox: LayoutBBox | None = None, value_bbox: LayoutBBox | None = None,
) -> OrderFieldExtraction:
"""构造无可用坐标证据的失败关闭结果。"""
return OrderFieldExtraction(field_id=layout.field_id, field_code=layout.field_code, status='unavailable', source=source, page_no=page_no, anchor_bbox=anchor_bbox, value_bbox=value_bbox, issues=[issue])
def _review(
layout: OrderFieldLayout, issue: str, page_no: int, source: str, anchor_bbox: LayoutBBox | None,
value_bbox: LayoutBBox, selected: list[tuple[int, dict[str, Any]]],
) -> OrderFieldExtraction:
"""构造带最小证据索引的人工复核候选。"""
return OrderFieldExtraction(
field_id=layout.field_id, field_code=layout.field_code, status='needs_review', source=source,
page_no=page_no, anchor_bbox=anchor_bbox, value_bbox=value_bbox,
glyph_indices=[index for index, _item in selected], issues=[issue],
)
@@ -62,15 +62,82 @@ class RelativeRegion(OrderProfileModel):
return self
class AnchorRelativeRegion(OrderProfileModel):
"""表示相对锚点框宽高的值区偏移;允许标签右侧或下方落在锚点外。"""
# Address values can be much wider than short labels such as "BILL TO".
# Keep a finite bound while accepting the deterministic suggestion geometry.
x0: float = Field(ge=-12, le=12)
y0: float = Field(ge=-12, le=12)
x1: float = Field(ge=-12, le=12)
y1: float = Field(ge=-12, le=12)
@model_validator(mode='after')
def validate_area(self) -> 'AnchorRelativeRegion':
"""拒绝零面积和反向偏移区域,确保运行期投影只有一个解释。"""
if self.x0 >= self.x1 or self.y0 >= self.y1:
raise ValueError('anchor-relative region must have positive area')
return self
class AnchorRule(OrderProfileModel):
"""定义模板匹配或行启动使用的稳定静态文字锚点。"""
anchor_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
text: str = Field(min_length=1, max_length=160)
aliases: list[str] = Field(default_factory=list, max_length=16)
match_mode: Literal['exact', 'contains'] = 'contains'
region: RelativeRegion | None = None
minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate'
@model_validator(mode='after')
def validate_aliases(self) -> 'AnchorRule':
"""只接受有限、去重的精确别名,避免把模糊词表当作自由匹配规则。"""
aliases = [item.strip() for item in self.aliases]
if any(not item for item in aliases) or len({item.casefold() for item in aliases}) != len(aliases):
raise ValueError('anchor aliases must be non-empty and unique')
if self.text.casefold() in {item.casefold() for item in aliases}:
raise ValueError('anchor aliases must not repeat anchor text')
return self
class OrderFieldLayout(OrderProfileModel):
"""定义独立订单级字段的锚点和值区;它绝不属于表头或物理明细行。"""
layout_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
field_id: str = Field(min_length=1, max_length=128)
field_code: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
page_scope: Literal['first_page', 'all_pages', 'exact_page'] = 'first_page'
page_no: int | None = Field(default=None, ge=1)
anchor: AnchorRule | None = None
# Anchored values use offsets relative to the anchor bbox; fixed-position
# fallback values are stored separately so they cannot be mistaken for anchors.
value_region: AnchorRelativeRegion | None = None
fallback_value_region: RelativeRegion | None = None
value_mode: Literal['single_line', 'multi_line', 'right_of_anchor', 'below_anchor'] = 'single_line'
stop_anchors: list[AnchorRule] = Field(default_factory=list)
normalizer_key: str | None = Field(default=None, min_length=1, max_length=64)
required: bool = False
minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate'
@model_validator(mode='after')
def validate_order_field_layout(self) -> 'OrderFieldLayout':
"""限制无锚点回退为单页值区,并要求多行字段有明确停止证据。"""
if self.page_scope == 'exact_page' and self.page_no is None:
raise ValueError('exact_page order field requires page_no')
if self.page_scope != 'exact_page' and self.page_no is not None:
raise ValueError('page_no is only allowed for exact_page order field')
if self.anchor is None:
if self.page_scope == 'all_pages':
raise ValueError('value-only order field must have a bounded page scope')
if self.value_region is not None or self.fallback_value_region is None:
raise ValueError('value-only order field requires one fallback value region')
elif self.value_region is None or self.fallback_value_region is not None:
raise ValueError('anchored order field requires one anchor-relative value region')
if self.value_mode == 'multi_line' and not self.stop_anchors:
raise ValueError('multi-line order field requires stop anchors')
return self
class FieldRegion(OrderProfileModel):
"""将一个管理员确认的坐标区域绑定至稳定 Schema field_code。"""
@@ -141,12 +208,40 @@ class TerminationRule(OrderProfileModel):
class DraftUnboundFieldRegion(OrderProfileModel):
"""草稿阶段尚未绑定 Schema 的字段框;运行和发布均不得使用。"""
"""草稿阶段尚未绑定 Schema 的字段框;仅迁移遗留项要求重新绑定。"""
region_id: str = Field(pattern=r'^[a-z][a-z0-9_-]{0,95}$')
parent_layout_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
label: str = Field(min_length=1, max_length=160)
region: RelativeRegion
requires_rebinding: bool = False
class DraftUnboundOrderFieldLayout(OrderProfileModel):
"""Schema 迁移后暂失绑定的订单字段区域;保留证据布局但禁止发布或运行。"""
layout_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
label: str = Field(min_length=1, max_length=160)
page_scope: Literal['first_page', 'all_pages', 'exact_page'] = 'first_page'
page_no: int | None = Field(default=None, ge=1)
anchor: AnchorRule | None = None
value_region: AnchorRelativeRegion | None = None
fallback_value_region: RelativeRegion | None = None
value_mode: Literal['single_line', 'multi_line', 'right_of_anchor', 'below_anchor'] = 'single_line'
stop_anchors: list[AnchorRule] = Field(default_factory=list)
minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate'
@model_validator(mode='after')
def validate_unbound_order_field_layout(self) -> 'DraftUnboundOrderFieldLayout':
"""复用订单字段的区域互斥与页作用域规则,避免迁移草稿保存坏坐标。"""
OrderFieldLayout(
layout_id=self.layout_id, field_id='draft_unbound', field_code='draft_unbound',
page_scope=self.page_scope, page_no=self.page_no, anchor=self.anchor,
value_region=self.value_region, fallback_value_region=self.fallback_value_region,
value_mode=self.value_mode, stop_anchors=self.stop_anchors,
minimum_evidence_level=self.minimum_evidence_level,
)
return self
class TableRegionProfile(OrderProfileModel):
@@ -230,6 +325,8 @@ class OrderCoordinateProfileV2(OrderProfileModel):
version: int = Field(ge=1)
document_match: DocumentMatchProfile
table_regions: list[TableRegionProfile] = Field(min_length=1)
order_field_layouts: list[OrderFieldLayout] = Field(default_factory=list)
draft_unbound_order_field_layouts: list[DraftUnboundOrderFieldLayout] = Field(default_factory=list)
@model_validator(mode='after')
def validate_profile_rules(self) -> 'OrderCoordinateProfileV2':
@@ -246,6 +343,15 @@ class OrderCoordinateProfileV2(OrderProfileModel):
for table in self.table_regions:
if not set(table.continuation_rule.required_anchor_ids).issubset(anchor_ids):
raise ValueError('cross-page continuation anchor must be a document match anchor')
order_layout_ids = [item.layout_id for item in self.order_field_layouts]
if len(order_layout_ids) != len(set(order_layout_ids)):
raise ValueError('order field layout ids must be unique')
order_field_codes = [item.field_code for item in self.order_field_layouts]
if len(order_field_codes) != len(set(order_field_codes)):
raise ValueError('order field may bind only once')
unbound_ids = [item.layout_id for item in self.draft_unbound_order_field_layouts]
if len(unbound_ids) != len(set(unbound_ids)) or set(unbound_ids) & set(order_layout_ids):
raise ValueError('bound and unbound order field layout ids must be unique')
return self
@@ -45,6 +45,7 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout:
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
if not tables or not pages or not glyph_tables:
return ProfileMatchResult(status='evidence_insufficient')
@@ -57,6 +58,7 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout:
profile = OrderCoordinateProfileV2(
profile_code=str(raw.get('profile_code') or ''), version=int(raw.get('version') or 0),
document_match=definition.get('document_match'), table_regions=definition.get('table_regions'),
order_field_layouts=definition.get('order_field_layouts') or [],
)
except (TypeError, ValueError):
continue
@@ -64,11 +66,15 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout:
if len(tables) < len(profile.table_regions):
reasons.append('table_region_count_insufficient')
required = profile.document_match.required_anchors
required_hits = [_anchor_present(anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, pages=pages) for anchor in required]
required_hits = [_anchor_present(
anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
) for anchor in required]
if not all(required_hits):
reasons.append('required_anchor_missing')
optional = profile.document_match.optional_anchors
optional_hits = sum(_anchor_present(anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, pages=pages) for anchor in optional)
optional_hits = sum(_anchor_present(
anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
) for anchor in optional)
hard_match = not reasons
# Required evidence is mandatory rather than a soft score. Optional evidence only separates already valid templates.
score = 1.0 if not optional else 0.8 + 0.2 * optional_hits / len(optional)
@@ -92,14 +98,26 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout:
)
def _anchor_present(anchor: dict[str, Any], *, tables: list[dict[str, Any]], glyph_tables: dict[str, Any], pages: dict[str, Any]) -> bool:
"""检查静态锚点是否在指定页面区域出现;不读取订单业务字段或 HTML 网格。"""
def _anchor_present(
anchor: dict[str, Any], *, tables: list[dict[str, Any]], glyph_tables: dict[str, Any],
page_glyphs: dict[str, Any], pages: dict[str, Any],
) -> bool:
"""检查静态锚点是否在整页冻结字符中出现;旧快照才受限回退到表内证据。"""
expected = str(anchor.get('text') or '').strip()
if not expected:
candidates = [expected, *[str(item).strip() for item in anchor.get('aliases') or []]]
if not expected or not all(candidates):
return False
for table in tables:
glyphs = glyph_tables.get(str(table.get('table_id') or ''))
page = pages.get(str(table.get('page_no') or ''))
page_numbers = sorted({str(item.get('page_no') or '') for item in tables if item.get('page_no')})
for page_no in page_numbers:
glyphs = page_glyphs.get(page_no)
# v1 frozen snapshots do not have page glyphs. Preserve historical matching
# rather than silently invalidating published profiles, but never merge rows here.
if not isinstance(glyphs, list):
glyphs = [
glyph for table in tables if str(table.get('page_no') or '') == page_no
for glyph in (glyph_tables.get(str(table.get('table_id') or '')) or [])
]
page = pages.get(page_no)
if not isinstance(glyphs, list) or not isinstance(page, dict):
continue
selected = glyphs
@@ -115,8 +133,8 @@ def _anchor_present(anchor: dict[str, Any], *, tables: list[dict[str, Any]], gly
and y0 <= (float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 <= y1]
text = ''.join(str(item.get('text') or '') for item in sorted(selected, key=lambda item: (item.get('bbox', {}).get('y0', 0), item.get('bbox', {}).get('x0', 0))))
if str(anchor.get('match_mode') or 'contains') == 'exact':
if expected.casefold() == text.casefold():
if any(candidate.casefold() == text.casefold() for candidate in candidates):
return True
elif expected.casefold() in text.casefold():
elif any(candidate.casefold() in text.casefold() for candidate in candidates):
return True
return False
@@ -175,7 +175,7 @@ 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,
)
@@ -187,7 +187,7 @@ def build_mineru_table_snapshot(
def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]]) -> dict[str, Any]:
"""保存表内字符和内部页尺寸,使 v2 页面相对坐标可在冻结 Run 中精确换算。"""
"""保存表内及整页原生字符和页尺寸,分别供明细与订单级字段确定性重放。"""
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)}
@@ -211,9 +211,34 @@ def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]])
glyphs.append(item.model_dump(mode='json'))
if glyphs:
evidence[table_id] = glyphs
page_glyphs: dict[str, list[dict[str, Any]]] = {}
page_sources: dict[str, str] = {}
for page_no, page in pages.items():
native_glyphs = [item.model_dump(mode='json') for item in page.characters]
if native_glyphs:
page_glyphs[str(page_no)] = native_glyphs
page_sources[str(page_no)] = 'pdf_coordinate'
continue
# Only scanned pages without a usable native text layer trigger OCR. OCR failure
# intentionally leaves this page without order-field evidence rather than guessing.
try:
from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines
ocr_lines = extract_ocr_lines(page.image, page_width=page.width, page_height=page.height)
ocr_glyphs = _ocr_page_characters(ocr_lines)
except Exception:
ocr_glyphs = []
if ocr_glyphs:
page_glyphs[str(page_no)] = ocr_glyphs
page_sources[str(page_no)] = 'ocr_coordinate'
return {
'version': 'shipping_order_coordinate_evidence.v1',
'tables': evidence,
# 订单字段锚点可能位于表格外;只保存同一冻结 PDF 的最小字符证据,不向 Dify 暴露。
'page_glyphs': page_glyphs,
'sources': {
'pages': page_sources,
},
# Internal runtime metadata only. It is removed with layout_snapshot before Dify input.
'pages': {
str(page_no): {'width': page.width, 'height': page.height}
@@ -222,6 +247,29 @@ def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]])
}
def _ocr_page_characters(lines: list[Any]) -> list[dict[str, Any]]:
"""把整页 OCR 行均匀拆成字符证据;仅服务订单字段锚点,不参与表格 cell 自动接受。"""
result: list[dict[str, Any]] = []
source_index = 0
for line in lines:
text = str(getattr(line, 'text', '') or '').strip()
bbox = getattr(line, 'bbox', None)
if not text or bbox is None:
continue
width = (bbox.x1 - bbox.x0) / len(text)
if width <= 0:
continue
for index, character in enumerate(text):
if character.isspace():
continue
result.append({'text': character, 'source_index': source_index, 'bbox': {
'x0': bbox.x0 + index * width, 'y0': bbox.y0,
'x1': bbox.x0 + (index + 1) * width, 'y1': bbox.y1,
}})
source_index += 1
return result
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 {}
@@ -3,12 +3,13 @@ services/shipping_notice/document_profile_quality_service.py
用途:治理订单文档 Profile 的盲测样本、执行结果和确定性自动建单资格。
依赖:Profile 服务、MinerU 当前布局快照、Profile 纯解析器与质量 ORM 模型。
逻辑:管理员先固化独立样本的期望行,服务按冻结 Profile 执行比对;至少三份样本全部通过并批准后才放行自动建单。
逻辑:管理员先固化一份独立样本的期望行,服务按冻结 Profile 执行比对;样本通过并批准后才放行自动建单。
"""
from __future__ import annotations
from datetime import datetime
from decimal import Decimal
from typing import Any
from app import db
@@ -18,7 +19,9 @@ from app.models import (
ShippingDocumentProfileTestSample,
ShippingDocumentProfileTestSuite,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingOrderDocumentProfile,
ShippingOrderDocumentProfileSample,
)
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
@@ -28,12 +31,20 @@ from app.services.shipping_notice.document_layout.order_profile import (
reconstruct_order_profile_html,
)
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import reconstruct_coordinate_profile_rows
from app.services.shipping_notice.order_document_profile_service import _audit, _definition_contract
from app.services.shipping_notice.document_layout.order_field_extraction import (
_is_placeholder_anchor_text, extract_order_fields,
)
from app.services.shipping_notice.order_document_profile_service import (
_audit, _definition_contract, _ensure_page_coordinate_evidence,
)
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value
MINIMUM_BLIND_SAMPLES = 3
HEADERLESS_MINIMUM_BLIND_SAMPLES = 5
# 日常模板维护采用一份独立样本门槛;字段 confirmed、人工真值一致、
# 多明细和声明的跨页覆盖等质量门禁仍然生效。
MINIMUM_BLIND_SAMPLES = 1
HEADERLESS_MINIMUM_BLIND_SAMPLES = 1
def _quality_checksum(profile: ShippingOrderDocumentProfile) -> str:
@@ -101,6 +112,76 @@ def _coordinate_table_available(document_id: int, table_id: str) -> bool:
)
def _ensure_order_field_evidence(
*, document: ShippingNoticeDocument, layout: dict[str, Any], parser: OrderCoordinateProfileV2,
) -> dict[str, Any]:
"""补齐模板订单字段涉及页面的整页字符坐标;表内坐标不能替代锚点证据。"""
required_pages: set[int] = set()
pages = (layout.get('coordinate_evidence') or {}).get('pages') if isinstance(layout.get('coordinate_evidence'), dict) else {}
known_pages = {int(page_no) for page_no in (pages or {}) if str(page_no).isdigit()}
for field in parser.order_field_layouts:
if field.page_scope == 'exact_page' and field.page_no:
required_pages.add(field.page_no)
elif field.page_scope == 'first_page':
required_pages.add(1)
else:
required_pages.update(known_pages)
for page_no in sorted(required_pages):
layout = _ensure_page_coordinate_evidence(document=document, layout=layout, page_no=page_no)
return layout
def _has_matching_key_order_field(
*, parser: OrderCoordinateProfileV2, schema_fields: dict[str, dict[str, Any]], layout: dict[str, Any],
) -> bool:
"""筛除没有任何真实订单锚点命中的异版样本,避免盲测页面只展示 unavailable。"""
key_layouts = [
item for item in parser.order_field_layouts
if item.anchor is not None and not _is_placeholder_anchor_text(item.anchor.text)
]
if not key_layouts:
# Historical templates that only have manually named anchors retain the
# existing compatibility path; their evidence remains needs_review.
return True
extracted = {
item.field_code: item
for item in extract_order_fields(
profile=parser, schema_fields=schema_fields,
coordinate_evidence=layout.get('coordinate_evidence') or {},
)
}
return any(
extracted.get(item.field_code) is not None
and extracted[item.field_code].status != 'unavailable'
for item in key_layouts
)
def _order_field_quality_failures(
*, parser: OrderCoordinateProfileV2, schema_fields: dict[str, dict[str, Any]], layout: dict[str, Any],
expected_values: dict[str, Any], sample_id: int,
) -> list[str]:
"""将订单字段的坐标/格式状态纳入盲测;任何非 confirmed 结果都不能成为发布依据。"""
if not parser.order_field_layouts:
return []
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
failures: list[str] = []
for candidate in extract_order_fields(
profile=parser, schema_fields=schema_fields, coordinate_evidence=evidence,
):
if candidate.status != 'confirmed':
failures.append(f'sample:{sample_id}:order_field:{candidate.field_code}:{candidate.status}')
else:
config = schema_fields.get(candidate.field_id)
try:
expected = normalize_order_field_value(expected_values.get(candidate.field_code), config or {})
except Exception:
expected = None
if candidate.value != expected:
failures.append(f'sample:{sample_id}:order_field:{candidate.field_code}:mismatch')
return failures
def _expected_rows(raw: Any) -> list[dict[str, Any]]:
"""校验人工录入的盲测真值,只接受行字段字典且不允许空集合。"""
if not isinstance(raw, list) or not raw or any(not isinstance(item, dict) or not item for item in raw):
@@ -108,24 +189,219 @@ def _expected_rows(raw: Any) -> list[dict[str, Any]]:
return [dict(item) for item in raw]
def _expected_order_fields(raw: Any, *, parser: Any) -> dict[str, Any]:
"""校验订单字段盲测真值;有订单布局时要求按 stable field_code 提供完整映射。"""
layouts = parser.order_field_layouts if isinstance(parser, OrderCoordinateProfileV2) else []
if not layouts:
return {}
if not isinstance(raw, dict):
raise ValidationError('expected_order_fields is required for order field layouts', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
expected_codes = {item.field_code for item in layouts}
if set(raw) != expected_codes or any(value in (None, '') for value in raw.values()):
raise ValidationError('expected_order_fields must contain every configured order field', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
return dict(raw)
def _candidate_for_sample(
*, profile: ShippingOrderDocumentProfile, document_id: int, table_id: str,
) -> dict[str, Any]:
"""运行当前 Profile 并返回供盲测复核的脱敏字段候选,不写入任何真值或执行记录。"""
parser = _definition_contract(profile)
document = db.session.get(ShippingNoticeDocument, int(document_id))
layout = current_layout_snapshot(document) if document is not None else None
if document is None or not layout:
raise NotFoundError('Order document test sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
if isinstance(parser, OrderCoordinateProfileV2):
layout = _ensure_order_field_evidence(document=document, layout=layout, parser=parser)
if not _coordinate_table_available(document_id, table_id):
raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
schema_fields = {
str(item.get('field_id') or ''): item
for item in (profile.schema_version.definition_json or {}).get('fields') or []
if isinstance(item, dict) and item.get('enabled', True)
}
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
raw_table = next((
item for item in layout.get('tables') or []
if isinstance(item, dict) and str(item.get('table_id') or '') == str(table_id)
), None)
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
page = pages.get(str((raw_table or {}).get('page_no') or ''))
characters = (evidence.get('tables') or {}).get(str(table_id))
if not isinstance(raw_table, dict) or not isinstance(page, dict) or not isinstance(characters, list):
raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
try:
table_bbox = {'x0': 0, 'y0': 0, 'x1': float(page['width']), 'y1': float(page['height'])}
except (KeyError, TypeError, ValueError) as exc:
raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') from exc
rows: list[dict[str, Any]] = []
for region in parser.table_regions:
# Header-only pages can carry order fields without a physical line
# layout. They are valid template regions, but cannot reconstruct rows.
if not region.line_layouts:
continue
rows.extend(item.fields for item in reconstruct_coordinate_profile_rows(
characters=[item for item in characters if isinstance(item, dict)], table_bbox=table_bbox,
line_layouts=[item.model_dump() for item in region.line_layouts], table_region=region.region.model_dump(),
termination_rules=[item.model_dump() for item in region.termination_rules],
exclusion_regions=[item.model_dump() for item in region.exclusion_regions],
) if not item.issues)
order_fields = [
{
'field_code': item.field_code, 'value': _json_value(item.value), 'status': item.status,
'page_no': item.page_no, 'issues': list(item.issues),
}
for item in extract_order_fields(profile=parser, schema_fields=schema_fields, coordinate_evidence=evidence)
]
return {'document_id': document.id, 'table_id': str(table_id), 'rows': rows, 'order_fields': order_fields}
contract = compile_table_header_contract(profile.schema_version.definition_json or {})
parsed = parse_html_table_with_order_profile(_table_html(document.id, table_id), table_id=table_id, profile=parser, contract=contract)
return {
'document_id': document.id, 'table_id': str(table_id),
'rows': [dict(row.fields) for row in parsed.rows if row.status == 'parsed'], 'order_fields': [],
}
def _json_value(value: Any) -> Any:
"""将日期和 Decimal 等运行期字段转换为 API/JSON 可展示的稳定值。"""
if isinstance(value, Decimal):
return str(value)
return value.isoformat() if hasattr(value, 'isoformat') else value
def list_independent_samples(*, suite_id: int, actor_id: int) -> dict[str, Any]:
"""列出可用于当前盲测的同类专用订单,严格排除建模和已加入盲测的文档。"""
suite = db.session.get(ShippingDocumentProfileTestSuite, int(suite_id))
if suite is None:
raise NotFoundError('Order document profile test suite not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_FOUND')
profile = _profile(suite.profile_id)
parser = _definition_contract(profile)
schema_fields = {
str(item.get('field_id') or ''): item
for item in (profile.schema_version.definition_json or {}).get('fields') or []
if isinstance(item, dict) and item.get('enabled', True)
}
excluded = {
item.document_id for item in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).all()
} | {item.document_id for item in suite.samples}
result: list[dict[str, Any]] = []
documents = ShippingNoticeDocument.query.join(
ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingNoticeDocument.intake_id,
).filter(
ShippingNoticeIntake.purpose == 'order_document_profile_sample',
).order_by(ShippingNoticeDocument.created_at.desc()).limit(200).all()
for document in documents:
if document.id in excluded:
continue
layout = current_layout_snapshot(document) or {}
if isinstance(parser, OrderCoordinateProfileV2):
layout = _ensure_order_field_evidence(document=document, layout=layout, parser=parser)
if not _has_matching_key_order_field(parser=parser, schema_fields=schema_fields, layout=layout):
continue
tables = layout.get('tables') if isinstance(layout.get('tables'), list) else []
if layout.get('status') != 'ready' or not tables:
continue
for table in tables:
if not isinstance(table, dict) or not str(table.get('table_id') or ''):
continue
if isinstance(parser, OrderCoordinateProfileV2) and not _coordinate_table_available(document.id, str(table['table_id'])):
continue
result.append({
'document_id': document.id, 'table_id': str(table['table_id']),
'page_no': int(table.get('page_no') or 1), 'filename': document.filename or '',
})
return {'samples': result}
def preview_independent_sample(*, suite_id: int, document_id: int, table_id: str, actor_id: int) -> dict[str, Any]:
"""读取一份可用独立样本的自动候选;复核确认前不写入盲测真值。"""
suite = db.session.get(ShippingDocumentProfileTestSuite, int(suite_id))
if suite is None or suite.status != 'draft':
raise ConflictError('Blind test suite is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_IMMUTABLE')
available = {
(item['document_id'], item['table_id'])
for item in list_independent_samples(suite_id=suite.id, actor_id=actor_id)['samples']
}
if (int(document_id), str(table_id)) not in available:
raise ConflictError('Blind test sample must be independent of modelling samples', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_NOT_INDEPENDENT')
return _candidate_for_sample(profile=_profile(suite.profile_id), document_id=int(document_id), table_id=str(table_id))
def confirm_sample_reviews(*, suite_id: int, document_id: int, table_id: str, row_reviews: Any, order_field_reviews: Any, actor_id: int) -> dict[str, Any]:
"""把逐项正确/错误复核转换为既有盲测真值;未确认或错误未修正时拒绝写入。"""
candidate = preview_independent_sample(
suite_id=suite_id, document_id=document_id, table_id=table_id, actor_id=actor_id,
)
if not isinstance(row_reviews, list) or len(row_reviews) != len(candidate['rows']):
raise ValidationError('Every candidate row requires a review', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
expected_rows: list[dict[str, Any]] = []
for index, review in enumerate(row_reviews):
if not isinstance(review, dict) or review.get('correct') not in {True, False}:
raise ValidationError('Every candidate row requires a review', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
values = candidate['rows'][index] if review['correct'] else review.get('values')
if not isinstance(values, dict) or not values:
raise ValidationError('Incorrect row requires corrected values', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
expected_rows.append(dict(values))
expected_order_fields: dict[str, Any] = {}
for field in candidate['order_fields']:
review = order_field_reviews.get(field['field_code']) if isinstance(order_field_reviews, dict) else None
if not isinstance(review, dict) or review.get('correct') not in {True, False}:
raise ValidationError('Every order field requires a review', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
value = field['value'] if review['correct'] else review.get('value')
if value in (None, ''):
raise ValidationError('Incorrect order field requires a corrected value', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
expected_order_fields[field['field_code']] = value
return add_sample(
suite_id=suite_id, document_id=document_id, table_id=table_id, expected_rows=expected_rows,
expected_order_fields=expected_order_fields, actor_id=actor_id,
)
def create_suite(*, profile_id: int, actor_id: int) -> dict[str, Any]:
"""为草稿或发布 Profile 建立唯一盲测集;发布前完成审批以形成真正发布门禁。"""
"""为当前 Profile checksum 建立独立盲测集,并将过期草稿集转为 superseded。
核心逻辑:模板保存会改变草稿 definition hash,旧盲测真值不能为新定义背书。
同一模板因此按 checksum 保留历史集;再次打开盲测时只返回当前定义对应的集。
Args:
profile_id: 草稿或发布 Profile 主键。
actor_id: 管理员主键,用于写入创建/过期审计。
Returns:
当前 Profile checksum 对应的可维护盲测集摘要。
"""
profile = _profile(profile_id)
existing = ShippingDocumentProfileTestSuite.query.filter_by(profile_id=profile.id).first()
checksum = _quality_checksum(profile)
existing = ShippingDocumentProfileTestSuite.query.filter_by(
profile_id=profile.id, profile_checksum=checksum,
).one_or_none()
if existing is not None:
return serialize_suite(existing)
stale_suites = ShippingDocumentProfileTestSuite.query.filter(
ShippingDocumentProfileTestSuite.profile_id == profile.id,
ShippingDocumentProfileTestSuite.status == 'draft',
ShippingDocumentProfileTestSuite.profile_checksum != checksum,
).all()
for stale in stale_suites:
stale.status = 'superseded'
_audit(profile_id=profile.id, event_type='blind_test_suite_superseded', actor_id=actor_id, detail={
'suite_id': stale.id,
})
suite = ShippingDocumentProfileTestSuite(
profile_id=profile.id, profile_checksum=_quality_checksum(profile), created_by_id=actor_id,
profile_id=profile.id, profile_checksum=checksum, created_by_id=actor_id,
)
db.session.add(suite)
_audit(profile_id=profile.id, event_type='blind_test_suite_created', actor_id=actor_id, detail={
'profile_checksum': _quality_checksum(profile),
'profile_checksum': checksum,
})
db.session.commit()
return serialize_suite(suite)
def add_sample(*, suite_id: int, document_id: int, table_id: str, expected_rows: Any, actor_id: int) -> dict[str, Any]:
def add_sample(
*, suite_id: int, document_id: int, table_id: str, expected_rows: Any,
expected_order_fields: Any = None, actor_id: int,
) -> dict[str, Any]:
"""增加独立盲测样本;批准后禁止继续更改真值。"""
suite = db.session.get(ShippingDocumentProfileTestSuite, int(suite_id))
if suite is None:
@@ -144,7 +420,9 @@ def add_sample(*, suite_id: int, document_id: int, table_id: str, expected_rows:
_table_html(document_id, table_id)
sample = ShippingDocumentProfileTestSample(
suite_id=suite.id, document_id=int(document_id), table_id=str(table_id),
expected_rows_json=_expected_rows(expected_rows), created_by_id=actor_id,
expected_rows_json=_expected_rows(expected_rows),
expected_order_fields_json=_expected_order_fields(expected_order_fields, parser=parser),
created_by_id=actor_id,
)
db.session.add(sample)
try:
@@ -189,12 +467,24 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
raise ConflictError('Profile changed after test suite creation', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_STALE')
contract = compile_table_header_contract(profile.schema_version.definition_json or {})
parser = _definition_contract(profile)
schema_fields = {
str(item.get('field_id') or ''): item
for item in (profile.schema_version.definition_json or {}).get('fields') or []
if isinstance(item, dict) and item.get('enabled', True)
}
failures: list[str] = []
passed = 0
for sample in suite.samples:
document = db.session.get(ShippingNoticeDocument, sample.document_id)
layout = current_layout_snapshot(document) if document is not None else None
if isinstance(parser, OrderCoordinateProfileV2):
field_failures = _order_field_quality_failures(
parser=parser, schema_fields=schema_fields, layout=layout or {},
expected_values=dict(sample.expected_order_fields_json or {}), sample_id=sample.id,
)
if field_failures:
failures.extend(field_failures)
continue
evidence = (layout or {}).get('coordinate_evidence') if isinstance((layout or {}).get('coordinate_evidence'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
characters = (evidence.get('tables') or {}).get(sample.table_id) if isinstance(evidence.get('tables'), dict) else None
@@ -210,6 +500,10 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
continue
actual_rows: list[dict[str, Any]] = []
for region in parser.table_regions:
# See candidate preview: a header-only page is evidence for order
# fields only and must not be sent to the line reconstruction engine.
if not region.line_layouts:
continue
actual_rows.extend(item.fields for item in reconstruct_coordinate_profile_rows(
characters=[item for item in characters if isinstance(item, dict)], table_bbox=table_bbox,
line_layouts=[item.model_dump() for item in region.line_layouts], table_region=region.region.model_dump(),
@@ -345,12 +639,53 @@ def promote_approved_suite_for_publish(*, profile: ShippingOrderDocumentProfile,
run.profile_checksum = published_checksum
def _serialize_suite_sample(sample: ShippingDocumentProfileTestSample) -> dict[str, Any]:
"""返回单份盲测样本的安全展示信息。
核心逻辑:从当前布局快照反查表格所在页,仅公开文件名、文档和表格标识,
不向工作台回传人工真值或订单正文。
Args:
sample: 已属于盲测集的样本 ORM 记录。
Returns:
可用于工作台已加入样本清单的脱敏摘要。
"""
document = db.session.get(ShippingNoticeDocument, sample.document_id)
layout = current_layout_snapshot(document) if document is not None else {}
table = next(
(
item for item in (layout or {}).get('tables') or []
if isinstance(item, dict) and str(item.get('table_id') or '') == sample.table_id
),
None,
)
return {
'id': sample.id,
'document_id': sample.document_id,
'table_id': sample.table_id,
'filename': str(document.filename or '') if document is not None else '',
'page_no': int(table.get('page_no') or 1) if isinstance(table, dict) else 1,
}
def serialize_suite(suite: ShippingDocumentProfileTestSuite) -> dict[str, Any]:
"""返回不含订单正文的盲测治理摘要,供管理端确认发布状态。"""
"""返回不含订单正文及真值的盲测治理摘要,供管理端维护与确认发布状态。
核心逻辑:保留运行门禁汇总,并附带可删除样本的最小定位信息;真值仍只在
服务端保存,避免通过摘要接口泄露订单内容。
Args:
suite: 当前 Profile checksum 对应的盲测集。
Returns:
含样本清单、执行摘要与批准状态的管理端 DTO。
"""
latest = suite.runs[-1] if suite.runs else None
return {
'id': suite.id, 'profile_id': suite.profile_id, 'profile_checksum': suite.profile_checksum,
'status': suite.status, 'sample_count': len(suite.samples),
'samples': [_serialize_suite_sample(sample) for sample in suite.samples],
'approved_at': suite.approved_at.isoformat() if suite.approved_at else None,
'latest_run': None if latest is None else {
'status': latest.status, 'sample_count': latest.sample_count,
@@ -19,7 +19,7 @@ from flask import current_app
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.constants import CP_UPLOADED, PH_UPLOAD_RPA_PENDING
from app.services.shipping_notice.constants import CP_UPLOADED, PH_UPLOAD_RPA_PENDING, PH_UPLOAD_RESULT_UNKNOWN
from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values
from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task
from app.services.shipping_notice.inventory_workflow import (
@@ -40,6 +40,7 @@ from app.services.shipping_notice.rpa import write_upload_trigger
from app.services.shipping_notice.upload_attempt_service import (
complete_attempt,
current_upload_artifact,
mark_attempt_result_unknown,
record_manual_upload,
start_rpa_attempt,
)
@@ -734,15 +735,28 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
)
last_failed = latest_event(task, "upload_rpa_failed")
if not last_failed or (last_failed.created_at < last_trigger.created_at):
attempt_id = (last_trigger.detail_json or {}).get('attempt_id') if isinstance(last_trigger.detail_json, dict) else None
from app.models import ShippingUploadAttempt
timed_out_attempt = db.session.get(ShippingUploadAttempt, attempt_id) if attempt_id else None
if timed_out_attempt is not None:
mark_attempt_result_unknown(timed_out_attempt)
task.error_message = t("workflow.fulfillment.upload_timeout_error", lang=lang).format(
timeout=timeout_seconds
)
task.pending_human_reason = PH_UPLOAD_RESULT_UNKNOWN
task.upload_status = 'unknown'
log_task_event(
task,
"upload_rpa_failed",
"upload_rpa_result_unknown",
{"error": "timeout", "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds},
)
db.session.flush()
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message='货代上传结果未知,已冻结重试;请先核对货代结果并登记回执或明确拒绝。',
data=serialize_task_for_tool(task),
)
attempts = upload_rpa_attempts(task)
if attempts >= max_attempts:
@@ -2,8 +2,9 @@
backend/app/services/shipping_notice/order_document_profile_service.py
用途:管理订单文档模板 Profile 的草稿、发布、退役和 Run 冻结快照。
依赖:ShippingOrderDocumentProfile、订单 Schema 版本、document_layout.order_profile 纯契约。
逻辑:草稿保存时把目标 field_code 转成稳定 field_id;发布时重新校验绑定 Schema 并原子替换当前版本。
依赖:ShippingOrderDocumentProfile、盲测套件模型、订单 Schema 版本、document_layout.order_profile 纯契约。
逻辑:草稿保存时把目标 field_code 转成稳定 field_id;发布时重新校验绑定 Schema 并原子替换当前版本;
删除草稿前先清理关联盲测套件,避免 suites.profile_id 外键 500。
"""
from __future__ import annotations
@@ -25,6 +26,7 @@ from app.extensions import db
from app.models import (
FileAsset,
ShippingDocumentProfileTestSample,
ShippingDocumentProfileTestSuite,
ShippingNoticeDocument,
ShippingNoticeIntake,
ShippingOrderDocumentProfile,
@@ -48,6 +50,7 @@ from app.services.shipping_notice.document_layout.order_profile import (
order_profile_structure_fingerprint,
reconstruct_order_profile_html,
)
from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields
from app.services.shipping_notice.order_schema.compatibility import (
compare_profile_schema,
is_replacement_compatible,
@@ -76,6 +79,7 @@ def _match_summary(definition: dict[str, Any]) -> dict[str, Any]:
'minimum_score': match.get('minimum_score'),
'minimum_margin': match.get('minimum_margin'),
'table_region_count': len(definition.get('table_regions') or []),
'order_field_layout_count': len(definition.get('order_field_layouts') or []),
}
@@ -100,6 +104,7 @@ def _definition_audit_summary(definition: dict[str, Any]) -> dict[str, Any]:
line_layout_count = 0
header_layout_count = 0
field_codes: set[str] = set()
order_field_count = 0
for table_region in table_regions:
if not isinstance(table_region, dict):
continue
@@ -111,9 +116,14 @@ def _definition_audit_summary(definition: dict[str, Any]) -> dict[str, Any]:
for field_region in line_layout.get('field_regions') or []:
if isinstance(field_region, dict) and field_region.get('field_code'):
field_codes.add(str(field_region['field_code']))
for order_field in definition.get('order_field_layouts') or []:
if isinstance(order_field, dict) and order_field.get('field_code'):
field_codes.add(str(order_field['field_code']))
order_field_count += 1
return {
'table_region_count': len(table_regions), 'header_layout_count': header_layout_count,
'line_layout_count': line_layout_count, 'bound_field_count': len(field_codes),
'line_layout_count': line_layout_count, 'order_field_layout_count': order_field_count,
'bound_field_count': len(field_codes),
}
@@ -220,6 +230,8 @@ def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersio
normalized = {
'document_match': raw.get('document_match'),
'table_regions': raw.get('table_regions'),
'order_field_layouts': raw.get('order_field_layouts') or [],
'draft_unbound_order_field_layouts': raw.get('draft_unbound_order_field_layouts') or [],
}
for table_region in normalized['table_regions'] or []:
if not isinstance(table_region, dict):
@@ -258,12 +270,52 @@ def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersio
{'field_id': str(profile_fields[target]['field_id']), 'field_code': target}
for target in sorted(outputs)
]
for order_field in normalized['order_field_layouts']:
if not isinstance(order_field, dict):
continue
code = str(order_field.get('field_code') or '').strip()
field = profile_fields.get(code)
if field is None or field.get('scope') != 'header':
raise ValidationError('Order field binding must target a header Schema field', code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID')
order_field['field_id'] = str(field['field_id'])
normalizer = order_field.get('normalizer_key')
if normalizer is not None and normalizer != field.get('normalizer_key'):
raise ValidationError('Order field normalizer must match Schema', code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID')
order_field['normalizer_key'] = field.get('normalizer_key')
# `ocr_coordinate` is a minimum level, not an OCR-only restriction: native PDF
# coordinates are stronger evidence and remain valid at runtime.
allowed_sources = (
['pdf_coordinate']
if order_field.get('minimum_evidence_level', 'coordinate') == 'coordinate'
else ['pdf_coordinate', 'ocr_coordinate']
)
schema_sources = field.get('allowed_sources')
if not isinstance(schema_sources, list) or not set(allowed_sources) & set(schema_sources):
raise ValidationError('Schema field does not allow order field coordinate source', code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID')
order_field_codes = [
str(item.get('field_code') or '').strip()
for item in normalized['order_field_layouts']
if isinstance(item, dict) and str(item.get('field_code') or '').strip()
]
duplicate_order_field_codes = sorted({
code for code in order_field_codes if order_field_codes.count(code) > 1
})
if duplicate_order_field_codes:
# Expose the duplicate Schema codes before Pydantic returns a generic
# contract error, so the workbench can direct the administrator to it.
raise ValidationError(
'Order field may bind only once',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID',
details={'reason': 'order_field_duplicate', 'field_codes': duplicate_order_field_codes},
)
try:
contract = OrderCoordinateProfileV2(
profile_code='VALIDATION_PROFILE',
version=1,
document_match=normalized['document_match'],
table_regions=normalized['table_regions'],
order_field_layouts=normalized['order_field_layouts'],
draft_unbound_order_field_layouts=normalized['draft_unbound_order_field_layouts'],
)
except (TypeError, ValueError) as exc:
raise ValidationError(
@@ -273,6 +325,8 @@ def _normalize_definition(raw: Any, *, schema_version: ShippingOrderSchemaVersio
'contract_version': contract.contract_version,
'document_match': contract.document_match.model_dump(),
'table_regions': [item.model_dump() for item in contract.table_regions],
'order_field_layouts': [item.model_dump() for item in contract.order_field_layouts],
'draft_unbound_order_field_layouts': [item.model_dump() for item in contract.draft_unbound_order_field_layouts],
}
@@ -293,6 +347,8 @@ def _definition_contract(profile: ShippingOrderDocumentProfile) -> OrderCoordina
version=profile.version,
document_match=definition.get('document_match'),
table_regions=definition.get('table_regions'),
order_field_layouts=definition.get('order_field_layouts') or [],
draft_unbound_order_field_layouts=definition.get('draft_unbound_order_field_layouts') or [],
)
@@ -489,6 +545,7 @@ def preview_profile_region(
contract = OrderCoordinateProfileV2(
profile_code=profile.profile_code, version=profile.version,
document_match=definition['document_match'], table_regions=definition['table_regions'],
order_field_layouts=definition['order_field_layouts'],
)
table_id = str(data.get('table_id') or '').strip()
layout = _document_layout(document)
@@ -587,6 +644,7 @@ def suggest_profile_header(
contract = OrderCoordinateProfileV2(
profile_code=profile.profile_code, version=profile.version,
document_match=definition['document_match'], table_regions=definition['table_regions'],
order_field_layouts=definition['order_field_layouts'],
)
table_id = str(data.get('table_id') or '').strip()
layout = _document_layout(document)
@@ -735,6 +793,359 @@ def _coordinate_characters(layout: dict[str, Any], table_id: str) -> list[dict[s
return [item for item in characters if isinstance(item, dict)]
def _page_coordinate_characters(layout: dict[str, Any], *, page_no: int) -> tuple[list[dict[str, Any]], str | None]:
"""读取整页字符证据供订单字段锚点建议使用,绝不以表格坐标代替页面坐标。"""
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
glyphs = (evidence.get('page_glyphs') or {}).get(str(page_no))
source = (evidence.get('sources') or {}).get('pages', {}).get(str(page_no))
if not isinstance(glyphs, list):
return [], None
return [item for item in glyphs if isinstance(item, dict)], str(source or '') or None
def _ensure_page_coordinate_evidence(
*, document: ShippingNoticeDocument, layout: dict[str, Any], page_no: int,
) -> dict[str, Any]:
"""为历史表格样本补齐整页坐标,避免订单抬头因仅存表内字符而无法自动标记。"""
glyphs, source = _page_coordinate_characters(layout, page_no=page_no)
if glyphs and source in {'pdf_coordinate', 'ocr_coordinate'}:
return layout
if not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'):
return layout
asset = db.session.get(FileAsset, document.asset_id)
if asset is None:
return layout
try:
from app.services.file_assets.service import read_asset_bytes
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages
from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines
native_page = next(item for item in extract_native_pdf_pages(read_asset_bytes(asset)) if item.page_no == page_no)
page_glyphs = [item.model_dump(mode='json') for item in native_page.characters]
page_source = 'pdf_coordinate'
if not page_glyphs:
page_glyphs = _ocr_lines_to_page_characters(
lines=extract_ocr_lines(native_page.image, page_width=native_page.width, page_height=native_page.height),
)
page_source = 'ocr_coordinate'
if not page_glyphs:
return layout
next_snapshot = dict(layout)
evidence = dict(next_snapshot.get('coordinate_evidence') or {})
pages = dict(evidence.get('pages') or {})
pages[str(page_no)] = {'width': native_page.width, 'height': native_page.height}
page_map = dict(evidence.get('page_glyphs') or {})
page_map[str(page_no)] = page_glyphs
sources = dict(evidence.get('sources') or {})
source_pages = dict(sources.get('pages') or {})
source_pages[str(page_no)] = page_source
sources['pages'] = source_pages
next_snapshot['coordinate_evidence'] = {**evidence, 'pages': pages, 'page_glyphs': page_map, 'sources': sources}
record_inline_layout_snapshot(
document, next_snapshot,
parser_key=f'mineru-pipeline+{page_source}:shipping_order_page_coordinate_evidence.v1',
)
db.session.commit()
return next_snapshot
except Exception:
# A suggestion is optional. Preserve existing table annotation behavior if the source cannot be reread.
return layout
def _page_text_lines(glyphs: list[dict[str, Any]]) -> list[tuple[str, dict[str, float], list[dict[str, Any]]]]:
"""将同一视觉行的字符压缩为文本和包围盒,供保守的标签精确匹配。"""
rows: list[list[dict[str, Any]]] = []
for glyph in sorted(glyphs, key=lambda item: (float((item.get('bbox') or {}).get('y0', 0)), float((item.get('bbox') or {}).get('x0', 0)))):
bbox = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else None
if not bbox or not str(glyph.get('text') or '').strip():
continue
center_y = (float(bbox.get('y0', 0)) + float(bbox.get('y1', 0))) / 2
if rows:
previous = rows[-1][0].get('bbox') or {}
previous_y = (float(previous.get('y0', 0)) + float(previous.get('y1', 0))) / 2
height = max(1.0, float(previous.get('y1', 0)) - float(previous.get('y0', 0)))
if abs(center_y - previous_y) <= height * .65:
rows[-1].append(glyph)
continue
rows.append([glyph])
result: list[tuple[str, dict[str, float], list[dict[str, Any]]]] = []
for row in rows:
ordered = sorted(row, key=lambda item: float((item.get('bbox') or {}).get('x0', 0)))
boxes = [item['bbox'] for item in ordered]
parts: list[str] = []
previous_x1: float | None = None
previous_width = 0.0
for item in ordered:
box = item['bbox']
x0, x1 = float(box['x0']), float(box['x1'])
# Native PDF glyph streams usually omit whitespace. Restore a visual word gap
# so suggested anchor text remains usable in the workbench and template config.
if previous_x1 is not None and x0 - previous_x1 > max(1.5, previous_width * 1.45):
parts.append(' ')
parts.append(str(item.get('text') or ''))
previous_x1, previous_width = x1, max(1.0, x1 - x0)
result.append((
''.join(parts),
{'x0': min(float(box['x0']) for box in boxes), 'y0': min(float(box['y0']) for box in boxes),
'x1': max(float(box['x1']) for box in boxes), 'y1': max(float(box['y1']) for box in boxes)},
ordered,
))
return result
def _anchor_text_key(value: str) -> str:
"""按标签语义比较,忽略空白和常见分隔符但不尝试模糊纠错。"""
return re.sub(r'[^\w]+', '', value, flags=re.UNICODE).casefold()
def _inline_anchor_and_value_regions(
*, text: str, line_bbox: dict[str, float], glyphs: list[dict[str, Any]], label: str, width: float, height: float,
) -> tuple[dict[str, float], dict[str, float], str]:
"""从字符 bbox 切分同行标签和值,绝不把同一行其他字段扩展进值框。"""
label_key = _anchor_text_key(label)
consumed: list[dict[str, Any]] = []
consumed_start = 0
key = ''
for index, glyph in enumerate(glyphs):
glyph_key = _anchor_text_key(str(glyph.get('text') or ''))
if not glyph_key:
continue
if label_key.startswith(key + glyph_key):
if not consumed:
consumed_start = index
consumed.append(glyph)
key += glyph_key
if key == label_key:
break
elif not consumed:
continue
else:
break
if not consumed or key != label_key:
consumed = glyphs[:1]
consumed_start = 0
# Consume the label separator but never add it to the value area.
anchor_glyphs = list(consumed)
after_label = glyphs[consumed_start + len(consumed):]
while after_label and str(after_label[0].get('text') or '') in ':: ':
anchor_glyphs.append(after_label.pop(0))
anchor_boxes = [item['bbox'] for item in anchor_glyphs]
anchor = {
'x0': max(0.0, min(1.0, min(float(box['x0']) for box in anchor_boxes) / width)),
'y0': max(0.0, min(1.0, min(float(box['y0']) for box in anchor_boxes) / height)),
'x1': max(0.0, min(1.0, max(float(box['x1']) for box in anchor_boxes) / width)),
'y1': max(0.0, min(1.0, max(float(box['y1']) for box in anchor_boxes) / height)),
}
if after_label:
normalized_text = text.casefold()
label_start = normalized_text.find(label.casefold())
label_end = label_start + len(label) if label_start >= 0 else len(label)
while label_end < len(text) and text[label_end] in ':: ':
label_end += 1
inline_value_text = text[label_end:].strip()
# PDF text can place independent key/value groups on the same visual row
# without a large glyph gap. Stop before the next explicit ``LABEL:``.
next_label = re.search(r'\s+[A-Za-z][A-Za-z0-9 ]{1,30}[::]', inline_value_text)
value_char_limit = (
len([char for char in inline_value_text[:next_label.start()] if not char.isspace()])
if next_label else None
)
# A large character gap starts the next key/value group on a shared visual
# row. Keep only the first contiguous value rather than swallowing it.
value_glyphs = [after_label[0]]
for glyph in after_label[1:]:
previous = value_glyphs[-1]['bbox']
current = glyph['bbox']
previous_width = max(1.0, float(previous['x1']) - float(previous['x0']))
if float(current['x0']) - float(previous['x1']) > previous_width * 3.5:
break
value_glyphs.append(glyph)
if value_char_limit is not None:
value_glyphs = value_glyphs[:max(1, value_char_limit)]
value_boxes = [item['bbox'] for item in value_glyphs]
# A relative percentage becomes visibly huge on tall PDFs. Keep the visual
# breathing room to at most one native page pixel around a single-line value.
vertical_padding = min(.0015, 1.0 / max(1.0, height))
value = {
'x0': max(anchor['x1'] + .003, min(float(box['x0']) for box in value_boxes) / width - .003),
'y0': max(0.0, min(float(box['y0']) for box in value_boxes) / height - vertical_padding),
'x1': min(.99, max(float(box['x1']) for box in value_boxes) / width + .003),
'y1': min(1.0, max(float(box['y1']) for box in value_boxes) / height + vertical_padding),
}
return anchor, value, 'right_of_anchor'
value = {
'x0': anchor['x0'], 'y0': min(.98, anchor['y1'] + .012),
'x1': min(.96, max(anchor['x1'] + .2, anchor['x0'] + .45)), 'y1': min(1.0, anchor['y1'] + .075),
}
return anchor, value, 'below_anchor'
def _inline_value_text(*, text: str, label: str) -> str:
"""返回与同行值框一致的首个值文本,供候选面板展示而不重复读取 PDF。"""
start = text.casefold().find(label.casefold())
suffix = text[start + len(label):] if start >= 0 else ''
suffix = suffix.lstrip(':: ').strip()
next_label = re.search(r'\s+[A-Za-z][A-Za-z0-9 ]{1,30}[::]', suffix)
return (suffix[:next_label.start()] if next_label else suffix).strip()
def _generic_order_label_candidates(
*, lines: list[tuple[str, dict[str, float], list[dict[str, Any]]]], width: float, height: float,
table_start_y: float | None, known_anchor_keys: set[str], bound_line_indexes: set[int], source: str,
) -> list[dict[str, Any]]:
"""为尚未配置 Schema 别名的 ``LABEL: value`` 生成未绑定订单字段候选。"""
candidates: list[dict[str, Any]] = []
for line_index, (text, bbox, glyphs) in enumerate(lines):
# 只取明细表前的上半段抬头;紧贴表格的 QUALITY/SHIPMENT 等条款不属于订单字段。
if table_start_y is not None and bbox['y0'] >= table_start_y - height * .18:
continue
match = re.match(r'^\s*([^::]{2,42}?)[::]', text)
if match is None:
continue
label = match.group(1).strip()
key = _anchor_text_key(label)
if line_index in bound_line_indexes or len(key) < 2 or key in known_anchor_keys or len(label.split()) > 3:
continue
anchor, value_region, value_mode = _inline_anchor_and_value_regions(
text=text, line_bbox=bbox, glyphs=glyphs, label=label, width=width, height=height,
)
candidates.append({
'field_id': '', 'field_code': '', 'display_name': label, 'source': source,
'status': 'suggested', 'binding_status': 'unbound', 'anchor_text': label,
'anchor_region': anchor,
'value_region': value_region, 'value_mode': value_mode,
'suggested_value': _inline_value_text(text=text, label=label),
'issue': 'order_field_schema_binding_required',
})
return candidates
def preview_order_field_values(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""
按当前未保存的 v2 定义重读订单字段值,供工作台刷新后展示复核证据。
浏览器只能提交当前样本与受控定义;读取复用正式运行期锚点/相对区域算法,
因此通用 Ship To、Bill To 标签不会依赖自动建议的标签过滤范围。
"""
try:
document_id = int(data.get('document_id'))
page_no = int(data.get('page_no') or 1)
except (TypeError, ValueError) as exc:
raise ValidationError('document_id or page_no is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') from exc
document = db.session.get(ShippingNoticeDocument, document_id)
if document is None:
raise NotFoundError('Order profile sample document not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
schema_version = _require_schema_version(data.get('schema_version_id'))
definition = _normalize_definition(data.get('definition'), schema_version=schema_version)
profile = OrderCoordinateProfileV2(
profile_code='WORKBENCH_PREVIEW', version=1,
document_match=definition['document_match'], table_regions=definition['table_regions'],
order_field_layouts=definition['order_field_layouts'],
draft_unbound_order_field_layouts=definition['draft_unbound_order_field_layouts'],
)
layout = _ensure_page_coordinate_evidence(
document=document, layout=_document_layout(document), page_no=page_no,
)
fields_by_id = {
str(field['field_id']): field
for field in _schema_profile_fields(schema_version).values()
if field.get('scope') == 'header'
}
return {
'page_no': page_no,
'fields': [
item.model_dump(mode='json')
for item in extract_order_fields(
profile=profile, schema_fields=fields_by_id,
coordinate_evidence=layout.get('coordinate_evidence') or {},
)
if item.page_no == page_no
],
}
def suggest_order_field_layouts(data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""
从冻结 Schema 的 Header 标签别名生成订单级字段的待复核锚点和值区建议。
只使用整页 PDF/OCR 字符坐标;标签不唯一、无坐标或 Schema 未授权时保留问题码,
绝不自动绑定或发布任何字段。
"""
try:
document_id = int(data.get('document_id'))
page_no = int(data.get('page_no') or 1)
except (TypeError, ValueError) as exc:
raise ValidationError('document_id or page_no is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID') from exc
document = db.session.get(ShippingNoticeDocument, document_id)
if document is None:
raise NotFoundError('Order profile sample document not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
schema_version = _require_schema_version(data.get('schema_version_id'))
layout = _document_layout(document)
layout = _ensure_page_coordinate_evidence(document=document, layout=layout, page_no=page_no)
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
page = (evidence.get('pages') or {}).get(str(page_no))
glyphs, source = _page_coordinate_characters(layout, page_no=page_no)
if not isinstance(page, dict) or not glyphs or source not in {'pdf_coordinate', 'ocr_coordinate'}:
return {'page_no': page_no, 'order_field_candidates': [], 'issues': ['order_field_page_coordinate_unavailable'], 'status': 'needs_review'}
try:
width, height = float(page['width']), float(page['height'])
except (KeyError, TypeError, ValueError) as exc:
raise ValidationError('Page coordinate evidence is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc
lines = _page_text_lines(glyphs)
candidates: list[dict[str, Any]] = []
known_anchor_keys: set[str] = set()
bound_line_indexes: set[int] = set()
for field in (schema_version.definition_json or {}).get('fields') or []:
if (
not isinstance(field, dict)
or field.get('enabled') is False
or field.get('auto_annotation_enabled', True) is False
or field.get('scope') != 'header'
):
continue
if source not in set(field.get('allowed_sources') or []):
continue
labels = [str(field.get('display_name') or '').strip(), *[str(item).strip() for item in field.get('aliases') or []]]
# Display text and alias often differ only by whitespace/case; count each visual hit once.
labels = list({key: item for item in labels if len(key := _anchor_text_key(item)) >= 2}.values())
known_anchor_keys.update(_anchor_text_key(item) for item in labels)
hits = [
(line_index, label, bbox)
for line_index, (text, bbox, _) in enumerate(lines)
for label in labels if _anchor_text_key(label) in _anchor_text_key(text)
]
base = {'field_id': str(field.get('field_id') or ''), 'field_code': str(field.get('field_code') or ''),
'display_name': str(field.get('display_name') or field.get('field_code') or ''), 'source': source}
if len(hits) != 1:
candidates.append({**base, 'status': 'ambiguous' if len(hits) > 1 else 'unavailable',
'issue': 'order_field_anchor_ambiguous' if len(hits) > 1 else 'order_field_anchor_not_found'})
continue
line_index, label, bbox = hits[0]
bound_line_indexes.add(line_index)
text, _, line_glyphs = lines[line_index]
anchor, value_region, value_mode = _inline_anchor_and_value_regions(
text=text, line_bbox=bbox, glyphs=line_glyphs, label=label, width=width, height=height,
)
candidates.append({**base, 'status': 'suggested', 'anchor_text': label, 'anchor_region': anchor,
'value_region': value_region, 'value_mode': value_mode,
'suggested_value': _inline_value_text(text=text, label=label),
'binding_status': 'bound', 'issue': None})
table_starts = [
float(item.get('bbox', {}).get('y0')) for item in layout.get('tables') or []
if isinstance(item, dict) and isinstance(item.get('bbox'), dict) and item.get('bbox', {}).get('y0') is not None
]
candidates.extend(_generic_order_label_candidates(
lines=lines, width=width, height=height, table_start_y=min(table_starts) if table_starts else None,
known_anchor_keys=known_anchor_keys, bound_line_indexes=bound_line_indexes, source=source,
))
_audit(profile_id=None, document_id=document.id, event_type='order_field_suggestions_viewed', actor_id=actor_id, detail={
'page_no': page_no, 'candidate_count': len(candidates), 'suggested_count': sum(item['status'] == 'suggested' for item in candidates),
})
db.session.commit()
return {'page_no': page_no, 'order_field_candidates': candidates, 'issues': [], 'status': 'needs_review'}
def generate_ocr_coordinate_evidence(*, document_id: int, table_id: str, actor_id: int | None) -> dict[str, Any]:
"""
为指定 PDF 表格补齐字符坐标证据;优先恢复原生文字层,仅在无文字层时执行 OCR。
@@ -853,6 +1264,27 @@ def _ocr_lines_to_characters(*, lines: list[Any], table_bbox: dict[str, Any]) ->
return result
def _ocr_lines_to_page_characters(*, lines: list[Any]) -> list[dict[str, Any]]:
"""将 OCR 行拆为整页字符坐标,专供订单抬头锚点候选,不与表格 cell 证据混用。"""
result: list[dict[str, Any]] = []
source_index = 0
for line in lines:
text = str(line.text or '')
box = line.bbox
if not text:
continue
width = (box.x1 - box.x0) / len(text)
for index, character in enumerate(text):
if not character.strip():
continue
result.append({'text': character, 'source_index': source_index, 'bbox': {
'x0': box.x0 + index * width, 'y0': box.y0,
'x1': box.x0 + (index + 1) * width, 'y1': box.y1,
}})
source_index += 1
return result
def _reconstructed_table_html(*, layout: dict[str, Any], raw_table: dict[str, Any], raw_settings: Any) -> str:
"""从持久化坐标证据和管理员确认的边界生成可审核重建表,缺任一条件均拒绝。"""
try:
@@ -1111,7 +1543,7 @@ def suggest_coordinate_reconstruction(data: dict[str, Any], *, actor_id: int | N
data: document_id、table_id,以及可选的非负 row_offset。省略 row_offset 时建议全部行。
actor_id: 当前管理员 ID;保留与预览接口一致的授权边界。
Returns:
仅含相对边界、少量列示例及确定性 line_no 建议的待审核配置;指定行时只返回该行。
仅含相对边界、少量列示例及字段规则驱动的待审核绑定;指定行时只返回该行。
"""
try:
document_id = int(data.get('document_id'))
@@ -1129,6 +1561,14 @@ def suggest_coordinate_reconstruction(data: dict[str, Any], *, actor_id: int | N
characters = _coordinate_characters(layout, table_id)
if raw_table is None or not characters or not isinstance(raw_table.get('bbox'), dict):
raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE')
schema_fields: list[dict[str, Any]] = []
if data.get('schema_version_id') is not None:
version = _require_schema_version(data.get('schema_version_id'))
schema_fields = [
field for field in _schema_fields(version).values()
if field.get('auto_annotation_enabled', True)
and set(field.get('allowed_sources') or []) & {'pdf_coordinate', 'ocr_coordinate'}
]
suggestions = suggest_multi_subrow_layouts(
characters=characters, table_bbox=raw_table['bbox'],
)
@@ -1162,9 +1602,50 @@ def suggest_coordinate_reconstruction(data: dict[str, Any], *, actor_id: int | N
}
except (KeyError, TypeError, ValueError, ZeroDivisionError) as exc:
raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc
header_suggestions = suggest_header_regions(characters=characters, table_bbox=raw_table['bbox'])
# Only exact, unique aliases can bind a column. Position is considered only after
# the label itself is proven, preventing shifted documents from remapping fields.
aliases: dict[str, str | None] = {}
for field in schema_fields:
code = str(field.get('field_code') or '').strip()
# A schema code is a stable, deterministic label variant: `unit_price`
# normalizes to `UNIT PRICE`. Include it alongside maintained aliases so
# common table headers bind without positional guessing.
for value in (code.replace('_', ' '), field.get('display_name'), *(field.get('aliases') or [])):
key = _anchor_text_key(str(value or ''))
if key:
aliases[key] = code if aliases.get(key, code) == code else None
for header in header_suggestions:
for field in header.fields:
key = _anchor_text_key(field.text)
code = aliases.get(key)
field.field_code = code
field.confidence = 'exact_alias' if code else ('ambiguous' if key in aliases else 'unmapped')
serialized = []
for item in suggestions:
payload = item.model_dump()
if item.row_offset == 0 and schema_fields:
mapped_codes: list[str | None] = [None] * (len(item.column_boundaries) - 1)
mapped_indexes: dict[int, list[str]] = {}
for header in header_suggestions:
for field in header.fields:
if not field.field_code:
continue
center = (field.region.x0 + field.region.x1) / 2
column_index = min(
range(len(mapped_codes)),
key=lambda index: abs(
center - (item.column_boundaries[index] + item.column_boundaries[index + 1]) / 2,
),
)
mapped_indexes.setdefault(column_index, []).append(field.field_code)
for column_index, codes in mapped_indexes.items():
# Multiple exact labels pointing to one reconstructed column is still
# ambiguous; retain the visual candidate but require manual binding.
if len(set(codes)) == 1:
mapped_codes[column_index] = codes[0]
payload['suggested_field_codes'] = mapped_codes
payload['region'] = {
'x0': table_region['x0'],
'x1': table_region['x1'],
@@ -1173,7 +1654,7 @@ def suggest_coordinate_reconstruction(data: dict[str, Any], *, actor_id: int | N
}
serialized.append(payload)
serialized_headers = []
for item in suggest_header_regions(characters=characters, table_bbox=raw_table['bbox']):
for item in header_suggestions:
payload = item.model_dump()
region = payload['region']
payload['region'] = {
@@ -1428,6 +1909,37 @@ def create_schema_migration_draft(
if isinstance(item, dict) and item.get('field_id') and item.get('enabled', True)
}
definition = remap_profile_field_codes(source.definition_json or {}, target_schema.definition_json or {})
unbound_order_fields = list(definition.get('draft_unbound_order_field_layouts') or [])
retained_order_fields: list[dict[str, Any]] = []
for field in definition.get('order_field_layouts') or []:
if not isinstance(field, dict):
continue
field_id = str(field.get('field_id') or '')
if field_id not in breaking_ids:
retained_order_fields.append(field)
continue
resolution = resolutions[field_id]
replacement_id = str(resolution.get('replacement_field_id') or '') if isinstance(resolution, dict) else ''
if replacement_id:
replacement = target_fields.get(replacement_id)
original = next((item for item in (source_schema.definition_json or {}).get('fields') or []
if isinstance(item, dict) and str(item.get('field_id')) == field_id), None)
if replacement is None or original is None or not is_replacement_compatible(
original, replacement, source_field_id=field_id, candidate_field_id=replacement_id,
):
raise ValidationError('Replacement field is not contract-compatible', code='SHIPPING.ORDER_DOCUMENT_PROFILE_MIGRATION_INVALID')
field['field_id'] = replacement_id
field['field_code'] = str(replacement.get('field_code') or '')
retained_order_fields.append(field)
elif isinstance(resolution, dict) and resolution.get('action') == 'unbind':
unbound_order_fields.append({
key: value for key, value in field.items()
if key not in {'field_id', 'field_code', 'normalizer_key', 'required'}
} | {'label': str(field.get('field_code') or field_id)})
else:
raise ValidationError('Migration resolution is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_MIGRATION_INVALID')
definition['order_field_layouts'] = retained_order_fields
definition['draft_unbound_order_field_layouts'] = unbound_order_fields
for table in definition.get('table_regions') or []:
if not isinstance(table, dict):
continue
@@ -1485,6 +1997,8 @@ def create_schema_migration_draft(
'parent_layout_id': str(layout.get('layout_id') or ''),
'label': str(field.get('field_code') or field_id),
'region': field.get('region'),
# Schema-breaking migrations require an explicit field decision.
'requires_rebinding': True,
})
else:
raise ValidationError(
@@ -1561,14 +2075,21 @@ def publish(
code='SHIPPING.ORDER_DOCUMENT_PROFILE_VERSION_CONFLICT',
)
if any(
table.get('draft_unbound_field_regions')
item.get('requires_rebinding')
for table in (profile.definition_json or {}).get('table_regions', [])
if isinstance(table, dict)
for item in (table.get('draft_unbound_field_regions') or [])
if isinstance(item, dict)
):
raise ValidationError(
'All draft field regions must be bound before publish',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
)
if (profile.definition_json or {}).get('draft_unbound_order_field_layouts'):
raise ValidationError(
'All draft order field layouts must be bound before publish',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
)
# 发布前先以草稿定义 checksum 执行训练/盲测门禁;不能先发布再补测。
from app.services.shipping_notice.document_profile_quality_service import (
assert_profile_publishable,
@@ -1629,7 +2150,12 @@ def retire(profile_id: int, *, actor_id: int | None = None) -> dict[str, Any]:
def delete_draft(profile_id: int) -> None:
"""删除未发布草稿;不可变版本永久保留审计。"""
"""
删除未发布草稿及其草稿盲测集;已发布/退役版本永久保留审计。
核心逻辑:草稿允许绑定独立盲测套件,但 suites.profile_id 外键无 CASCADE;
删除前先移除 suite(samples/runs 由 ORM cascade 清理),避免 IntegrityError 500。
"""
profile = db.session.get(ShippingOrderDocumentProfile, profile_id)
if profile is None:
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
@@ -1638,6 +2164,12 @@ def delete_draft(profile_id: int) -> None:
'Only draft order document profile can be deleted',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_DELETE_BLOCKED',
)
# [STEP 1] 先清盲测套件;samples/runs 随 suite cascade delete-orphan
suite = ShippingDocumentProfileTestSuite.query.filter_by(profile_id=profile.id).first()
if suite is not None:
db.session.delete(suite)
db.session.flush()
# [STEP 2] 删除草稿 Profile 本体(样本表已有 DB CASCADE)
db.session.delete(profile)
db.session.commit()
@@ -417,7 +417,8 @@ def persist_order_extraction_result(
candidate.order_extraction_id = int(dynamic['extraction'].id)
candidate.order_extraction_run_id = int(run_id) if run_id is not None else None
candidate.is_current_version = True
candidate.extraction_source = extraction_source
automatic_acceptance = raw_order.get('_hxops_acceptance') == 'approved_deterministic_profile_v1'
candidate.extraction_source = 'approved_deterministic_profile' if automatic_acceptance else extraction_source
candidate.classification_confidence = classification_confidence
candidate.field_confidence_json = field_confidence
candidate.missing_fields_json = list(assessment['missing_required_fields']) + list(assessment['missing_process_fields'])
@@ -426,7 +427,14 @@ def persist_order_extraction_result(
candidate.confidence = classification_confidence
candidate.conflicts_json = blocking_conflicts
candidate.validation_status = 'ready' if not reasons else 'needs_review'
candidate.selected = not reasons
# Only the backend's frozen approved-profile marker can automatically accept.
candidate.candidate_status = 'accepted' if automatic_acceptance else 'provisional'
candidate.acceptance_mode = 'automatic' if automatic_acceptance else None
candidate.accepted_at = datetime.utcnow() if automatic_acceptance else None
candidate.accepted_by_id = None
candidate.acceptance_reason = 'approved_deterministic_profile' if automatic_acceptance else None
candidate.acceptance_policy_version = 'deterministic-profile-v1' if automatic_acceptance else None
candidate.selected = bool(automatic_acceptance)
identity = build_business_fingerprint(normalized)
content = build_content_fingerprint(normalized)
candidate.business_fingerprint = identity.get('fingerprint')
@@ -493,12 +501,44 @@ def persist_order_extraction_result(
candidate.duplicate_target_task_no = str(matches[0].get('task_no') or '').strip().upper() or None
# [STEP] 仅无审核阻断原因时才选中自动打开;证据/冲突失败必须保持未选中,
# 否则同 Intake 其它 ready Candidate 会被 selection 门禁整批挡住。
candidate.selected = not reasons
candidate.selected = False
candidate.validation_status = 'ready' if not reasons else 'needs_review'
elif duplicate.get('blocking'):
reasons.append('duplicate_decision_required')
candidate.selected = False
candidate.validation_status = 'needs_review'
# An approved template is automatic only after the same strict field and
# duplicate gates as a manual decision. A partial parse stays provisional.
automatic_eligible = (
automatic_acceptance
and not reasons
and candidate.validation_status == 'ready'
and not duplicate.get('blocking')
)
open_existing_eligible = (
candidate.duplicate_resolution == 'open_existing'
and bool(candidate.duplicate_target_task_no)
and not reasons
and candidate.validation_status == 'ready'
)
if open_existing_eligible:
# This does not admit a Dify result into new fulfillment. It only
# selects a strong duplicate for the dedicated existing-task path.
# Candidate acceptance remains exclusively automatic/manual/legacy.
candidate.candidate_status = 'provisional'
candidate.acceptance_mode = None
candidate.accepted_at = None
candidate.accepted_by_id = None
candidate.acceptance_reason = None
candidate.acceptance_policy_version = None
candidate.selected = True
elif not automatic_eligible:
candidate.candidate_status = 'provisional'
candidate.acceptance_mode = None
candidate.accepted_at = None
candidate.acceptance_reason = None
candidate.acceptance_policy_version = None
candidate.selected = False
candidate.updated_at = datetime.utcnow()
# Candidate 已关联本轮受控 FieldValue 后刷新影子识别;不读取其 LLM 摘要,也不触发自动确认。
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution_safely
@@ -506,10 +546,17 @@ def persist_order_extraction_result(
refresh_candidate_shadow_resolution_safely(candidate)
document_candidate_keys[int(document.id)].append(candidate_key)
document_has_pending[int(document.id)] = document_has_pending[int(document.id)] or bool(reasons)
if candidate.selected and candidate.validation_status == 'ready' and auto_create_enabled:
if (
candidate.selected
and candidate.validation_status == 'ready'
and (
(candidate.candidate_status == 'accepted' and auto_create_enabled)
or candidate.duplicate_resolution == 'open_existing'
)
):
auto_candidates.append(candidate)
else:
if candidate.validation_status == 'ready' and not auto_create_enabled:
if candidate.candidate_status != 'accepted' and candidate.validation_status == 'ready' and not auto_create_enabled:
candidate.selected = False
reasons.append('auto_create_disabled')
pending_item = {
@@ -168,6 +168,9 @@ def merge_unit_orders(*, orders: list[dict[str, Any]], schema_definition: dict[s
po_numbers, line_keys = _order_identity(order, codes)
match = None
for candidate in merged:
# A Dify order may never inherit an approved-profile acceptance marker.
if candidate.get('_hxops_acceptance') != order.get('_hxops_acceptance'):
continue
if str(candidate.get('source_intake_no') or '').strip().upper() != intake_no:
continue
candidate_pos, candidate_lines = _order_identity(candidate, codes)
@@ -380,8 +380,15 @@ def create_order_extraction_run(
capability_code='shipping.order_extraction',
)
schema_version = published_version()
binding_auto_create_enabled = bool((binding.config_json or {}).get('auto_create_enabled'))
from app.services.shipping_notice.order_schema.service import get_auto_creation_policy
schema_auto_creation_policy = get_auto_creation_policy()
effective_auto_create_enabled = bool(
schema_auto_creation_policy.get('enabled') and binding_auto_create_enabled
)
quality_batch_id = binding.quality_batch_id
if bool((binding.config_json or {}).get('auto_create_enabled')):
if effective_auto_create_enabled:
from app.services.shipping_notice.order_extraction_quality_service import require_approved_quality_batch
require_approved_quality_batch(
@@ -413,9 +420,14 @@ def create_order_extraction_run(
intakes=intakes,
schema_version=schema_version,
)
# 自动建单总开关与字段模板一起冻结,后续管理员变更不影响已创建 Run。
from app.services.shipping_notice.order_schema.service import get_auto_creation_policy
snapshot['auto_creation_policy'] = get_auto_creation_policy()
# 自动建单必须同时通过 Schema 总开关、运行能力绑定和质量批次;任何一层关闭
# 都冻结为影子模式,避免仅改 Schema 意外恢复自动履约。
snapshot['auto_creation_policy'] = {
**schema_auto_creation_policy,
'enabled': effective_auto_create_enabled,
'schema_enabled': bool(schema_auto_creation_policy.get('enabled')),
'runtime_binding_enabled': binding_auto_create_enabled,
}
snapshot_hash = _sha256(snapshot)
idempotency_key = _sha256({
'user_id': user.id,
@@ -458,7 +470,7 @@ def create_order_extraction_run(
runtime_binding_id=binding.id,
provider_agent_id=binding.provider_agent_id,
quality_batch_id=quality_batch_id,
provider_config_json=binding_config,
provider_config_json={**binding_config, 'auto_create_enabled': effective_auto_create_enabled},
provider_snapshot_json={
'provider_agent_id': binding.provider_agent_id,
'runtime_provider': binding.provider_agent.runtime_provider,
@@ -599,7 +611,9 @@ def reparse_order_extraction_run(
).all()
for candidate in source_candidates:
candidate.selected_before_superseded = bool(candidate.selected)
candidate.candidate_status_before_superseded = candidate.candidate_status
candidate.selected = False
candidate.candidate_status = 'expired'
candidate.is_current_version = False
source.superseded_by_run_id = run.id
source.superseded_at = datetime.utcnow()
@@ -1252,6 +1266,8 @@ def _restore_candidates_after_failed_reparse(run: ShippingOrderExtractionRun) ->
candidate.is_current_version = True
candidate.selected = bool(candidate.selected_before_superseded)
candidate.selected_before_superseded = None
candidate.candidate_status = candidate.candidate_status_before_superseded or 'provisional'
candidate.candidate_status_before_superseded = None
source.superseded_by_run_id = None
source.superseded_at = None
@@ -26,6 +26,7 @@ from app.services.shipping_notice.document_layout.order_profile import (
)
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import reconstruct_coordinate_profile_rows
from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields
from app.services.shipping_notice.document_layout.order_profile_matcher import match_frozen_coordinate_profiles
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value
@@ -679,6 +680,10 @@ def parse_order_extraction_workflow_result(result: dict[str, Any]) -> list[dict[
if isinstance(raw, dict) and 'orders' in raw:
raw = raw['orders']
continue
# Only the documented data wrapper is accepted; do not search arbitrary JSON.
if isinstance(raw, dict) and isinstance(raw.get('data'), dict) and 'orders' in raw['data']:
raw = raw['data']['orders']
continue
if not isinstance(raw, str) or json_decode_count >= 2:
break
try:
@@ -711,6 +716,11 @@ def validate_unit_orders(
}
evidence_text = frozen_document_text_for_dify(document) or str(document.get('extracted_text') or '')
for order in orders:
if strict_provider_evidence and any(str(key).startswith('_hxops_') for key in order):
raise ValidationError(
'Workflow order contains reserved HXOPS fields',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
)
if str(order.get('source_intake_no') or '').strip().upper() != intake_no:
raise ValidationError(
'Unit order source intake does not match the extraction unit',
@@ -734,7 +744,19 @@ def validate_unit_orders(
'Unit order contains a field outside the frozen extraction contract',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
)
if strict_provider_evidence and any(str(key).startswith('_hxops_') for key in field):
raise ValidationError(
'Workflow field contains reserved HXOPS fields',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
)
for observation in field.get('observations') or [] if isinstance(field, dict) else []:
if strict_provider_evidence and isinstance(observation, dict) and any(
str(key).startswith('_hxops_') for key in observation
):
raise ValidationError(
'Workflow observation contains reserved HXOPS fields',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
)
if not isinstance(observation, dict) or int(observation.get('document_id') or 0) != int(unit.document_id):
raise ValidationError(
'Unit observation references another document',
@@ -748,7 +770,7 @@ def validate_unit_orders(
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
)
_validate_locked_layout_fields(document, orders=orders)
return orders
return _merge_confirmed_profile_order_fields(run, unit=unit, orders=orders)
def _validate_locked_layout_fields(document: dict[str, Any], *, orders: list[dict[str, Any]]) -> None:
@@ -798,6 +820,63 @@ def _validate_locked_layout_fields(document: dict[str, Any], *, orders: list[dic
)
def _merge_confirmed_profile_order_fields(run: Any, *, unit: Any, orders: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""注入 confirmed 订单字段并拒绝 Provider 显式冲突;Provider 省略它们是合法的。"""
locked = {
str(item.get('field_id') or ''): item for item in _confirmed_profile_order_fields(run, unit=unit)
if item.get('field_id')
}
if not locked:
return orders
for order in orders:
returned: dict[str, set[str]] = {}
for field in order.get('header_fields') or []:
if not isinstance(field, dict) or str(field.get('field_id') or '') not in locked:
continue
for observation in field.get('observations') or []:
if isinstance(observation, dict):
returned.setdefault(str(field['field_id']), set()).add(
json.dumps(observation.get('value'), ensure_ascii=False, sort_keys=True),
)
expected = {
field_id: {json.dumps(item.get('value'), ensure_ascii=False, sort_keys=True)}
for field_id, item in locked.items()
}
# Missing fields are expected: Dify never receives coordinate template values.
if any(returned.get(field_id, values) != values for field_id, values in expected.items() if field_id in returned):
raise ValidationError(
'Workflow changed a confirmed order field',
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
)
header_fields = order.get('header_fields') if isinstance(order.get('header_fields'), list) else []
by_id = {str(item.get('field_id') or ''): item for item in header_fields if isinstance(item, dict)}
for field_id, candidate in locked.items():
# Replace any agreeing Provider observation with immutable coordinate evidence.
field = by_id.get(field_id)
observation = {
'value': candidate.get('value'), 'document_id': int(unit.document_id),
'quote': str(candidate.get('value') or '')[:1000], 'confidence': 1.0,
'layout_evidence': {
'page_no': candidate.get('page_no'), 'source': candidate.get('source'),
'anchor_bbox': candidate.get('anchor_bbox'), 'value_bbox': candidate.get('value_bbox'),
'glyph_indices': list(candidate.get('glyph_indices') or []),
},
}
if field is None:
header_fields.append({
'field_id': field_id, 'observations': [observation],
'_hxops_order_field_evidence': True,
})
else:
field['observations'] = [observation]
field['_hxops_order_field_evidence'] = True
order['header_fields'] = header_fields
# Only HXOPS can set this marker. Provider validation ran before this point;
# it grants coordinate evidence only, never automatic order acceptance.
order['_hxops_order_field_evidence'] = True
return orders
def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, Any]] | None:
"""仅由盲测批准的唯一 Profile 实测行生成零 Provider 订单;其余交给模型补充。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
@@ -819,10 +898,17 @@ def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, An
# 文档出现多个模板表时不猜测其业务关系,即使其中一个模板已批准也回退 Dify/人工。
if len(profile_result.get('tables') or []) != 1 or len(approved_tables) != 1:
return None
confirmed_order_fields = _confirmed_profile_order_fields(run, unit=unit)
order = _build_approved_profile_order(
unit=unit, intake=intake, schema=schema, definition=definition, table=approved_tables[0],
confirmed_order_fields=confirmed_order_fields,
)
return [order] if order is not None else None
if order is None:
return None
if confirmed_order_fields:
# `_build_approved_profile_order` has already merged and validated these fields.
pass
return [order]
def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfileV2:
@@ -831,12 +917,13 @@ def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfileV2:
return OrderCoordinateProfileV2(
profile_code=str(raw.get('profile_code') or ''), version=int(raw.get('version') or 0),
document_match=definition.get('document_match'), table_regions=definition.get('table_regions'),
order_field_layouts=definition.get('order_field_layouts') or [],
)
def _build_approved_profile_order(
*, unit: Any, intake: dict[str, Any], schema: dict[str, Any], definition: dict[str, Any],
table: dict[str, Any],
table: dict[str, Any], confirmed_order_fields: list[dict[str, Any]] | None = None,
) -> dict[str, Any] | None:
"""
把已批准 Profile 本次实际解析的唯一完整表格转换为零 Provider 订单。
@@ -847,6 +934,7 @@ def _build_approved_profile_order(
schema: Dify 抽取契约元信息。
definition: Run 冻结 Schema 完整定义,用于 required/scope 门禁。
table: `_profile_table_candidates` 产生且已批准的单个表解析结果。
confirmed_order_fields: 同一冻结模板产生的 confirmed 订单字段,作为独立 Header 证据合并。
Returns:
完整确定性订单;候选非唯一、含问题或缺必填字段时返回 None。
@@ -889,9 +977,28 @@ def _build_approved_profile_order(
if len(unique) != 1:
return None
header_fields.append({'field_id': field_id, 'observations': [observations[0]]})
present_header = {item['field_id'] for item in header_fields}
for candidate in confirmed_order_fields or []:
field_id = str(candidate.get('field_id') or '')
if not field_id:
continue
if field_id in present_header:
# Header table evidence and independent order-field evidence must never silently compete.
return None
header_fields.append({'field_id': field_id, '_hxops_order_field_evidence': True, 'observations': [{
'value': candidate.get('value'), 'document_id': int(unit.document_id),
'quote': str(candidate.get('value') or '')[:1000], 'confidence': 1.0,
# Kept only in the internal deterministic result. The Dify manifest strips
# layout payloads and strict Provider validation rejects `_hxops_*` markers.
'layout_evidence': {
'page_no': candidate.get('page_no'), 'source': candidate.get('source'),
'anchor_bbox': candidate.get('anchor_bbox'), 'value_bbox': candidate.get('value_bbox'),
'glyph_indices': list(candidate.get('glyph_indices') or []),
},
}]})
present_header.add(field_id)
if not line_groups:
return None
present_header = {item['field_id'] for item in header_fields}
for config in fields:
if not config.get('required'):
continue
@@ -908,9 +1015,47 @@ def _build_approved_profile_order(
'source_intake_no': str(intake.get('intake_no') or ''),
'primary_document_id': int(unit.document_id),
'header_fields': header_fields, 'lines': line_groups, 'conflicts': [],
# Only this frozen approved-profile builder may add this internal marker.
'_hxops_acceptance': 'approved_deterministic_profile_v1',
}
def _confirmed_profile_order_fields(run: Any, *, unit: Any) -> list[dict[str, Any]]:
"""读取唯一匹配 v2 模板的 confirmed 订单字段;无页级证据或歧义时返回空锁集。"""
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
definition = schema_snapshot.get('definition') if isinstance(schema_snapshot.get('definition'), dict) else {}
schema_fields = {
str(item.get('field_id') or ''): item for item in definition.get('fields') or []
if isinstance(item, dict) and item.get('enabled', True) and item.get('scope') == 'header'
}
profiles = [
item for item in snapshot.get('order_document_profiles') or []
if isinstance(item, dict) and int(item.get('schema_version_id') or 0) == int(run.schema_version_id)
and isinstance(item.get('definition'), dict)
and item['definition'].get('contract_version') == 'order_coordinate_profile.v2'
]
_intake, document = _unit_snapshot(run, unit)
layout = document.get('layout_snapshot') if isinstance(document.get('layout_snapshot'), dict) else {}
if not profiles or layout.get('status') != 'ready':
return []
match = match_frozen_coordinate_profiles(profiles=profiles, layout=layout)
if match.status != 'unique_match':
return []
raw = next((
item for item in profiles
if item.get('profile_code') == match.profile_code and int(item.get('version') or 0) == match.version
and str(item.get('checksum') or '') == match.checksum
), None)
if raw is None:
return []
candidates = extract_order_fields(
profile=_frozen_coordinate_profile(raw), schema_fields=schema_fields,
coordinate_evidence=layout.get('coordinate_evidence') or {},
)
return [item.model_dump(mode='json') for item in candidates if item.status == 'confirmed']
def execute_order_extraction_workflow(*, run: Any, unit: Any, provider: Any, timeout_seconds: int, event_observer=None) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""调用绑定 Provider 的 Workflow,并把网络异常归类为可重试业务错误。"""
try:
@@ -36,6 +36,9 @@ def referenced_field_ids(profile_definition: dict[str, Any] | None) -> set[str]:
for target in field.get('target_fields') or []:
if isinstance(target, dict) and target.get('field_id'):
result.add(str(target['field_id']))
for field in (profile_definition or {}).get('order_field_layouts') or []:
if isinstance(field, dict) and field.get('field_id'):
result.add(str(field['field_id']))
return result
@@ -191,4 +194,10 @@ def remap_profile_field_codes(
values = layout.get(key)
if isinstance(values, list):
layout[key] = [code_map.get(str(code), code) for code in values]
for field in result.get('order_field_layouts') or []:
if not isinstance(field, dict):
continue
target_field = target.get(str(field.get('field_id') or ''))
if target_field:
field['field_code'] = target_field.get('field_code')
return result
@@ -14,6 +14,7 @@ from typing import Any
_SCALAR_KEYS = (
'field_code', 'scope', 'value_type', 'field_category', 'collection_mode', 'enabled',
'display_name', 'description', 'business_purpose', 'required', 'normalizer_key',
'auto_annotation_enabled',
'relation_role', 'comparator_key', 'extraction_instruction', 'context_source',
'sensitivity_level', 'dify_exposure_policy', 'available_for_customer_identity', 'sequence',
)
@@ -8,7 +8,7 @@ backend/app/services/shipping_notice/order_schema/field_rules.py
from __future__ import annotations
from datetime import date
from datetime import date, datetime
from decimal import Decimal, InvalidOperation
from typing import Any
@@ -28,8 +28,16 @@ def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any:
if value_type == 'integer':
return int(str(value).replace(',', '').strip())
if value_type == 'date':
text = str(value).strip().replace('/', '-').replace('.', '-')
return date.fromisoformat(text)
text = str(value).strip()
# Purchase orders commonly print US-style dates (for example
# ``06/20/2026``). Accept only explicit, deterministic layouts so
# we restore coordinate candidates without treating free text as a date.
for pattern in ('%Y-%m-%d', '%Y/%m/%d', '%Y.%m.%d', '%Y%m%d', '%m/%d/%Y', '%m-%d-%Y', '%m.%d.%Y'):
try:
return datetime.strptime(text, pattern).date()
except ValueError:
continue
raise ValueError('invalid date')
if value_type == 'boolean':
if isinstance(value, bool):
return value
@@ -178,6 +178,15 @@ def _verified_observations(
quote = str(item.get('quote') or '').strip()
if document is None or value is None or not _validate(value, config):
continue
layout_evidence = item.get('layout_evidence') if raw.get('_hxops_order_field_evidence') is True else None
if isinstance(layout_evidence, dict) and _valid_coordinate_evidence(layout_evidence):
verified.append({
'value': value, 'document': document, 'quote': quote or str(value), 'confidence': 1.0,
'source_type': 'attachment_coordinate', 'extractor': 'order_profile_order_field',
'evidence_ref': f"document:{int(document.id)}:order-field:{config['field_id']}:page:{int(layout_evidence['page_no'])}",
'evidence_metadata': {'kind': 'order_field_coordinate', **layout_evidence},
})
continue
frozen_text = str((frozen_evidence_text_by_document or {}).get(int(document.id)) or '')
source_texts = [frozen_text, str(document.extracted_text or '')]
if not quote or not any(quote in text for text in source_texts if text):
@@ -203,6 +212,16 @@ def _verified_observations(
return verified
def _valid_coordinate_evidence(raw: dict[str, Any]) -> bool:
"""只接受后端确认的最小页级坐标证据,缺页号、来源或字符索引时不提升为已验证。"""
return (
str(raw.get('source') or '') == 'pdf_coordinate'
and isinstance(raw.get('page_no'), int) and raw['page_no'] >= 1
and isinstance(raw.get('anchor_bbox'), dict) and isinstance(raw.get('value_bbox'), dict)
and isinstance(raw.get('glyph_indices'), list) and bool(raw['glyph_indices'])
)
def _choose_value(observations: list[dict[str, Any]], config: dict[str, Any]) -> tuple[Any, str, str | None]:
"""按一致性、来源优先级和冲突策略选择字段值。"""
if not observations:
@@ -1124,6 +1124,13 @@ def _coordinate_sources(value: Any) -> list[str]:
return sources
def _default_auto_annotation_enabled(raw: dict[str, Any]) -> bool:
"""仅让必填或建单关键字段默认参与画布自动标记,避免可选字段淹没候选。"""
return bool(raw.get('required')) or bool(raw.get('auto_create_key_field')) or (
str(raw.get('business_purpose') or 'general') != 'general'
)
def save_draft(
version_id: int, data: dict[str, Any], *, actor_id: int | None = None,
request_id: str | None = None,
@@ -1170,9 +1177,10 @@ def save_draft(
validators = _string_list(raw.get('validator_keys', []), field='validator_keys')
aliases = _string_list(raw.get('aliases', []), field='aliases')
enum_options = _string_list(raw.get('enum_options', []), field='enum_options')
auto_annotation_enabled = raw.get('auto_annotation_enabled', _default_auto_annotation_enabled(raw))
relation_role = str(raw.get('relation_role') or '').strip() or None
required = raw.get('required', False)
if not isinstance(enabled, bool) or not isinstance(required, bool):
if not isinstance(enabled, bool) or not isinstance(required, bool) or not isinstance(auto_annotation_enabled, bool):
raise ValidationError('required must be boolean', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
if not display_name or normalizer not in NORMALIZERS or comparator not in COMPARATORS:
raise ValidationError('field display or transformation config is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
@@ -1234,6 +1242,7 @@ def save_draft(
'minimum_confidence': round(minimum_confidence, 2) if minimum_confidence is not None else None,
'required': required,
'aliases': aliases,
'auto_annotation_enabled': auto_annotation_enabled,
'normalizer_key': normalizer,
'validator_keys': validators,
'enum_options': enum_options,
@@ -145,6 +145,7 @@ def record_inventory_verification(
db.session.add(verification)
db.session.flush()
available_count = 0
seen_reservation_ids: set[str] = set()
for item in line_results:
reservation_id = validated_reservation_id(item.get('reservation_id'))
part_number = str(item.get('part_number') or '').strip()
@@ -152,6 +153,11 @@ def record_inventory_verification(
if reservation is None or reservation.part_number != part_number:
raise ValidationError('Inventory result does not map to a frozen reservation', code='SHIPPING.RESERVATION_MISMATCH')
required = _decimal(item.get('required_qty'))
# The frozen order is the quantity authority. A reduced or duplicate result
# must not turn an insufficient reservation into an exportable line.
if reservation_id in seen_reservation_ids or required != reservation.required_qty:
raise ValidationError('Inventory result quantity is inconsistent with the frozen reservation', code='SHIPPING.RESERVATION_MISMATCH')
seen_reservation_ids.add(reservation_id)
available = _decimal(item.get('available_qty')) if Decimal(str(item.get('available_qty') or 0)) > 0 else Decimal('0')
status = 'available' if available >= required else 'shortage'
db.session.add(ShippingInventoryVerificationLine(
@@ -36,6 +36,7 @@ from app.services.shipping_notice.constants import (
CP_UPLOADED,
CP_COMPLETED,
CP_UPLOAD_FAILED,
CP_UPLOAD_RESULT_UNKNOWN,
CP_UPLOAD_REQ,
CP_WAITING_UPLOAD,
PH_INV_UNAVAIL,
@@ -48,6 +49,7 @@ from app.services.shipping_notice.constants import (
PH_SHORTAGE,
PH_UPLOAD_RPA_FAILED,
PH_UPLOAD_RPA_PENDING,
PH_UPLOAD_RESULT_UNKNOWN,
RS_CONFIRMED,
RS_PARSE_REVIEW,
RS_REJECTED,
@@ -121,6 +123,7 @@ CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("replace_notice_file", "reparse", "reject"),
CP_UPLOAD_FAILED: ("retry_upload", "download_excel", "mark_manual_uploaded"),
CP_WAITING_UPLOAD: ("refresh", "retry_upload", "download_excel", "mark_manual_uploaded"),
CP_UPLOAD_RESULT_UNKNOWN: ("refresh", "download_excel", "mark_manual_uploaded"),
CP_READY_MATCH: ("match_inventory",),
CP_READY_EXPORT: ("generate_excel",),
CP_EXPORT_READY: ("download_excel", "mark_manual_uploaded"),
@@ -355,6 +358,11 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
checkpoint=CP_UPLOAD_FAILED,
human_options=list(CHECKPOINT_REGISTRY[CP_UPLOAD_FAILED]),
)
if reason == PH_UPLOAD_RESULT_UNKNOWN:
return TaskUiState(
checkpoint=CP_UPLOAD_RESULT_UNKNOWN,
human_options=list(CHECKPOINT_REGISTRY[CP_UPLOAD_RESULT_UNKNOWN]),
)
if reason == PH_RPA_PENDING or (
task.process_status == "waiting_inventory" and reason == PH_RPA_PENDING
):
@@ -15,7 +15,7 @@ from typing import Any
from app.models import ShippingNoticeCandidate, ShippingTask
from app.services.shipping_notice.constants import PH_RSV_REQ
from app.services.shipping_notice.po_number import normalize_po_number
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
from app.services.shipping_notice.reservation_gate import reservation_gate_issues, task_reservation_gate_issues
from app.services.shipping_notice.reservation_id import (
is_valid_reservation_id,
validated_reservation_id,
@@ -41,6 +41,13 @@ RECONCILE_FIELDS: tuple[str, ...] = (
)
def _reconciliation_reservation_issues(task: ShippingTask) -> list[dict[str, Any]]:
"""回填旧任务时以当前已接受订单字段投影状态;下游履约仍强制冻结 Snapshot。"""
if task.order_snapshot_id:
return task_reservation_gate_issues(task)
return reservation_gate_issues(current_line_field_values(task))
def _normalized_qty(value: Any) -> str:
"""数量稳定比较值。"""
try:
@@ -307,7 +314,7 @@ def apply_candidate_reconciliation_plan(
],
)
open_rows = list_open_field_conflicts(task)
issues = task_reservation_gate_issues(task)
issues = _reconciliation_reservation_issues(task)
step_payload = dict(task.step_payload_json or {})
step_payload['parse_validation'] = {
'status': 'needs_review',
@@ -345,7 +352,7 @@ def apply_candidate_reconciliation_plan(
'updated_line_indexes': [],
}
issues = task_reservation_gate_issues(task)
issues = _reconciliation_reservation_issues(task)
open_rows = list_open_field_conflicts(task)
step_payload = dict(task.step_payload_json or {})
step_payload['parse_validation'] = {
@@ -77,7 +77,7 @@ def current_order_field_display(task: ShippingTask) -> dict[str, Any]:
"""按当前字段目录顺序展示锁定 Schema 字段,历史缺失字段回退版本 sequence。"""
extraction = _current_extraction(task)
global_sequences = {
field.id: int(field.display_sequence or 0)
str(field.field_code): int(field.display_sequence or 0)
for field in ShippingOrderField.query.filter_by(schema_id=extraction.schema_version.schema_id).all()
}
fields = sorted(
@@ -86,7 +86,7 @@ def current_order_field_display(task: ShippingTask) -> dict[str, Any]:
if item.get('enabled', True)
],
key=lambda item: (
global_sequences.get(str(item.get('field_id')), 1_000_000 + int(item.get('sequence') or 0)),
global_sequences.get(str(item.get('field_code')), 1_000_000 + int(item.get('sequence') or 0)),
int(item.get('sequence') or 0),
str(item.get('field_code') or ''),
),
@@ -26,6 +26,7 @@ from app.services.shipping_notice.constants import (
CP_RSV_REQ,
CP_UPLOADED,
CP_UPLOAD_FAILED,
CP_UPLOAD_RESULT_UNKNOWN,
CP_UPLOAD_REQ,
CP_WAITING_UPLOAD,
PH_INV_UNAVAIL,
@@ -88,6 +89,7 @@ _BLOCKED_CHECKPOINTS = {
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_UPLOAD_REQ,
CP_UPLOAD_FAILED,
CP_UPLOAD_RESULT_UNKNOWN,
}
@@ -50,9 +50,13 @@ def start_rpa_attempt(task: ShippingTask, *, artifact_id: int | None = None, ide
if existing is not None:
if existing.artifact_id != artifact.id:
raise ConflictError('Idempotency key belongs to another artifact', code='SHIPPING.UPLOAD_ATTEMPT_CONFLICT')
if existing.status == 'timed_out':
raise ConflictError('Upload result is unknown and must be reconciled before retry', code='SHIPPING.UPLOAD_RESULT_UNKNOWN')
return existing
if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='succeeded').first():
raise ConflictError('Artifact has already been uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED')
if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='timed_out').first():
raise ConflictError('Upload result is unknown and must be reconciled before retry', code='SHIPPING.UPLOAD_RESULT_UNKNOWN')
attempt_no = (db.session.query(ShippingUploadAttempt).filter_by(artifact_id=artifact.id).count() + 1)
attempt = ShippingUploadAttempt(
artifact_id=artifact.id, attempt_no=attempt_no, mode='rpa', idempotency_key=key,
@@ -96,7 +100,7 @@ def complete_attempt(
raise ValidationError('Upload artifact is missing', code='SHIPPING.UPLOAD_ARTIFACT_REQUIRED')
if attempt.status == 'succeeded' or artifact.status == 'uploaded':
raise ConflictError('Late callback cannot overwrite uploaded artifact', code='SHIPPING.UPLOAD_CALLBACK_STALE')
if attempt.status not in {'pending', 'running'}:
if attempt.status not in {'pending', 'running', 'timed_out'}:
raise ConflictError('Callback is not valid for this attempt', code='SHIPPING.UPLOAD_CALLBACK_STALE')
attempt.callback_id = callback
attempt.finished_at = datetime.utcnow()
@@ -115,6 +119,13 @@ def complete_attempt(
task.freight_ref_no = attempt.freight_ref_no
_aggregate_task_upload_status(task)
else:
# A missing callback may conceal a completed freight submission. A late
# transport error is not enough to safely release or retry that Artifact.
if attempt.status == 'timed_out' and not str(error_message or '').strip().lower().startswith('freight_rejected:'):
attempt.error_code = 'UPLOAD_RESULT_UNKNOWN'
attempt.error_message = str(error_message or 'Upload result remains unknown')[:500]
db.session.flush()
return attempt
attempt.status = 'failed'
message = str(error_message or 'RPA upload failed')[:500]
attempt.error_code = 'FREIGHT_REJECTED' if str(error_message or '').strip().lower().startswith('freight_rejected:') else 'RPA_UPLOAD_FAILED'
@@ -126,6 +137,18 @@ def complete_attempt(
return attempt
def mark_attempt_result_unknown(attempt: ShippingUploadAttempt) -> ShippingUploadAttempt:
"""超时后冻结 Artifact;仅迟到成功回调或货代明确拒绝才能解除未知结果。"""
if attempt.status != 'running':
return attempt
attempt.status = 'timed_out'
attempt.finished_at = datetime.utcnow()
attempt.error_code = 'UPLOAD_RESULT_UNKNOWN'
attempt.error_message = 'RPA callback timed out; freight submission must be reconciled before retry'
db.session.flush()
return attempt
def record_manual_upload(task: ShippingTask, *, artifact_id: int | None, evidence_asset_no: str, operator_id: int, freight_ref_no: str | None = None) -> ShippingUploadAttempt:
"""登记人工上传成功;必须持有当前用户已上传的私有截图或回执资产。"""
asset_no = str(evidence_asset_no or '').strip()