feat(shipping-notice): 落地 XFA 统一视觉拆分确认门禁与处理投影收敛

闭合拆分预览令牌单次消费、样本 checksum 绑定与确认审计;正式提取改为 bindings-only。
同步统一标注工作台交互,并补齐进度投影/任务中心与迁移文档。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-08-06 10:21:25 +08:00
1 parent d2b3d74def
commit 84a881b554
195 files changed
+20269 -3463

No files matched your search

@@ -2,9 +2,10 @@
backend/app/services/shipping_notice/document_layout/lifecycle.py
用途:管理 ShippingOrderDocument 的版面版本、checksum、大小门禁和当前成功快照。
依赖:ShippingDocumentLayoutVersion、Flask 配置、SQLAlchemy Session、workflow_ledger_service
依赖:ShippingDocumentLayoutVersion、ShippingXfaStructureAnalysis、Flask 配置、SQLAlchemy Session、workflow_ledger_service
(claim/complete/recovery 尽力同步 WorkflowItem,缺 Item 不阻断版面收口)。
逻辑:相同内容/parser/checksum 幂等复用;失败版本保留审计,只有可用终态更新 Document 当前引用。
逻辑:相同内容/parser/checksum 幂等复用;XFA 复用时同步本地化结构分析身份;
失败版本保留审计,只有可用终态更新 Document 当前引用。
"""
from __future__ import annotations
@@ -20,7 +21,12 @@ from flask import current_app
from sqlalchemy import and_, func, or_, update
from app.extensions import db
from app.models import ShippingDocumentLayoutVersion, ShippingOrderDocument, ShippingOrderIntake
from app.models import (
ShippingDocumentLayoutVersion,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingXfaStructureAnalysis,
)
_LOGGER = logging.getLogger(__name__)
@@ -296,22 +302,93 @@ def _clone_reusable_layout_for_document(
将同一所有者的已完成布局快照本地化到目标 Document。
LayoutVersion 的 document_id 是不可跨文档共享的外键语义;相同内容只能复用
已冻结 payload,不能让目标 Document 指向源 Document 的版本记录。
已冻结 payload,不能让目标 Document 指向源 Document 的版本记录。XFA 快照还必须
为目标 Document 克隆独立 StructureAnalysis,并重写快照 analysis_id;源证据缺失或
身份不一致时返回 None,让调用方重新排队解析。
Args:
document: 待接收复用结果的目标 Document。
reusable: 同一所有者、同内容且 parser 身份一致的源 LayoutVersion。
Returns:
目标 Document 专属 LayoutVersion;无法安全本地化时返回 None。
"""
payload = reusable.payload_json
if not isinstance(payload, dict):
return None
copied_payload = dict(payload)
copied_payload = json.loads(json.dumps(payload, ensure_ascii=True))
copied_payload['status'] = str(reusable.status or copied_payload.get('status') or 'failed')
copied_payload.setdefault('provider', reusable.parser_name or LAYOUT_PARSER_NAME)
copied_payload.setdefault('provider_version', reusable.parser_version)
copied_payload.setdefault('backend', reusable.backend or LAYOUT_BACKEND)
copied_payload.setdefault('snapshot_version', reusable.contract_version or LAYOUT_CONTRACT_VERSION)
return record_inline_layout_snapshot(
target_analysis: ShippingXfaStructureAnalysis | None = None
if str(copied_payload.get('provider') or '') == 'xfa':
capability = (
copied_payload.get('xfa_capability')
if isinstance(copied_payload.get('xfa_capability'), dict)
else {}
)
source_analysis_id = capability.get('structure_analysis_id')
source_analysis = (
db.session.get(ShippingXfaStructureAnalysis, int(source_analysis_id))
if source_analysis_id not in (None, '')
else None
)
if (
source_analysis is None
or int(source_analysis.document_id) != int(reusable.document_id)
or str(source_analysis.analysis_status or '') != 'ready'
or str(source_analysis.source_content_hash or '').lower()
!= str(document.content_hash or '').lower()
or str(source_analysis.template_packet_checksum or '')
!= str(capability.get('template_packet_checksum') or '')
or str(source_analysis.dataset_structure_fingerprint or '')
!= str(capability.get('dataset_structure_fingerprint') or '')
):
return None
# [STEP 1] Analysis 是 document-scoped 证据;克隆安全摘要并先取得目标主键。
target_analysis = ShippingXfaStructureAnalysis(
document_id=int(document.id),
layout_version_id=None,
source_content_hash=str(document.content_hash or '').lower(),
document_kind=source_analysis.document_kind,
analysis_status='ready',
template_packet_checksum=source_analysis.template_packet_checksum,
datasets_packet_checksum=source_analysis.datasets_packet_checksum,
dataset_structure_fingerprint=source_analysis.dataset_structure_fingerprint,
packet_checksums_json=dict(source_analysis.packet_checksums_json or {}),
stats_json=dict(source_analysis.stats_json or {}),
security_summary_json=dict(source_analysis.security_summary_json or {}),
tree_summary_json=dict(source_analysis.tree_summary_json or {}),
error_code=None,
route_reason=source_analysis.route_reason,
encrypted_snapshot_ref=None,
parser_identity=source_analysis.parser_identity,
contract_version=source_analysis.contract_version,
finished_at=datetime.utcnow(),
)
db.session.add(target_analysis)
db.session.flush()
capability['structure_analysis_id'] = int(target_analysis.id)
copied_payload['xfa_capability'] = capability
if isinstance(copied_payload.get('capability'), dict):
copied_payload['capability']['structure_analysis_id'] = int(target_analysis.id)
# [STEP 2] 先记录目标 Layout,再反向绑定 Analysis,保持两条证据身份一致。
localized = record_inline_layout_snapshot(
document,
copied_payload,
parser_key=str(reusable.parser_key or current_layout_parser_key()),
)
if target_analysis is not None:
if str(localized.status or '') not in CURRENT_LAYOUT_STATUSES:
db.session.delete(target_analysis)
return None
target_analysis.layout_version_id = int(localized.id)
return localized
def schedule_layout_version(
@@ -1,14 +1,15 @@
"""
backend/app/services/shipping_notice/document_layout/xfa_acroform.py
用途:读取 AcroForm 字段值并生成与 datasets 叶子节点的对账候选。
依赖:pypdf、xfa_dataset.XfaDatasetAnalysis。
逻辑:由 xfa_analysis / xfa_validation 调用;按短名聚合多实例值供行对齐对账;
此处只做候选与分组,不因 display formatting 差异判失败。
用途:读取 AcroForm 字段值/Widget 几何,并生成与 datasets 叶子节点的对账与路径候选。
依赖:pypdf、xfa_dataset.XfaDatasetAnalysis、xfa_contract.hash_data_path。
逻辑:由 xfa_analysis、xfa_visual_binding、xfa_validation 调用;按短名聚合多实例值
供行对齐对账;Widget 摘要含页码与归一化 bbox,供统一视觉绑定评分。
"""
from __future__ import annotations
import hashlib
import re
import unicodedata
from dataclasses import dataclass
@@ -16,9 +17,14 @@ from io import BytesIO
from typing import Any
from pypdf import PdfReader
from pypdf.generic import ArrayObject
from app.services.shipping_notice.document_layout.xfa_contract import hash_data_path
from app.services.shipping_notice.document_layout.xfa_dataset import XfaDatasetAnalysis, mask_value_for_dto
from app.services.shipping_notice.document_layout.xfa_dataset import (
XfaDatasetAnalysis,
_path_id_for,
mask_value_for_dto,
)
@dataclass
@@ -31,6 +37,19 @@ class XfaAcroformField:
value_masked: str
@dataclass
class XfaAcroformWidget:
"""可定位 AcroForm Widget 摘要:页码、归一化 bbox、SOM/短名与展示值。"""
widget_id: str
qualified_name: str
short_name: str
page_no: int
normalized_bbox: dict[str, float]
value: str
value_masked: str
@dataclass
class XfaReconciliationCandidate:
"""datasets 叶子与 AcroForm 字段的对账候选。"""
@@ -78,6 +97,271 @@ def _normalize_key(value: str) -> str:
return re.sub(r'[^a-z0-9]+', '', text)
def _widget_id_for(qualified_name: str, page_no: int) -> str:
"""生成 Widget 稳定 ID(不含 SOM 明文外传)。"""
digest = hashlib.sha256(f'{qualified_name}:{page_no}'.encode('utf-8')).hexdigest()[:20]
return f'wgt-{digest}'
def _pdf_rect_to_normalized_bbox(
rect: ArrayObject | list[Any],
*,
page_width: float,
page_height: float,
) -> dict[str, float] | None:
"""
将 PDF /Rect(左下原点)转为页面相对框(左上原点,0..1)。
Args:
rect: PDF Rect 数组 [x0, y0, x1, y1]。
page_width: 页宽(pt)。
page_height: 页高(pt)。
Returns:
归一化 bbox;非法或零面积时返回 None。
"""
if page_width <= 0 or page_height <= 0:
return None
try:
x0, y0, x1, y1 = [float(item) for item in rect[:4]]
except (TypeError, ValueError, IndexError):
return None
norm_x0 = max(0.0, min(1.0, x0 / page_width))
norm_x1 = max(0.0, min(1.0, x1 / page_width))
norm_y0 = max(0.0, min(1.0, 1.0 - (y1 / page_height)))
norm_y1 = max(0.0, min(1.0, 1.0 - (y0 / page_height)))
if norm_x1 <= norm_x0 or norm_y1 <= norm_y0:
return None
return {'x0': norm_x0, 'y0': norm_y0, 'x1': norm_x1, 'y1': norm_y1}
def _field_display_value(field_obj: dict[str, Any]) -> str:
"""从 AcroForm 字段字典读取 /V 展示值。"""
value = field_obj.get('/V')
if value is None:
return ''
return str(getattr(value, 'name', value) or value).strip()
def _resolve_widget_page_no(reader: PdfReader, annot_obj: dict[str, Any], fallback_page_no: int) -> int:
"""
解析 Widget 所属页码。
核心逻辑:优先读 /P 页引用;否则使用遍历页码。
"""
page_ref = annot_obj.get('/P')
if page_ref is not None:
for index, page in enumerate(reader.pages):
if page.indirect_reference == page_ref:
return index + 1
return int(fallback_page_no)
def read_acroform_widgets(pdf_bytes: bytes) -> list[XfaAcroformWidget]:
"""
读取 PDF AcroForm Widget 页码、归一化 bbox、SOM/短名与展示值。
核心逻辑:遍历每页 /Annots 中 /Subtype=/Widget;补充 get_fields 中带 /Rect 的字段;
坐标转为 0..1 左上原点,与 PDFium 渲染画布一致。
Args:
pdf_bytes: 原始 PDF 字节。
Returns:
可定位 Widget 列表;无 Widget 或解析失败时返回空列表。
"""
try:
reader = PdfReader(BytesIO(pdf_bytes), strict=False)
except Exception:
return []
seen: set[tuple[str, int]] = set()
widgets: list[XfaAcroformWidget] = []
# [STEP 1] 页面 Widget 注解(含几何)
for page_index, page in enumerate(reader.pages):
page_no = page_index + 1
try:
width = float(page.mediabox.width)
height = float(page.mediabox.height)
except (TypeError, ValueError, AttributeError):
continue
annots = page.get('/Annots')
if not annots:
continue
for annot_ref in annots:
try:
annot_obj = annot_ref.get_object()
except Exception:
continue
if not isinstance(annot_obj, dict):
continue
subtype = str(annot_obj.get('/Subtype') or '')
if subtype != '/Widget':
continue
rect = annot_obj.get('/Rect')
if rect is None:
continue
bbox = _pdf_rect_to_normalized_bbox(rect, page_width=width, page_height=height)
if bbox is None:
continue
qualified_name = str(annot_obj.get('/T') or annot_obj.get('/TM') or '').strip()
if not qualified_name:
parent = annot_obj.get('/Parent')
if parent is not None:
try:
parent_obj = parent.get_object()
if isinstance(parent_obj, dict):
qualified_name = str(parent_obj.get('/T') or '').strip()
except Exception:
qualified_name = ''
if not qualified_name:
qualified_name = f'widget.page{page_no}.{len(widgets)}'
short_name = _local_tail(qualified_name)
value = _field_display_value(annot_obj)
key = (qualified_name, page_no)
if key in seen:
continue
seen.add(key)
widgets.append(XfaAcroformWidget(
widget_id=_widget_id_for(qualified_name, page_no),
qualified_name=qualified_name,
short_name=short_name,
page_no=page_no,
normalized_bbox=bbox,
value=value,
value_masked=mask_value_for_dto(value),
))
# [STEP 2] get_fields 补充(部分 XFA 仅在此暴露 /Rect)
try:
raw_fields = reader.get_fields() or {}
except Exception:
raw_fields = {}
for qualified_name, field_obj in raw_fields.items():
if not isinstance(field_obj, dict):
continue
rect = field_obj.get('/Rect')
if rect is None:
continue
page_no = _resolve_widget_page_no(reader, field_obj, fallback_page_no=1)
try:
page = reader.pages[page_no - 1]
width = float(page.mediabox.width)
height = float(page.mediabox.height)
except (IndexError, TypeError, ValueError, AttributeError):
continue
bbox = _pdf_rect_to_normalized_bbox(rect, page_width=width, page_height=height)
if bbox is None:
continue
qname = str(qualified_name)
key = (qname, page_no)
if key in seen:
continue
value = _field_display_value(field_obj)
if not value:
continue
seen.add(key)
short_name = _local_tail(qname)
widgets.append(XfaAcroformWidget(
widget_id=_widget_id_for(qname, page_no),
qualified_name=qname,
short_name=short_name,
page_no=page_no,
normalized_bbox=bbox,
value=value,
value_masked=mask_value_for_dto(value),
))
return widgets
def serialize_locatable_widget_summaries(widgets: list[XfaAcroformWidget]) -> list[dict[str, Any]]:
"""
序列化可定位 Widget 轻量摘要(分析快照用,不含展示值明文)。
Args:
widgets: Widget 列表。
Returns:
含 widget_id、page_no、bbox、short_name、has_value 的摘要列表。
"""
return [
{
'widget_id': item.widget_id,
'page_no': int(item.page_no),
'short_name': item.short_name,
'normalized_bbox': dict(item.normalized_bbox),
'has_value': bool(item.value),
}
for item in widgets
]
def build_widget_path_candidates(
*,
widget: XfaAcroformWidget,
dataset_analysis: XfaDatasetAnalysis,
) -> list[dict[str, Any]]:
"""
为单个 Widget 生成 datasets 路径候选(供视觉绑定评分)。
核心逻辑:按 localName / 规范化短名弱匹配叶子;多命中标记 ambiguous;
返回值供内部评分,DTO 仅含 masked 值与 path hash。
Args:
widget: AcroForm Widget 摘要。
dataset_analysis: datasets 结构分析。
Returns:
路径候选列表,按 match_hint 质量降序。
"""
by_short: dict[str, list[tuple[str, str]]] = {}
by_norm: dict[str, list[tuple[str, str]]] = {}
for data_path, raw_value in dataset_analysis.leaf_values_by_path.items():
local_name = data_path.rsplit('/', 1)[-1]
by_short.setdefault(local_name.upper(), []).append((data_path, raw_value))
by_norm.setdefault(_normalize_key(local_name), []).append((data_path, raw_value))
matches: list[dict[str, Any]] = []
short_key = str(widget.short_name or '').upper()
exact = by_short.get(short_key) or []
if len(exact) == 1:
data_path, raw_value = exact[0]
matches.append(_path_candidate_row(data_path, raw_value, match_hint='local_name_exact'))
elif len(exact) > 1:
for data_path, raw_value in exact:
matches.append(_path_candidate_row(data_path, raw_value, match_hint='local_name_ambiguous'))
else:
fuzzy = by_norm.get(_normalize_key(widget.short_name)) or []
if len(fuzzy) == 1:
data_path, raw_value = fuzzy[0]
matches.append(_path_candidate_row(data_path, raw_value, match_hint='normalized_exact'))
elif len(fuzzy) > 1:
for data_path, raw_value in fuzzy:
matches.append(_path_candidate_row(data_path, raw_value, match_hint='normalized_ambiguous'))
hint_rank = {
'local_name_exact': 4,
'normalized_exact': 3,
'local_name_ambiguous': 2,
'normalized_ambiguous': 1,
}
matches.sort(key=lambda item: hint_rank.get(str(item.get('match_hint') or ''), 0), reverse=True)
return matches
def _path_candidate_row(data_path: str, raw_value: str, *, match_hint: str) -> dict[str, Any]:
"""构造单条路径候选内部行。"""
return {
'path_id': _path_id_for(data_path),
'data_path_hash': hash_data_path(data_path),
'dataset_value_masked': mask_value_for_dto(raw_value),
'raw_value': raw_value,
'match_hint': match_hint,
}
def read_acroform_fields(pdf_bytes: bytes) -> list[XfaAcroformField]:
"""
读取 PDF AcroForm 字段值。
@@ -19,7 +19,9 @@ from app.models import ShippingXfaStructureAnalysis
from app.services.shipping_notice.document_layout.xfa_acroform import (
build_reconciliation_candidates,
read_acroform_fields,
read_acroform_widgets,
serialize_acroform_fields,
serialize_locatable_widget_summaries,
)
from app.services.shipping_notice.document_layout.xfa_contract import (
XFA_CONTRACT_VERSION,
@@ -157,10 +159,12 @@ def analyze_xfa_pdf(
dataset_nodes=dataset_analysis.nodes,
)
acroform_fields = read_acroform_fields(pdf_bytes)
acroform_widgets = read_acroform_widgets(pdf_bytes)
reconciliation = build_reconciliation_candidates(
dataset_analysis=dataset_analysis,
acroform_fields=acroform_fields,
)
widget_summaries = serialize_locatable_widget_summaries(acroform_widgets)
packet_checksums = {item.name: item.checksum for item in packet_result.packets}
capability = {
'parser_identity': XFA_PARSER_IDENTITY,
@@ -180,6 +184,8 @@ def analyze_xfa_pdf(
'header_candidate_count': len(dataset_analysis.header_candidates),
'collection_candidate_count': len(dataset_analysis.collection_candidates),
'acroform_field_count': len(acroform_fields),
'locatable_widget_count': len(acroform_widgets),
'widget_summaries': widget_summaries[:200],
'reconciliation_candidate_count': len(reconciliation),
'issues': [],
}
@@ -1,14 +1,16 @@
"""
services/shipping_notice/document_layout/xfa_contract.py
用途:冻结 XFA 数据路径 Profile 的阶段 0 契约——template_mode、受控路径语法、
结构指纹算法、资源上限、支持/拒绝矩阵、鉴别联合 definition、evidence 与安全投影。
用途:冻结 XFA 数据路径 Profile 契约——template_mode、受控路径语法、结构指纹、
统一字段 binding(value_binding + visual_binding)、鉴别联合 definition、
evidence 与安全投影。
依赖:Pydantic 2、标准库 hashlib/json/re/unicodedata;被 order_extraction_route_contract、
error_explainability_contract、Profile 校验与后续 xfa_*.py 解析器引用。
Profile 校验、拆分契约与后续 xfa_*.py 解析器引用。
逻辑:本模块只定义契约与纯函数校验,不读 PDF/XML、不执行脚本、不接正式流量;
coordinate 行为保持不变,xfa_dataset 定义不得混入坐标 region。
禁止混入 coordinate 表区键,但允许 visual_binding 归一化框作为视觉证据。
header_mappings / line_mapping.fields 仅作**迁移输入**解析(order_profile_unified_migration);
正式 validate/save/extract 须 bindings-only,legacy-only 或 dual-source 均 fail-closed。
"""
from __future__ import annotations
import hashlib
@@ -167,6 +169,15 @@ XFA_ROUTE_REASON_CODES: Final[frozenset[str]] = frozenset({
'xfa_split_rule_invalid',
'xfa_split_field_conflict',
'xfa_split_mirror_mismatch',
# 统一视觉绑定 / 发布门禁 / 运行时再验(阶段 5–6)
'xfa_visual_bindings_required',
'xfa_visual_binding_incomplete',
'xfa_visual_coverage_insufficient',
'xfa_evidence_retention_insufficient',
'xfa_mirror_consistency_insufficient',
'xfa_profile_checksum_mismatch',
'xfa_visual_not_publishable',
'xfa_split_rule_unconfirmed',
})
XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
@@ -193,10 +204,16 @@ XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
'xfa_cross_check_completed',
'xfa_structure_signature_frozen',
'xfa_audit_snapshot_viewed',
# 统一视觉绑定(阶段 2)
'xfa_visual_binding_suggested',
'xfa_visual_binding_confirmed',
'xfa_visual_binding_rejected',
'xfa_visual_binding_updated',
# 字段拆分映射审计(阶段 3/7)
'xfa_split_rule_suggested',
'xfa_split_rule_previewed',
'xfa_split_rule_validated',
'xfa_split_rule_confirmed',
'xfa_split_segment_created',
'xfa_split_segment_updated',
'xfa_split_segment_deleted',
@@ -208,6 +225,9 @@ XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
'xfa_profile_published',
'xfa_profile_formal_extracted',
'xfa_profile_needs_review',
# 统一 binding 一次性迁移(阶段 7)
'order_profile_unified_migration_dry_run',
'order_profile_unified_migration_executed',
})
# Profile / Run / 分析 DTO 禁止键(大小写不敏感);完整 XML / PDF bytes / 存储地址不得外泄。
@@ -294,7 +314,12 @@ class XfaSourceContract(XfaContractModel):
class XfaHeaderMapping(XfaContractModel):
"""Header 字段:Schema field ↔ 受控 datasets 路径。"""
"""
Header 字段:Schema field ↔ 受控 datasets 路径。
**迁移输入兼容**:仅供 unified migration 读取旧 definition;正式 save/validate/extract
禁止单独依赖本结构,须先 Execute 迁移为 bindings[]。
"""
mapping_id: str = Field(min_length=1, max_length=64)
field_id: str = Field(min_length=1, max_length=64)
@@ -313,7 +338,11 @@ class XfaHeaderMapping(XfaContractModel):
class XfaLineFieldMapping(XfaContractModel):
"""明细行字段映射。"""
"""
明细行字段映射。
**迁移输入兼容**:见 XfaHeaderMapping;正式路径禁止 legacy-only。
"""
mapping_id: str = Field(min_length=1, max_length=64)
field_id: str = Field(min_length=1, max_length=64)
@@ -332,7 +361,12 @@ class XfaLineFieldMapping(XfaContractModel):
class XfaLineMapping(XfaContractModel):
"""权威明细集合路径及行内字段映射。"""
"""
权威明细集合路径及行内字段映射。
row_path 为正式契约必填;fields 列表为**迁移输入兼容**(同 header_mappings),
Execute 后须为空,正式值绑定仅经 bindings[]。
"""
row_path: str = Field(min_length=1, max_length=512)
fields: list[XfaLineFieldMapping] = Field(default_factory=list)
@@ -353,25 +387,166 @@ class XfaCrossChecks(XfaContractModel):
total_amount_policy: XfaTotalAmountPolicy = 'must_equal_line_sum'
# ---------------------------------------------------------------------------
# 统一字段绑定(value_binding + visual_binding)
# ---------------------------------------------------------------------------
XfaValueBindingType = Literal['xfa_dataset', 'pdf_coordinate', 'ocr_coordinate']
XfaVisualBindingSource = Literal[
'acroform_widget',
'manual_draw',
'migrated_coordinate',
'suggested',
]
XfaVisualBindingStatus = Literal['suggested', 'confirmed', 'rejected', 'unavailable']
XfaBindingScope = Literal['header', 'line']
class XfaNormalizedBBox(XfaContractModel):
"""页面相对坐标框(0..1);仅作视觉证据,不作 XFA 正式取值来源。"""
x0: float = Field(ge=0.0, le=1.0)
y0: float = Field(ge=0.0, le=1.0)
x1: float = Field(ge=0.0, le=1.0)
y1: float = Field(ge=0.0, le=1.0)
@model_validator(mode='after')
def validate_positive_area(self) -> 'XfaNormalizedBBox':
"""框必须正面积且不倒置。"""
if self.x1 <= self.x0 or self.y1 <= self.y0:
raise ValueError('normalized_bbox must have positive area')
return self
class XfaValueBinding(XfaContractModel):
"""正式值绑定:XFA 仅允许 datasets 路径;普通 PDF 允许坐标/OCR。"""
type: XfaValueBindingType
path_id: str | None = Field(default=None, max_length=128)
data_path: str | None = Field(default=None, max_length=512)
region_id: str | None = Field(default=None, max_length=64)
@model_validator(mode='after')
def validate_by_type(self) -> 'XfaValueBinding':
"""
按类型校验必填字段。
XFA:必须 path_id + data_path;坐标类:必须 region_id。
"""
if self.type == 'xfa_dataset':
if not self.path_id or not self.data_path:
raise ValueError('xfa_dataset value_binding requires path_id and data_path')
validate_controlled_data_path(self.data_path)
if self.region_id:
raise ValueError('xfa_dataset value_binding must not set region_id')
else:
if not self.region_id:
raise ValueError(f'{self.type} value_binding requires region_id')
if self.path_id or self.data_path:
raise ValueError(f'{self.type} value_binding must not set XFA path fields')
return self
class XfaVisualBinding(XfaContractModel):
"""视觉绑定:页码 + 归一化框 + 确认状态;正式字段发布前须 confirmed。"""
page_no: int = Field(ge=1, le=500)
normalized_bbox: XfaNormalizedBBox
source: XfaVisualBindingSource
status: XfaVisualBindingStatus
confidence: float = Field(default=1.0, ge=0.0, le=1.0)
class XfaSplitRuleRef(XfaContractModel):
"""字段对拆分段的引用;未拆分字段可省略。"""
rule_set_id: str = Field(min_length=8, max_length=64)
segment_id: str = Field(min_length=8, max_length=64)
class XfaUnifiedFieldBinding(XfaContractModel):
"""
统一字段绑定:同一 Schema 字段在同一作用域最多一个正式来源。
核心逻辑:value_binding 决定正式取值;visual_binding 决定页面证据;
split_rule_ref 可选指向已确认拆分段。
"""
binding_id: str = Field(min_length=8, max_length=64)
field_id: str = Field(min_length=1, max_length=64)
field_code: str = Field(min_length=1, max_length=128)
scope: XfaBindingScope
value_binding: XfaValueBinding
visual_binding: XfaVisualBinding
split_rule_ref: XfaSplitRuleRef | None = None
@model_validator(mode='after')
def validate_xfa_scope_value_type(self) -> 'XfaUnifiedFieldBinding':
"""XFA Profile 内正式绑定必须是 xfa_dataset(由上层 Profile 再强制)。"""
return self
def is_formal_binding_publishable(binding: XfaUnifiedFieldBinding) -> bool:
"""
判断统一绑定是否满足发布门禁的视觉确认要求。
Args:
binding: 统一字段绑定。
Returns:
视觉状态为 confirmed 时为 True。
"""
return binding.visual_binding.status == 'confirmed'
def canonical_unified_bindings_payload(
bindings: list[XfaUnifiedFieldBinding] | list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""
生成统一 binding 的 canonical JSON 列表(供 checksum)。
Args:
bindings: 模型列表或已 dump 的字典列表。
Returns:
按 binding_id 排序的稳定字典列表。
"""
items: list[dict[str, Any]] = []
for raw in bindings or []:
if isinstance(raw, XfaUnifiedFieldBinding):
items.append(raw.model_dump(mode='json'))
elif isinstance(raw, dict):
items.append(XfaUnifiedFieldBinding.model_validate(raw).model_dump(mode='json'))
else:
raise ValueError('bindings must be XfaUnifiedFieldBinding or dict')
return sorted(items, key=lambda item: str(item.get('binding_id') or ''))
class OrderXfaDatasetProfile(XfaContractModel):
"""
xfa_dataset 模式的鉴别联合 definition。
核心逻辑:仅允许 XFA 映射字段;显式拒绝 coordinate 的 table_regions /
order_field_layouts 等键混入;可选 split_rules 声明式多行拆分。
核心逻辑:header_mappings / line_mapping.fields 仅迁移输入(须 bindings-only 正式运行);
validate 拒绝 legacy-only 与 dual-source;拒绝 coordinate 表区键;可选 split_rules。
"""
template_mode: Literal['xfa_dataset'] = 'xfa_dataset'
source_contract: XfaSourceContract
# 迁移输入兼容:禁止正式运行时单独携带非空 legacy mappings(须 bindings-only)。
header_mappings: list[XfaHeaderMapping] = Field(default_factory=list)
line_mapping: XfaLineMapping
bindings: list[XfaUnifiedFieldBinding] = Field(default_factory=list)
cross_checks: XfaCrossChecks = Field(default_factory=XfaCrossChecks)
split_rules: list[dict[str, Any]] = Field(default_factory=list)
@model_validator(mode='before')
@classmethod
def reject_coordinate_keys(cls, data: Any) -> Any:
"""拒绝 coordinate region / layout 键混入 XFA definition。"""
"""
拒绝 coordinate 表区 / layout 键混入 XFA definition。
注意:不拒绝 visual_binding / normalized_bbox(统一绑定的视觉证据)。
"""
if not isinstance(data, dict):
return data
forbidden = {
@@ -396,7 +571,7 @@ class OrderXfaDatasetProfile(XfaContractModel):
@model_validator(mode='after')
def validate_unique_bindings(self) -> 'OrderXfaDatasetProfile':
"""同一 Schema 字段与同一 mapping_id 不得重复绑定;校验 split_rules 契约。"""
"""同一 Schema 字段与同一 mapping/binding id 不得重复;校验 split_rules 与 bindings。"""
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
parse_split_rule_sets,
)
@@ -409,18 +584,40 @@ class OrderXfaDatasetProfile(XfaContractModel):
for item in self.line_mapping.fields:
field_ids.append(item.field_id)
mapping_ids.append(item.mapping_id)
binding_ids: list[str] = []
binding_field_keys: list[tuple[str, str]] = []
for binding in self.bindings:
if binding.value_binding.type != 'xfa_dataset':
raise ValueError('OrderXfaDatasetProfile bindings must use value_binding.type=xfa_dataset')
binding_ids.append(binding.binding_id)
binding_field_keys.append((binding.scope, binding.field_id))
field_ids.append(binding.field_id)
if len(binding_ids) != len(set(binding_ids)):
raise ValueError('duplicate binding_id values are not allowed')
if len(binding_field_keys) != len(set(binding_field_keys)):
raise ValueError('duplicate Schema field_id bindings in the same scope are not allowed')
rule_sets = parse_split_rule_sets(self.split_rules)
for rule_set in rule_sets:
for rule in rule_set.rules:
if rule.segment.handling == 'mapped' and rule.segment.target_field_id:
field_ids.append(rule.segment.target_field_id)
has_legacy_mappings = bool(self.header_mappings) or bool(self.line_mapping.fields)
if self.bindings and has_legacy_mappings:
raise ValueError(
'xfa_dual_binding_source: bindings cannot coexist with '
'header_mappings or line_mapping.fields',
)
if has_legacy_mappings and not self.bindings:
raise ValueError(
'xfa_legacy_mappings_forbidden: header_mappings / line_mapping.fields are '
'migration input only; formal runtime requires bindings[] — run unified migration first',
)
if len(field_ids) != len(set(field_ids)):
raise ValueError('duplicate Schema field_id bindings are not allowed')
if len(mapping_ids) != len(set(mapping_ids)):
raise ValueError('duplicate mapping_id values are not allowed')
if self.line_mapping.row_path != self.source_contract.authoritative_line_collection_path:
raise ValueError('line_mapping.row_path must equal authoritative_line_collection_path')
# 回写规范化后的 split_rules(model_dump 形状)。
object.__setattr__(
self,
'split_rules',
@@ -603,7 +800,11 @@ def compute_dataset_structure_fingerprint(
def validate_xfa_dataset_definition(payload: dict[str, Any] | OrderXfaDatasetProfile) -> OrderXfaDatasetProfile:
"""
将字典校验为 OrderXfaDatasetProfile。
将字典校验为 OrderXfaDatasetProfile(正式路径:bindings-only)。
核心逻辑:normalize 后若仅有 legacy mappings 无 bindings → ValidationError
(xfa_legacy_mappings_forbidden);与提取 fail-closed 一致。迁移读入旧字段请直接用
dict + order_profile_unified_migration,勿经本函数校验 legacy-only 输入。
Args:
payload: 原始 definition 或已构造模型。
@@ -612,7 +813,7 @@ def validate_xfa_dataset_definition(payload: dict[str, Any] | OrderXfaDatasetPro
通过鉴别联合与路径语法校验的模型。
Raises:
pydantic.ValidationError / ValueError: 契约不合法。
pydantic.ValidationError / ValueError: 契约不合法或 legacy-only。
"""
if isinstance(payload, OrderXfaDatasetProfile):
return OrderXfaDatasetProfile.model_validate(payload.model_dump(mode='json'))
@@ -565,7 +565,7 @@ def serialize_tree_node(node: XfaDatasetNode, *, include_values: bool = False) -
Args:
node: 数据集树节点。
include_values: 是否包含脱敏样本值。
include_values: 是否包含当前管理端使用的完整样本值。
Returns:
安全 DTO 字典。
@@ -583,11 +583,10 @@ def serialize_tree_node(node: XfaDatasetNode, *, include_values: bool = False) -
'children': [serialize_tree_node(child, include_values=include_values) for child in node.children],
}
if include_values and node.is_leaf:
payload['sample_value_masked'] = node.sample_value_masked or ''
payload['sample_value_display'] = node.sample_value_display or ''
payload['display_policy'] = node.display_policy
payload['can_reveal'] = bool(node.can_reveal)
# 仅暴露行数,不返回 lines 原文(完整值走受控 reveal)。
payload['sample_value_masked'] = str(node.raw_value or '')
payload['sample_value_display'] = str(node.raw_value or '')
payload['display_policy'] = 'full'
payload['can_reveal'] = False
payload['line_count'] = len(node.lines or [])
return payload
@@ -1,12 +1,13 @@
"""
backend/app/services/shipping_notice/document_layout/xfa_profile_extraction.py
用途:按冻结 published XFA Profile 路径映射提取 Header/Lines,并产出安全 evidence refs。
依赖:xfa_contract、xfa_dataset、xfa_split_rule_contract、xfa_split_rule_engine、
order_schema.field_rules、order_profile_extractors、XfaProfileMatchResult。
逻辑:由 order_extraction_workflow XFA 分支在精确命中后调用;失败由上层回退坐标/OCR/通用;
普通结果不含完整 XML / 明文路径;NETPR ``单价 / 价格单位`` 确定性拆分为 unit_price + price_unit;
多行源字段经已确认 split_rules 引擎产出 mapped 字段与 evidence_only 段(非 Schema 字段)。
用途:按冻结 published XFA Profile 统一 bindings[] 提取 Header/Lines,并产出安全 evidence refs。
依赖:xfa_contract(OrderXfaDatasetProfile / XfaUnifiedFieldBinding)、xfa_dataset、
xfa_split_rule_contract、xfa_split_rule_engine、order_schema.field_rules、
order_profile_extractors。
逻辑:由 order_extraction_workflow XFA 分支在精确命中后调用;正式提取仅读 bindings[],
无 bindings 或仍含 header_mappings/line_mapping.fields 时 fail-closed;
类型/normalizer/validator 取自 schema_fields;失败由上层回退坐标/OCR/通用。
"""
from __future__ import annotations
@@ -23,6 +24,7 @@ from app.services.shipping_notice.document_layout.order_profile_extractors impor
from app.services.shipping_notice.document_layout.xfa_contract import (
OrderXfaDatasetProfile,
XfaFieldEvidenceRef,
XfaUnifiedFieldBinding,
XFA_PARSER_IDENTITY,
hash_data_path,
sanitize_xfa_dto,
@@ -76,6 +78,43 @@ class XfaExtractionResult:
evidence_summary: dict[str, Any] = field(default_factory=dict)
def _schema_metadata_for_field(
*,
schema_fields: dict[str, dict[str, Any]],
field_id: str,
field_code: str,
) -> tuple[str, str | None, str | None]:
"""
从 schema_fields 读取 value_type / normalizer / validator。
核心逻辑:bindings 不含类型元数据时,以 Schema 为唯一来源;缺省 string + trim。
Args:
schema_fields: Run 冻结 Schema field_id → 配置。
field_id: Schema 字段 ID。
field_code: 业务 field_code(仅用于缺省回退)。
Returns:
(value_type, normalizer_key, validator_key)。
"""
cfg = schema_fields.get(field_id) or {}
value_type = str(cfg.get('value_type') or 'string')
normalizer_key = str(cfg.get('normalizer_key') or 'trim') or None
validator_keys = list(cfg.get('validator_keys') or [])
validator_key = str(validator_keys[0]) if validator_keys else None
if not cfg and field_code:
_ = field_code
return value_type, normalizer_key, validator_key
def _bindings_for_scope(
profile: OrderXfaDatasetProfile,
scope: str,
) -> list[XfaUnifiedFieldBinding]:
"""按 scope 过滤统一 bindings(header / line)。"""
return [item for item in profile.bindings if str(item.scope) == scope]
def _schema_field_config(
*,
schema_fields: dict[str, dict[str, Any]],
@@ -239,39 +278,45 @@ def _is_formal_ready_split_rule_set(rule_set: XfaSplitRuleSet) -> bool:
def _build_path_id_to_data_path(profile: OrderXfaDatasetProfile) -> dict[str, str]:
"""从 Header/Line 映射构建 path_id → data_path 索引。"""
"""
从 bindings[].value_binding 构建 path_id → data_path 索引。
核心逻辑:正式提取与 split_rules 源路径解析均只读统一 bindings。
"""
mapping: dict[str, str] = {}
for item in profile.header_mappings:
if item.path_id and item.data_path:
mapping[str(item.path_id)] = str(item.data_path)
for item in profile.line_mapping.fields:
if item.path_id and item.data_path:
mapping[str(item.path_id)] = str(item.data_path)
for binding in profile.bindings:
path_id = str(binding.value_binding.path_id or '').strip()
data_path = str(binding.value_binding.data_path or '').strip()
if path_id and data_path:
mapping[path_id] = data_path
return mapping
def _resolve_split_source_data_path(
rule_set: XfaSplitRuleSet,
*,
line_fields: list[Any],
line_bindings: list[XfaUnifiedFieldBinding],
path_id_to_data_path: dict[str, str],
) -> str | None:
"""
解析拆分规则集源字段 data_path。
核心逻辑:优先使用服务端冻结的 source_data_path,其次按 source_path_id 命中映射;
旧定义最后按 data_path 后缀兼容匹配 source_field_code。
核心逻辑:优先使用服务端冻结的 source_data_path,其次按 source_path_id 命中 bindings;
最后按 data_path 后缀兼容匹配 source_field_code。
"""
if rule_set.source_data_path:
return str(rule_set.source_data_path)
path_id = str(rule_set.source_path_id or '')
if path_id in path_id_to_data_path:
return path_id_to_data_path[path_id]
suffix = f'/{rule_set.source_field_code}'
for mapping in line_fields:
data_path = str(getattr(mapping, 'data_path', '') or '')
mapping_path_id = str(getattr(mapping, 'path_id', '') or '')
if mapping_path_id == path_id or data_path.endswith(suffix):
field_code = str(rule_set.source_field_code or '').strip()
if not field_code:
return None
suffix = f'/{field_code}'
for binding in line_bindings:
data_path = str(binding.value_binding.data_path or '')
binding_path_id = str(binding.value_binding.path_id or '')
if binding_path_id == path_id or data_path.endswith(suffix):
return data_path or None
return None
@@ -299,7 +344,7 @@ def _apply_split_rules_for_header(
for rule_set in rule_sets:
data_path = _resolve_split_source_data_path(
rule_set,
line_fields=[],
line_bindings=[],
path_id_to_data_path=path_id_to_data_path,
)
if not data_path:
@@ -360,7 +405,7 @@ def _apply_split_rules_for_row(
*,
row_values: dict[str, str],
rule_sets: list[XfaSplitRuleSet],
line_fields: list[Any],
line_bindings: list[XfaUnifiedFieldBinding],
path_id_to_data_path: dict[str, str],
schema_fields: dict[str, dict[str, Any]],
schema_by_code: dict[str, dict[str, Any]],
@@ -371,6 +416,9 @@ def _apply_split_rules_for_row(
"""
对单行执行已确认拆分规则并产出 Schema 字段值与 evidence_only 段。
Args:
line_bindings: scope=line 的统一 bindings,供源路径后缀回退。
Returns:
(values, split_evidence, produced_field_codes, issues, required_missing)
"""
@@ -383,7 +431,7 @@ def _apply_split_rules_for_row(
for rule_set in rule_sets:
data_path = _resolve_split_source_data_path(
rule_set,
line_fields=line_fields,
line_bindings=line_bindings,
path_id_to_data_path=path_id_to_data_path,
)
if not data_path:
@@ -455,10 +503,11 @@ def extract_xfa_profile(
dataset_structure_fingerprint: str | None = None,
) -> XfaExtractionResult:
"""
按冻结 XFA Profile 提取 Header 与权威明细行。
按冻结 XFA Profile 统一 bindings[] 提取 Header 与权威明细行。
核心逻辑:校验 definition → 读 Header 叶子 → 读权威集合行 → Schema 标准化;
权威集合缺失时 fail-closed(reason=xfa_authoritative_collection_missing)。
核心逻辑:校验 definition → 要求 bindings-only(拒绝 legacy mappings)→
按 scope 迭代 bindings → 读权威集合行 → 从 schema_fields 标准化;
无 bindings → xfa_visual_bindings_required;双源 → xfa_dual_binding_source。
Args:
raw_profile: 冻结 Profile 快照(含 definition / checksum)。
@@ -472,6 +521,30 @@ def extract_xfa_profile(
XfaExtractionResult:含 rows(对齐坐标路径)与安全 evidence_summary。
"""
definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {}
header_mappings = definition.get('header_mappings') if isinstance(definition.get('header_mappings'), list) else []
line_mapping = definition.get('line_mapping') if isinstance(definition.get('line_mapping'), dict) else {}
line_fields = line_mapping.get('fields') if isinstance(line_mapping.get('fields'), list) else []
bindings_raw = definition.get('bindings') if isinstance(definition.get('bindings'), list) else []
has_bindings = bool(bindings_raw)
has_legacy_mappings = bool(header_mappings) or bool(line_fields)
if not has_bindings:
return XfaExtractionResult(
status='failed',
reason_codes=['xfa_visual_bindings_required'],
packet_checksum=packet_checksum,
dataset_structure_fingerprint=dataset_structure_fingerprint,
profile_checksum=str(raw_profile.get('checksum') or '') or None,
)
if has_legacy_mappings:
return XfaExtractionResult(
status='failed',
reason_codes=['xfa_dual_binding_source'],
packet_checksum=packet_checksum,
dataset_structure_fingerprint=dataset_structure_fingerprint,
profile_checksum=str(raw_profile.get('checksum') or '') or None,
)
try:
profile = OrderXfaDatasetProfile.model_validate(definition)
except (TypeError, ValueError):
@@ -489,20 +562,30 @@ def extract_xfa_profile(
if isinstance(item, dict) and item.get('enabled', True) and item.get('field_id')
}
# [STEP 1] Header 映射
# [STEP 0] 正式提取仅允许 bindings-only(已在 model_validate 前 fail-closed)
header_bindings = _bindings_for_scope(profile, 'header')
line_bindings = _bindings_for_scope(profile, 'line')
# [STEP 1] Header bindings
header_fields: list[XfaExtractedField] = []
header_issues: list[str] = []
for mapping in profile.header_mappings:
raw_value = read_dataset_value(dataset_analysis, mapping.data_path)
for binding in header_bindings:
data_path = str(binding.value_binding.data_path or '')
value_type, normalizer_key, validator_key = _schema_metadata_for_field(
schema_fields=schema_fields,
field_id=binding.field_id,
field_code=binding.field_code,
)
raw_value = read_dataset_value(dataset_analysis, data_path)
extracted = _extract_one_field(
raw_value=raw_value,
mapping_id=mapping.mapping_id,
field_id=mapping.field_id,
field_code=mapping.field_code,
data_path=mapping.data_path,
value_type=mapping.value_type,
normalizer_key=mapping.normalizer_key,
validator_key=mapping.validator_key,
mapping_id=binding.binding_id,
field_id=binding.field_id,
field_code=binding.field_code,
data_path=data_path,
value_type=value_type,
normalizer_key=normalizer_key,
validator_key=validator_key,
schema_fields=schema_fields,
document_id=document_id,
packet_checksum=packet_checksum,
@@ -580,7 +663,7 @@ def extract_xfa_profile(
_apply_split_rules_for_row(
row_values=row_values,
rule_sets=line_split_rule_sets,
line_fields=list(profile.line_mapping.fields),
line_bindings=line_bindings,
path_id_to_data_path=path_id_to_data_path,
schema_fields=schema_fields,
schema_by_code=schema_by_code,
@@ -609,38 +692,44 @@ def extract_xfa_profile(
})
pending_price_unit_raw: str | None = None
pending_price_unit_path: str | None = None
for mapping in profile.line_mapping.fields:
if str(mapping.field_code or '') in split_produced_codes:
for binding in line_bindings:
if str(binding.field_code or '') in split_produced_codes:
continue
if str(mapping.path_id or '') in split_source_path_ids:
if str(binding.value_binding.path_id or '') in split_source_path_ids:
continue
raw_value = row_values.get(mapping.data_path)
data_path = str(binding.value_binding.data_path or '')
raw_value = row_values.get(data_path)
extract_raw = raw_value
# [STEP] NETPR 复合值:拆出单价;价格单位若无独立映射则稍后补齐。
if str(mapping.field_code or '') == 'unit_price':
value_type, normalizer_key, validator_key = _schema_metadata_for_field(
schema_fields=schema_fields,
field_id=binding.field_id,
field_code=binding.field_code,
)
# [STEP] NETPR 复合值:拆出单价;价格单位若无独立 binding 则稍后补齐。
if str(binding.field_code or '') == 'unit_price':
composite = parse_unit_price_with_price_unit(
None if raw_value is None else str(raw_value)
)
if composite:
extract_raw = composite['unit_price']
pending_price_unit_raw = composite['price_unit']
pending_price_unit_path = mapping.data_path
pending_price_unit_path = data_path
extracted = _extract_one_field(
raw_value=extract_raw if extract_raw is not None else raw_value,
mapping_id=mapping.mapping_id,
field_id=mapping.field_id,
field_code=mapping.field_code,
data_path=mapping.data_path,
value_type=mapping.value_type,
normalizer_key=mapping.normalizer_key,
validator_key=mapping.validator_key,
mapping_id=binding.binding_id,
field_id=binding.field_id,
field_code=binding.field_code,
data_path=data_path,
value_type=value_type,
normalizer_key=normalizer_key,
validator_key=validator_key,
schema_fields=schema_fields,
document_id=document_id,
packet_checksum=packet_checksum,
)
# 保留原文 quote(含 ``898.72 / 1``)便于审计对账。
if (
str(mapping.field_code or '') == 'unit_price'
str(binding.field_code or '') == 'unit_price'
and raw_value not in (None, '')
and extract_raw != raw_value
):
@@ -727,7 +816,7 @@ def extract_xfa_profile(
reason_codes: list[str] = []
if has_unconfirmed_split_rules:
reason_codes.append('xfa_split_rule_unconfirmed')
if required_missing or any(row.get('status') != 'parsed' for row in rows):
if required_missing:
reason_codes.append('xfa_required_field_missing')
evidence_summary = sanitize_xfa_dto({
@@ -0,0 +1,387 @@
"""
services/shipping_notice/document_layout/xfa_safe_regex.py
用途:XFA 拆分规则的安全正则编译与搜索——优先 RE2 线性时间语义,失败时回退受限子集。
依赖:可选 google-re2;标准库 re、multiprocessing、concurrent.futures;backend/xfa_regex_worker(spawn 隔离)。
逻辑:由 xfa_split_rule_contract 校验入口与 xfa_split_rule_engine 执行路径调用;
禁止无限制 Python re 执行用户正则;restricted_re 在独立子进程(xfa_regex_worker)执行;
不访问网络或文件。
"""
from __future__ import annotations
import multiprocessing as mp
import re
import threading
from concurrent.futures import ProcessPoolExecutor
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import TimeoutError as FuturesTimeoutError
from dataclasses import dataclass
from typing import Any, Final
import xfa_regex_worker
try:
import re2 as _re2 # type: ignore[import-untyped]
_HAS_RE2: Final[bool] = True
except ImportError: # pragma: no cover - CI/本地未装 google-re2 时走 fallback
_re2 = None # type: ignore[assignment]
_HAS_RE2 = False
_REGEX_FORBIDDEN: Final[tuple[str, ...]] = (
'(?P',
'(?R',
'(?&',
'\\g',
'(?<',
'(?<=',
'(?<!',
'(?=',
'(?!',
)
_REGEX_CATASTROPHIC: Final[tuple[re.Pattern[str], ...]] = (
re.compile(r'\([^)]*[+*][^)]*\)[+*]'),
re.compile(r'\([^)]*[+*][^)]*\)\{'),
re.compile(r'\(\?\:.*[+*].*\)[+*]'),
)
_WORKER_JOIN_GRACE_S: Final[float] = 1.0
_restricted_pool: ProcessPoolExecutor | None = None
_restricted_pool_lock = threading.Lock()
@dataclass(frozen=True)
class SafeRegexCompiled:
"""安全正则编译结果:携带引擎标识供诊断。"""
pattern: str
engine: str # re2 | restricted_re
flags: int
_re2_obj: Any = None
_re_obj: re.Pattern[str] | None = None
@dataclass(frozen=True)
class _MatchSnapshot:
"""父进程侧重导出 xfa_regex_worker.MatchSnapshot 类型别名。"""
groups: tuple[str, ...]
lastindex: int | None
class SafeRegexError(ValueError):
"""安全正则编译或执行失败。"""
class _MatchSnapshotAdapter:
"""
将子进程序列化的分组快照适配为 re.Match 最小接口(group / lastindex)。
核心逻辑:仅暴露 search_safe 消费方所需的 group、lastindex、groupdict。
"""
def __init__(self, snapshot: _MatchSnapshot) -> None:
self._snapshot = snapshot
@property
def lastindex(self) -> int | None:
return self._snapshot.lastindex
def group(self, index: int = 0) -> str:
groups = self._snapshot.groups
if index < 0 or index >= len(groups):
raise IndexError(f'no such group: {index}')
return groups[index]
def groupdict(self) -> dict[str, str]:
return {}
def validate_restricted_regex_pattern(pattern: str, *, max_length: int, max_groups: int) -> None:
"""
校验受限子集正则是否可接受(不执行匹配)。
核心逻辑:长度、捕获组、禁止 token、灾难回溯启发式;为 RE2 预留相同接口。
Args:
pattern: 正则表达式。
max_length: 最大模式长度。
max_groups: 最大捕获组数。
Raises:
SafeRegexError: 模式非法或高风险。
"""
text = str(pattern or '')
if not text:
raise SafeRegexError('regex pattern is empty')
if len(text) > max_length:
raise SafeRegexError('regex pattern exceeds max length')
for token in _REGEX_FORBIDDEN:
if token in text:
raise SafeRegexError(f'regex pattern contains forbidden construct: {token}')
for probe in _REGEX_CATASTROPHIC:
if probe.search(text):
raise SafeRegexError('regex pattern looks catastrophic (nested quantifiers)')
try:
compiled = re.compile(text)
except re.error as exc:
raise SafeRegexError(f'invalid regex pattern: {exc}') from exc
if compiled.groups > max_groups:
raise SafeRegexError('regex capture groups exceed limit')
def compile_safe_regex(
pattern: str,
*,
case_sensitive: bool = True,
max_length: int = 128,
max_groups: int = 5,
) -> SafeRegexCompiled:
"""
编译安全正则:优先 RE2,失败或未安装时使用受限 Python re 子集。
Args:
pattern: 正则表达式。
case_sensitive: 是否区分大小写。
max_length: 最大模式长度。
max_groups: 最大捕获组数。
Returns:
SafeRegexCompiled。
Raises:
SafeRegexError: 模式非法或 RE2 拒绝。
"""
validate_restricted_regex_pattern(pattern, max_length=max_length, max_groups=max_groups)
flags = 0 if case_sensitive else re.IGNORECASE
if _HAS_RE2 and _re2 is not None:
try:
re2_flags = _re2.Flags(0)
if not case_sensitive:
re2_flags = _re2.Flags.CASE_INSENSITIVE # type: ignore[attr-defined]
compiled_re2 = _re2.compile(str(pattern), re2_flags)
group_count = compiled_re2.groups if hasattr(compiled_re2, 'groups') else 0
if int(group_count or 0) > max_groups:
raise SafeRegexError('regex capture groups exceed limit')
return SafeRegexCompiled(
pattern=str(pattern),
engine='re2',
flags=flags,
_re2_obj=compiled_re2,
)
except SafeRegexError:
raise
except Exception as exc: # pragma: no cover - RE2 运行时拒绝
raise SafeRegexError(f're2 compile failed: {exc}') from exc
compiled = re.compile(str(pattern), flags)
return SafeRegexCompiled(
pattern=str(pattern),
engine='restricted_re',
flags=flags,
_re_obj=compiled,
)
def _terminate_process(process: mp.Process) -> None:
"""
强制终止子进程(Windows/Linux 兼容)。
核心逻辑:先 terminate,宽限期后仍存活则 kill。
Args:
process: 待终止的 multiprocessing.Process。
"""
if not process.is_alive():
return
process.terminate()
process.join(timeout=_WORKER_JOIN_GRACE_S)
if process.is_alive():
process.kill()
process.join()
def _destroy_restricted_pool() -> None:
"""
销毁 restricted_re 进程池并在超时后 terminate/kill 仍在运行的 worker。
核心逻辑:shutdown(cancel_futures=True) 后逐个 terminate/kill 残留进程,避免灾难回溯拖死 worker。
"""
global _restricted_pool
with _restricted_pool_lock:
pool = _restricted_pool
if pool is None:
return
processes = dict(getattr(pool, '_processes', {}) or {})
pool.shutdown(wait=False, cancel_futures=True)
for process in processes.values():
_terminate_process(process)
_restricted_pool = None
def _get_restricted_pool() -> ProcessPoolExecutor:
"""
获取或创建 restricted_re 专用 ProcessPoolExecutor(spawn,单 worker)。
核心逻辑:worker 仅导入 xfa_regex_worker;首次创建时提交空匹配预热 spawn 开销。
Returns:
可复用的 ProcessPoolExecutor(max_workers=1)。
"""
global _restricted_pool
with _restricted_pool_lock:
if _restricted_pool is None:
pool = ProcessPoolExecutor(
max_workers=1,
mp_context=mp.get_context('spawn'),
)
warm_future = pool.submit(xfa_regex_worker.run_restricted_search, '^$', 0, '')
warm_future.result(timeout=30.0)
_restricted_pool = pool
return _restricted_pool
def _search_restricted_re_in_subprocess(
pattern: str,
flags: int,
haystack: str,
*,
timeout_s: float,
) -> re.Match[str] | None:
"""
在可 kill 的子进程池中执行 restricted re.search,超时立即销毁池并抛 TimeoutError。
核心逻辑:ProcessPoolExecutor 复用 worker;future.result(timeout) 超时则 terminate/kill 全部 worker。
Args:
pattern: 已校验的正则 pattern。
flags: re 编译 flags。
haystack: 待搜索文本。
timeout_s: 超时秒数(仅计匹配执行,不含首次 pool 预热)。
Returns:
匹配快照适配器;无匹配时 None。
Raises:
TimeoutError: 超时且 worker 进程已被终止。
SafeRegexError: 子进程报告执行错误或异常退出。
"""
pool = _get_restricted_pool()
future = pool.submit(xfa_regex_worker.run_restricted_search, pattern, flags, haystack)
try:
payload = future.result(timeout=timeout_s)
except FuturesTimeoutError as exc:
_destroy_restricted_pool()
raise TimeoutError('regex execution timed out') from exc
except Exception as exc:
_destroy_restricted_pool()
raise SafeRegexError(f'restricted regex worker failed: {exc}') from exc
if payload is None:
return None
snapshot = _MatchSnapshot(groups=payload.groups, lastindex=payload.lastindex)
return _MatchSnapshotAdapter(snapshot)
def search_safe(
compiled: SafeRegexCompiled | str,
text: str,
*,
timeout_ms: int = 50,
case_sensitive: bool = True,
max_length: int = 128,
max_groups: int = 5,
) -> re.Match[str] | None:
"""
对文本执行安全正则搜索(带超时)。
核心逻辑:RE2 路径在线程池执行(线性时间,线程超时即可);
restricted_re 路径在 ProcessPoolExecutor spawn worker 中执行,超时 destroy pool 并 kill worker。
Args:
compiled: 已编译对象或原始 pattern(将临时编译)。
text: 待搜索文本。
timeout_ms: 超时毫秒。
case_sensitive: 当 compiled 为 str 时传给 compile_safe_regex。
max_length: 当 compiled 为 str 时的模式长度上限。
max_groups: 当 compiled 为 str 时的捕获组上限。
Returns:
匹配对象;无匹配时 None。
Raises:
SafeRegexError: 编译失败或 restricted 子进程执行失败。
TimeoutError: 执行超时(restricted 路径保证子进程已被终止)。
"""
obj = (
compiled
if isinstance(compiled, SafeRegexCompiled)
else compile_safe_regex(
str(compiled),
case_sensitive=case_sensitive,
max_length=max_length,
max_groups=max_groups,
)
)
haystack = str(text or '')
timeout_s = max(int(timeout_ms), 1) / 1000.0
if obj.engine == 're2' and obj._re2_obj is not None:
def _run_re2() -> Any:
assert obj._re2_obj is not None
return obj._re2_obj.search(haystack)
with ThreadPoolExecutor(max_workers=1) as pool:
future = pool.submit(_run_re2)
try:
matched = future.result(timeout=timeout_s)
except FuturesTimeoutError as exc:
future.cancel()
raise TimeoutError('regex execution timed out') from exc
if matched is None:
return None
return _Re2MatchAdapter(matched)
return _search_restricted_re_in_subprocess(
obj.pattern,
obj.flags,
haystack,
timeout_s=timeout_s,
)
class _Re2MatchAdapter:
"""
将 RE2 Match 适配为类似 re.Match 的最小接口(group / lastindex)。
"""
def __init__(self, raw: Any) -> None:
self._raw = raw
@property
def lastindex(self) -> int | None:
try:
count = int(self._raw.groups())
return count if count > 0 else None
except Exception:
return None
def group(self, index: int = 0) -> str:
try:
if index == 0:
return str(self._raw.group() or '')
return str(self._raw.group(index) or '')
except Exception as exc:
raise IndexError(str(exc)) from exc
def groupdict(self) -> dict[str, str]:
return {}
def has_re2_engine() -> bool:
"""
当前进程是否可用 RE2 引擎。
Returns:
True 表示 google-re2 已安装且可导入。
"""
return _HAS_RE2
@@ -1,10 +1,11 @@
"""
backend/app/services/shipping_notice/document_layout/xfa_signature.py
用途:计算 XFA template packet checksum、datasets 结构指纹与治理用 structure signature。
用途:计算 XFA template packet checksum、datasets 结构指纹、统一 binding/拆分
内容指纹与治理用 structure signature。
依赖:xfa_contract、xfa_dataset.XfaDatasetNode、标准库 hashlib/json。
逻辑:由 xfa_analysis / 验证服务调用;指纹忽略业务值与行数;structure signature
冻结 analysis 与 packet 身份供发布门禁引用。
与 definition checksum 覆盖视觉绑定与拆分规则业务字段。
"""
from __future__ import annotations
@@ -16,6 +17,8 @@ from typing import Any
from app.services.shipping_notice.document_layout.xfa_contract import (
XFA_STRUCTURE_SIGNATURE_ID,
XfaStructureNodeSpec,
XfaUnifiedFieldBinding,
canonical_unified_bindings_payload,
compute_dataset_structure_fingerprint,
)
from app.services.shipping_notice.document_layout.xfa_dataset import XfaDatasetNode
@@ -145,3 +148,43 @@ def build_xfa_structure_signature(
'has_structure_fingerprint': bool(dataset_structure_fingerprint),
},
}
def compute_unified_bindings_checksum(
bindings: list[XfaUnifiedFieldBinding] | list[dict[str, Any]],
) -> str:
"""
计算统一 binding(含 visual_binding / split_rule_ref)的稳定 checksum。
Args:
bindings: 统一字段绑定列表。
Returns:
`sha256:<hex>`。
"""
payload = {
'kind': 'xfa-unified-bindings.v1',
'bindings': canonical_unified_bindings_payload(bindings),
}
encoded = json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
return f'sha256:{hashlib.sha256(encoded).hexdigest()}'
def compute_definition_business_checksum(definition: dict[str, Any]) -> str:
"""
计算 XFA definition 业务字段 checksum(含 bindings 与 split_rules)。
核心逻辑:对 definition 做 canonical JSON 哈希;调用方须传入已通过契约校验的对象。
Args:
definition: Profile definition 字典。
Returns:
`sha256:<hex>`。
"""
payload = {
'kind': 'xfa-definition-business.v1',
'definition': definition or {},
}
encoded = json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
return f'sha256:{hashlib.sha256(encoded).hexdigest()}'
@@ -0,0 +1,437 @@
"""
services/shipping_notice/document_layout/xfa_split_preview_token.py
用途:签发与校验 XFA 拆分规则预览确认令牌,防止客户端自行声明 confirmed。
依赖:Flask current_app.SECRET_KEY、hmac、hashlib、time、secrets、redis_client(可选)。
逻辑:由 preview_xfa_split_rules 签发;save_draft / 确认接口经 verify_and_consume 原子消费 jti;
Redis 不可用时回退进程内 set + threading.Lock(单测与单进程开发友好,非多 Worker 生产语义)。
"""
from __future__ import annotations
import hashlib
import hmac
import json
import secrets
import threading
import time
from typing import Any
from flask import current_app
from app.core.errors import ValidationError
# 预览确认令牌默认有效期(秒)
DEFAULT_SPLIT_PREVIEW_TOKEN_TTL_SECONDS = 15 * 60
# Redis 消费键前缀;不可用时由 _MemoryConsumedJtiStore 兜底。
_JTI_REDIS_KEY_PREFIX = 'shipping:xfa_split_preview_token:'
class _MemoryConsumedJtiStore:
"""进程内 jti 一次性消费存储(Redis 不可用时的测试/单进程兜底)。"""
def __init__(self) -> None:
self._lock = threading.Lock()
self._consumed: dict[str, float] = {}
def try_consume(self, jti: str, ttl_seconds: int) -> bool:
"""
尝试标记 jti 为已消费。
核心逻辑:持锁清理过期项后,若 jti 已存在则拒绝(重放),否则写入过期时间。
Returns:
True 表示首次消费成功;False 表示已消费或仍在有效期内。
"""
now = time.time()
expires_at = now + max(1, int(ttl_seconds))
with self._lock:
expired = [key for key, exp in self._consumed.items() if exp <= now]
for key in expired:
del self._consumed[key]
if jti in self._consumed:
return False
self._consumed[jti] = expires_at
return True
_memory_jti_store = _MemoryConsumedJtiStore()
def _signing_secret() -> bytes:
"""
读取应用级签名密钥。
Returns:
SECRET_KEY 的 UTF-8 字节。
Raises:
ValidationError: SECRET_KEY 未配置。
"""
secret = str(current_app.config.get('SECRET_KEY') or '').strip()
if not secret:
raise ValidationError(
'SECRET_KEY is required for XFA split preview tokens',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
details={'reason': 'secret_key_missing'},
)
return secret.encode('utf-8')
def split_rule_preview_fingerprint(rule_set: dict[str, Any] | Any) -> str:
"""
计算规则集内容指纹(与确认令牌绑定)。
核心逻辑:委托 split_rule_content_fingerprint,保证预览与保存比对一致。
Args:
rule_set: 规则集 dict 或已校验模型。
Returns:
内容指纹字符串。
"""
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
split_rule_content_fingerprint,
)
return split_rule_content_fingerprint(rule_set)
def _try_consume_jti(*, jti: str, ttl_seconds: int) -> bool:
"""
原子消费令牌 jti。
核心逻辑:优先 Redis SET NX EX;失败或不可用时回退进程内 set + Lock。
Args:
jti: 令牌唯一标识。
ttl_seconds: 剩余有效秒数(与令牌 exp 对齐)。
Returns:
True 表示首次消费成功;False 表示已被消费。
"""
key = f'{_JTI_REDIS_KEY_PREFIX}{jti}'
ttl = max(1, int(ttl_seconds))
try:
from app.services.redis_client import get_redis_client
client = get_redis_client()
if client is not None:
return bool(client.set(key, '1', nx=True, ex=ttl))
except Exception:
pass
return _memory_jti_store.try_consume(jti, ttl)
def _validate_token_bindings(
payload: dict[str, Any],
*,
actor_id: int,
profile_id: int | None,
document_id: int | None,
path_id: str,
rule_fingerprint: str,
sample_checksum: str,
analysis_id: int | None = None,
template_packet_checksum: str | None = None,
dataset_structure_fingerprint: str | None = None,
) -> None:
"""
校验令牌 payload 与当前请求上下文绑定一致(不含 jti 消费)。
Raises:
ValidationError: 任一绑定字段不匹配。
"""
if int(payload.get('exp') or 0) < int(time.time()):
raise ValidationError(
'XFA split preview confirmation token expired',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
details={'reason': 'expired'},
)
if int(payload.get('actor_id') or 0) != int(actor_id):
raise ValidationError(
'XFA split preview confirmation token actor mismatch',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
details={'reason': 'actor_mismatch'},
)
if str(payload.get('path_id') or '') != str(path_id):
raise ValidationError(
'XFA split preview confirmation token path mismatch',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
details={'reason': 'path_mismatch'},
)
if str(payload.get('rule_fp') or '') != str(rule_fingerprint):
raise ValidationError(
'XFA split preview confirmation token rule fingerprint mismatch',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
details={'reason': 'rule_mismatch'},
)
token_sample = str(payload.get('sample_checksum') or '').strip()
if not token_sample or token_sample != str(sample_checksum or '').strip():
raise ValidationError(
'XFA split preview confirmation token sample checksum mismatch',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
details={'reason': 'sample_checksum_mismatch'},
)
token_profile = payload.get('profile_id')
if token_profile is not None and profile_id is not None and int(token_profile) != int(profile_id):
raise ValidationError(
'XFA split preview confirmation token profile mismatch',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
details={'reason': 'profile_mismatch'},
)
token_document = payload.get('document_id')
if document_id is not None and token_document is not None and int(token_document) != int(document_id):
raise ValidationError(
'XFA split preview confirmation token document mismatch',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
details={'reason': 'document_mismatch'},
)
token_analysis = payload.get('analysis_id')
if analysis_id is not None and token_analysis is not None and int(token_analysis) != int(analysis_id):
raise ValidationError(
'XFA split preview confirmation token analysis mismatch',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
details={'reason': 'analysis_mismatch'},
)
token_template = str(payload.get('template_packet_checksum') or '').strip()
expected_template = str(template_packet_checksum or '').strip()
if token_template and expected_template and token_template != expected_template:
raise ValidationError(
'XFA split preview confirmation token template checksum mismatch',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
details={'reason': 'template_checksum_mismatch'},
)
token_fp = str(payload.get('dataset_structure_fingerprint') or '').strip()
expected_fp = str(dataset_structure_fingerprint or '').strip()
if token_fp and expected_fp and token_fp != expected_fp:
raise ValidationError(
'XFA split preview confirmation token structure fingerprint mismatch',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
details={'reason': 'structure_fingerprint_mismatch'},
)
def _decode_and_verify_signature(token: str) -> dict[str, Any]:
"""
解码并验签令牌,返回 payload。
Raises:
ValidationError: 令牌缺失、伪造或 payload 非法。
"""
text = str(token or '').strip()
if not text or '.' not in text:
raise ValidationError(
'XFA split preview confirmation token is required',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
details={'reason': 'token_missing'},
)
payload_hex, _, sig = text.partition('.')
try:
raw = bytes.fromhex(payload_hex)
except ValueError as exc:
raise ValidationError(
'XFA split preview confirmation token is invalid',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
details={'reason': 'token_malformed'},
) from exc
expected = hmac.new(_signing_secret(), raw, hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, sig):
raise ValidationError(
'XFA split preview confirmation token signature mismatch',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
details={'reason': 'bad_signature'},
)
try:
payload = json.loads(raw.decode('utf-8'))
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
raise ValidationError(
'XFA split preview confirmation token payload is invalid',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
details={'reason': 'bad_payload'},
) from exc
if not isinstance(payload, dict):
raise ValidationError(
'XFA split preview confirmation token payload is invalid',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
details={'reason': 'bad_payload'},
)
return payload
def issue_split_preview_token(
*,
actor_id: int,
profile_id: int | None,
document_id: int,
path_id: str,
rule_fingerprint: str,
sample_checksum: str,
analysis_id: int | None = None,
template_packet_checksum: str | None = None,
dataset_structure_fingerprint: str | None = None,
ttl_seconds: int = DEFAULT_SPLIT_PREVIEW_TOKEN_TTL_SECONDS,
) -> str:
"""
签发可验证的拆分预览确认令牌。
核心逻辑:payload 含 jti、actor/profile/document/path/规则指纹/样本 checksum 与
可选 analysis/template/structure 绑定;HMAC-SHA256 签名后以 hex 拼接。
Args:
actor_id: 预览操作者。
profile_id: Profile 主键(可空,保存时须与请求一致)。
document_id: 样本文档 ID。
path_id: 源字段 path_id。
rule_fingerprint: 规则内容指纹。
sample_checksum: 源叶子 raw_value 的 SHA256 前 32 位 hex(必填)。
analysis_id: 结构分析 ID(可空;有则保存时校验)。
template_packet_checksum: 模板包 checksum(可空;有则校验)。
dataset_structure_fingerprint: 数据集结构指纹(可空;有则校验)。
ttl_seconds: 有效期秒数。
Returns:
令牌字符串。
"""
exp = int(time.time()) + max(60, int(ttl_seconds))
payload: dict[str, Any] = {
'v': 2,
'jti': secrets.token_hex(16),
'actor_id': int(actor_id),
'profile_id': int(profile_id) if profile_id is not None else None,
'document_id': int(document_id),
'path_id': str(path_id),
'rule_fp': str(rule_fingerprint),
'sample_checksum': str(sample_checksum).strip(),
'exp': exp,
}
if analysis_id is not None:
payload['analysis_id'] = int(analysis_id)
if template_packet_checksum:
payload['template_packet_checksum'] = str(template_packet_checksum).strip()
if dataset_structure_fingerprint:
payload['dataset_structure_fingerprint'] = str(dataset_structure_fingerprint).strip()
raw = json.dumps(payload, sort_keys=True, separators=(',', ':')).encode('utf-8')
payload_hex = raw.hex()
sig = hmac.new(_signing_secret(), raw, hashlib.sha256).hexdigest()
return f'{payload_hex}.{sig}'
def verify_split_preview_token(
token: str,
*,
actor_id: int,
profile_id: int | None,
document_id: int | None,
path_id: str,
rule_fingerprint: str,
sample_checksum: str,
analysis_id: int | None = None,
template_packet_checksum: str | None = None,
dataset_structure_fingerprint: str | None = None,
) -> dict[str, Any]:
"""
纯验签校验拆分预览确认令牌并返回 payload(不消费 jti)。
核心逻辑:验签 → 绑定字段比对;保存路径须改用 verify_and_consume_split_preview_token。
Args:
token: 预览接口返回的令牌。
actor_id: 当前操作者(须与签发者相同)。
profile_id: 当前 Profile。
document_id: 可选样本文档;提供时须匹配。
path_id: 规则源 path_id。
rule_fingerprint: 待确认规则内容指纹。
sample_checksum: 当前样本源叶子 checksum。
analysis_id: 当前结构分析 ID(可选)。
template_packet_checksum: 当前模板包 checksum(可选)。
dataset_structure_fingerprint: 当前结构指纹(可选)。
Returns:
已校验 payload dict。
Raises:
ValidationError: 令牌缺失、伪造、过期或绑定不匹配。
"""
payload = _decode_and_verify_signature(token)
_validate_token_bindings(
payload,
actor_id=actor_id,
profile_id=profile_id,
document_id=document_id,
path_id=path_id,
rule_fingerprint=rule_fingerprint,
sample_checksum=sample_checksum,
analysis_id=analysis_id,
template_packet_checksum=template_packet_checksum,
dataset_structure_fingerprint=dataset_structure_fingerprint,
)
return payload
def verify_and_consume_split_preview_token(
token: str,
*,
actor_id: int,
profile_id: int | None,
document_id: int | None,
path_id: str,
rule_fingerprint: str,
sample_checksum: str,
analysis_id: int | None = None,
template_packet_checksum: str | None = None,
dataset_structure_fingerprint: str | None = None,
) -> dict[str, Any]:
"""
验签并原子消费拆分预览确认令牌。
核心逻辑:验签与绑定校验通过后,以 Redis SET NX EX(或进程内兜底)标记 jti 已消费;
重复消费抛 token_replay。
Args:
token: 预览接口返回的令牌。
actor_id: 当前操作者。
profile_id: 当前 Profile。
document_id: 样本文档 ID。
path_id: 规则源 path_id。
rule_fingerprint: 待确认规则内容指纹。
sample_checksum: 当前样本源叶子 checksum。
analysis_id: 当前结构分析 ID(可选)。
template_packet_checksum: 当前模板包 checksum(可选)。
dataset_structure_fingerprint: 当前结构指纹(可选)。
Returns:
已校验且已消费的 payload dict。
Raises:
ValidationError: 令牌无效、绑定不匹配或已被消费(重放)。
"""
payload = _decode_and_verify_signature(token)
_validate_token_bindings(
payload,
actor_id=actor_id,
profile_id=profile_id,
document_id=document_id,
path_id=path_id,
rule_fingerprint=rule_fingerprint,
sample_checksum=sample_checksum,
analysis_id=analysis_id,
template_packet_checksum=template_packet_checksum,
dataset_structure_fingerprint=dataset_structure_fingerprint,
)
jti = str(payload.get('jti') or '').strip()
if not jti:
raise ValidationError(
'XFA split preview confirmation token is invalid',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
details={'reason': 'jti_missing'},
)
remaining_ttl = max(1, int(payload.get('exp') or 0) - int(time.time()))
if not _try_consume_jti(jti=jti, ttl_seconds=remaining_ttl):
raise ValidationError(
'XFA split preview confirmation token was already used',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SPLIT_TOKEN_INVALID',
details={'reason': 'token_replay'},
)
return payload
@@ -1,71 +1,123 @@
"""
services/shipping_notice/document_layout/xfa_split_rule_contract.py
用途:冻结 XFA 字段拆分规则契约——自定义 segment、多阶段 stages 白名单、
Schema 映射限制、evidence_only 边界与正则资源上限。
依赖:Pydantic 2、标准库 re/uuid;被 xfa_split_rule_engine、
order_document_profile_service 与正式提取路径引用。
用途:冻结 XFA 字段拆分规则契约——matcher 优先级模型、segment 映射、
evidence_only 边界、正则资源上限与 Schema 校验入口。
依赖:Pydantic 2、xfa_contract、xfa_safe_regex、Flask settings(可选)。
逻辑:仅声明式校验,不执行规则、不读 PDF、不接网络;非法契约以 ValidationError
或 ValueError 拒绝;不提供系统推荐;若残留 source=system_suggestion 必须 draft。
或 ValueError 拒绝;匹配优先级由引擎固定 prefix > regex > position > unmatched。
"""
from __future__ import annotations
import os
import re
import uuid
from typing import Any, Final, Literal
from pydantic import Field, field_validator, model_validator
from pydantic import AliasChoices, Field, field_validator, model_validator
from app.services.shipping_notice.document_layout.xfa_contract import (
XfaContractModel,
validate_controlled_data_path,
)
from app.services.shipping_notice.document_layout.xfa_safe_regex import (
SafeRegexError,
validate_restricted_regex_pattern,
)
# ---------------------------------------------------------------------------
# 资源上限(防止灾难性回溯与规则爆炸)
# 资源上限默认值(可被 settings / 环境变量覆盖)
# ---------------------------------------------------------------------------
XFA_SPLIT_MAX_RULES_PER_SET: Final[int] = 32
XFA_SPLIT_MAX_RULE_SETS: Final[int] = 64
XFA_SPLIT_MAX_STAGES_PER_RULE: Final[int] = 16
XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH: Final[int] = 128
XFA_SPLIT_MAX_REGEX_GROUPS: Final[int] = 5
XFA_SPLIT_MAX_PREFIX_LENGTH: Final[int] = 64
XFA_SPLIT_MAX_SEGMENT_CODE_LENGTH: Final[int] = 64
XFA_SPLIT_MAX_DISPLAY_NAME_LENGTH: Final[int] = 128
XFA_SPLIT_MAX_REPLACE_LENGTH: Final[int] = 128
XFA_SPLIT_MAX_INPUT_LENGTH: Final[int] = 32_768
XFA_SPLIT_REGEX_TIMEOUT_MS: Final[int] = 50
# 引擎固定匹配优先级(数值越小优先级越高)
XFA_SPLIT_MATCHER_PRIORITY: Final[dict[str, int]] = {
'prefix': 0,
'regex': 1,
'position': 2,
}
XFA_SPLIT_UNMATCHED_PRIORITY: Final[int] = 3
XfaSplitHandling = Literal['mapped', 'evidence_only']
XfaSplitStageType = Literal[
'split_lines',
'select_line',
'select_line_range',
'extract_prefix',
'regex_capture',
'replace',
'substring',
'normalize',
]
XfaSplitStrategy = Literal['pipeline']
XfaSplitMatcherType = Literal['position', 'prefix', 'regex']
XfaSplitSourceScope = Literal['header', 'line']
XfaSplitUnmatchedPolicy = Literal['evidence_only', 'needs_review']
XfaSplitDuplicatePolicy = Literal['needs_review']
XfaSplitRuleStatus = Literal['draft', 'confirmed', 'published']
XfaSplitRuleSource = Literal['system_suggestion', 'user', 'imported']
_SEGMENT_CODE_RE = re.compile(r'^[a-z][a-z0-9_]{1,63}$')
_REGEX_FORBIDDEN = (
'(?P', # named groups
'(?R', # recursive
'(?&',
'\\g',
)
# 常见灾难性回溯形态(启发式,不保证穷尽)
_REGEX_CATASTROPHIC = (
re.compile(r'\([^)]*[+*][^)]*\)[+*]'),
re.compile(r'\([^)]*[+*][^)]*\)\{'),
)
def _config_int(key: str, default: int) -> int:
"""
从 Flask config 或环境变量读取整型配置。
Args:
key: 配置键名。
default: 缺失时的默认值。
Returns:
解析后的正整数。
"""
try:
from flask import has_app_context, current_app
if has_app_context():
raw = current_app.config.get(key)
if raw is not None:
return max(1, int(raw))
except Exception:
pass
raw_env = os.getenv(key)
if raw_env is not None and str(raw_env).strip():
return max(1, int(raw_env))
return default
def get_xfa_split_max_rules_per_set() -> int:
"""单规则集最大 rules 条数。"""
return _config_int('XFA_SPLIT_MAX_RULES_PER_SET', XFA_SPLIT_MAX_RULES_PER_SET)
def get_xfa_split_max_rule_sets() -> int:
"""Profile 最大 split_rules 规则集数。"""
return _config_int('XFA_SPLIT_MAX_RULE_SETS', XFA_SPLIT_MAX_RULE_SETS)
def get_xfa_split_max_regex_pattern_length() -> int:
"""单条正则模式最大长度。"""
return _config_int('XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH', XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH)
def get_xfa_split_max_regex_groups() -> int:
"""正则最大捕获组数。"""
return _config_int('XFA_SPLIT_MAX_REGEX_GROUPS', XFA_SPLIT_MAX_REGEX_GROUPS)
def get_xfa_split_max_prefix_length() -> int:
"""前缀标签最大长度。"""
return _config_int('XFA_SPLIT_MAX_PREFIX_LENGTH', XFA_SPLIT_MAX_PREFIX_LENGTH)
def get_xfa_split_max_input_length() -> int:
"""拆分源字段最大输入长度。"""
return _config_int('XFA_SPLIT_MAX_INPUT_LENGTH', XFA_SPLIT_MAX_INPUT_LENGTH)
def get_xfa_split_regex_timeout_ms() -> int:
"""正则执行超时(毫秒)。"""
return _config_int('XFA_SPLIT_REGEX_TIMEOUT_MS', XFA_SPLIT_REGEX_TIMEOUT_MS)
class XfaSplitSegment(XfaContractModel):
@@ -102,125 +154,73 @@ class XfaSplitSegment(XfaContractModel):
return self
class XfaSplitStage(XfaContractModel):
class XfaSplitMatcher(XfaContractModel):
"""
单阶段处理步骤(声明式流水线节点)。
单行匹配器:position / prefix / regex。
状态机:split_lines 产出行列表;select_line/select_line_range 产出标量并记录行号范围;
其余阶段在标量文本上变换。
优先级由引擎固定为 prefix > regex > position;契约仅声明字段形状。
"""
stage_id: str = Field(min_length=1, max_length=64)
type: XfaSplitStageType
# split_lines / normalize
trim: bool = True
remove_empty_lines: bool = True
line_breaks: list[str] = Field(default_factory=lambda: ['\r\n', '\r', '\n'])
# select_line
type: XfaSplitMatcherType
line_index: int | None = Field(default=None, ge=1, le=1000)
# select_line_range
line_start: int | None = Field(default=None, ge=1, le=1000)
line_end: int | None = Field(default=None, ge=1, le=1000)
join_with: Literal['newline', 'space', 'comma'] = 'newline'
# extract_prefix
value: str | None = Field(default=None, max_length=XFA_SPLIT_MAX_PREFIX_LENGTH)
case_sensitive: bool = False
separators: list[str] = Field(default_factory=lambda: [':', ':'])
# regex_capture
case_sensitive: bool = False
pattern: str | None = Field(default=None, max_length=XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH)
capture_group: int | None = Field(default=None, ge=0, le=XFA_SPLIT_MAX_REGEX_GROUPS)
# replace
find: str | None = Field(default=None, max_length=XFA_SPLIT_MAX_REPLACE_LENGTH)
replace_with: str | None = Field(default=None, max_length=XFA_SPLIT_MAX_REPLACE_LENGTH)
# substring(0-based,end 不含)
start: int | None = Field(default=None, ge=0, le=10_000)
end: int | None = Field(default=None, ge=0, le=10_000)
@model_validator(mode='after')
def validate_stage_shape(self) -> 'XfaSplitStage':
"""按 type 校验必填字段与正则安全边界。"""
if self.type == 'split_lines':
breaks = [str(item) for item in (self.line_breaks or []) if str(item)]
if not breaks:
raise ValueError('split_lines requires at least one line_break')
object.__setattr__(self, 'line_breaks', breaks)
elif self.type == 'select_line':
def validate_matcher_shape(self) -> 'XfaSplitMatcher':
"""按 type 校验必填字段、前缀与正则安全边界。"""
max_prefix = get_xfa_split_max_prefix_length()
max_pattern_len = get_xfa_split_max_regex_pattern_length()
max_groups = get_xfa_split_max_regex_groups()
if self.type == 'position':
if self.line_index is None:
raise ValueError('select_line requires line_index (1-based)')
elif self.type == 'select_line_range':
if self.line_start is None or self.line_end is None:
raise ValueError('select_line_range requires line_start and line_end (1-based)')
if self.line_end < self.line_start:
raise ValueError('select_line_range requires line_end >= line_start')
elif self.type == 'extract_prefix':
raise ValueError('position matcher requires line_index (1-based)')
elif self.type == 'prefix':
label = str(self.value or '').strip()
if not label:
raise ValueError('extract_prefix requires non-empty value')
raise ValueError('prefix matcher requires non-empty value')
if len(label) > max_prefix:
raise ValueError('prefix value exceeds max length')
seps = [str(item) for item in (self.separators or []) if str(item)]
if not seps:
raise ValueError('extract_prefix requires at least one separator')
raise ValueError('prefix matcher requires at least one separator')
object.__setattr__(self, 'separators', seps)
object.__setattr__(self, 'value', label)
elif self.type == 'regex_capture':
elif self.type == 'regex':
pattern = str(self.pattern or '')
if not pattern:
raise ValueError('regex_capture requires pattern')
if len(pattern) > XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH:
raise ValueError('regex matcher requires pattern')
if len(pattern) > max_pattern_len:
raise ValueError('regex pattern exceeds max length')
for token in _REGEX_FORBIDDEN:
if token in pattern:
raise ValueError(f'regex pattern contains forbidden construct: {token}')
for probe in _REGEX_CATASTROPHIC:
if probe.search(pattern):
raise ValueError('regex pattern looks catastrophic (nested quantifiers)')
try:
compiled = re.compile(pattern)
except re.error as exc:
raise ValueError(f'invalid regex pattern: {exc}') from exc
if compiled.groups > XFA_SPLIT_MAX_REGEX_GROUPS:
raise ValueError('regex capture groups exceed limit')
if self.capture_group is not None and self.capture_group > compiled.groups:
raise ValueError('capture_group exceeds pattern groups')
elif self.type == 'replace':
if self.find is None or str(self.find) == '':
raise ValueError('replace requires non-empty find')
if self.replace_with is None:
object.__setattr__(self, 'replace_with', '')
elif self.type == 'substring':
if self.start is None:
raise ValueError('substring requires start')
if self.end is not None and self.end < self.start:
raise ValueError('substring end must be >= start')
elif self.type == 'normalize':
pass
validate_restricted_regex_pattern(
pattern,
max_length=max_pattern_len,
max_groups=max_groups,
)
except SafeRegexError as exc:
raise ValueError(str(exc)) from exc
if self.capture_group is not None and self.capture_group > max_groups:
raise ValueError('capture_group exceeds pattern groups limit')
else:
raise ValueError(f'unsupported matcher type: {self.type}')
return self
class XfaSplitRule(XfaContractModel):
"""单条输出流水线:显式 order + stages[] + segment。"""
"""单条拆分规则:rule_id + matcher + segment(无 stages[])。"""
rule_id: str = Field(min_length=1, max_length=64)
order: int = Field(ge=1, le=10_000)
matcher: XfaSplitMatcher
segment: XfaSplitSegment
stages: list[XfaSplitStage] = Field(min_length=1)
@model_validator(mode='after')
def validate_pipeline(self) -> 'XfaSplitRule':
"""校验 stages 数量与 stage_id 唯一。"""
if len(self.stages) > XFA_SPLIT_MAX_STAGES_PER_RULE:
raise ValueError(f'stages exceed max {XFA_SPLIT_MAX_STAGES_PER_RULE}')
stage_ids = [item.stage_id for item in self.stages]
if len(stage_ids) != len(set(stage_ids)):
raise ValueError('duplicate stage_id within split rule')
return self
class XfaSplitNormalization(XfaContractModel):
"""
规则集级默认换行策略:用于未匹配行盘点与无 split_lines 时的行清单。
流水线内仍以 stages.split_lines 为准。
"""
"""规则集级换行与 trim 策略:引擎按 line_breaks 拆行后再逐行匹配。"""
trim: bool = True
remove_empty_lines: bool = True
@@ -244,12 +244,16 @@ class XfaSplitRuleSet(XfaContractModel):
必须保持 draft + requires_confirmation,且不得进入正式提取/发布。
"""
rule_id: str = Field(min_length=1, max_length=128)
rule_set_id: str = Field(
min_length=1,
max_length=128,
validation_alias=AliasChoices('rule_set_id', 'rule_id'),
)
rule_version: int = Field(ge=1, le=10_000)
source_path_id: str = Field(min_length=1, max_length=128)
source_field_code: str = Field(min_length=1, max_length=128)
source_scope: XfaSplitSourceScope = 'line'
source_field_code: str | None = Field(default=None, max_length=128)
source_data_path: str | None = Field(default=None, min_length=1, max_length=512)
strategy: XfaSplitStrategy = 'pipeline'
normalization: XfaSplitNormalization = Field(default_factory=XfaSplitNormalization)
rules: list[XfaSplitRule] = Field(default_factory=list)
unmatched_line_policy: XfaSplitUnmatchedPolicy = 'evidence_only'
@@ -259,6 +263,11 @@ class XfaSplitRuleSet(XfaContractModel):
status: XfaSplitRuleStatus = 'draft'
requires_confirmation: bool = False
@property
def rule_id(self) -> str:
"""兼容旧字段名 rule_id(等同 rule_set_id)。"""
return self.rule_set_id
@field_validator('source_data_path', mode='before')
@classmethod
def validate_source_data_path(cls, value: Any) -> str | None:
@@ -270,14 +279,12 @@ class XfaSplitRuleSet(XfaContractModel):
@model_validator(mode='after')
def validate_rule_set_invariants(self) -> 'XfaSplitRuleSet':
"""规则集内唯一性与数量上限。"""
if len(self.rules) > XFA_SPLIT_MAX_RULES_PER_SET:
raise ValueError(f'rules exceed max {XFA_SPLIT_MAX_RULES_PER_SET}')
max_rules = get_xfa_split_max_rules_per_set()
if len(self.rules) > max_rules:
raise ValueError(f'rules exceed max {max_rules}')
rule_ids = [item.rule_id for item in self.rules]
if len(rule_ids) != len(set(rule_ids)):
raise ValueError('duplicate rule_id within split rule set')
orders = [item.order for item in self.rules]
if len(orders) != len(set(orders)):
raise ValueError('duplicate order within split rule set')
segment_ids = [item.segment.segment_id for item in self.rules]
if len(segment_ids) != len(set(segment_ids)):
raise ValueError('duplicate segment_id within split rule set')
@@ -316,25 +323,12 @@ def new_rule_id(prefix: str = 'rule') -> str:
return f'{safe}-{uuid.uuid4().hex[:12]}'
def new_stage_id(prefix: str = 'stage') -> str:
"""
生成 stage_id。
Args:
prefix: ID 前缀。
Returns:
形如 ``{prefix}-<hex>`` 的标识。
"""
safe = re.sub(r'[^a-z0-9_]+', '_', str(prefix or 'stage').strip().lower()) or 'stage'
return f'{safe}-{uuid.uuid4().hex[:10]}'
def split_rule_content_fingerprint(rule_set: XfaSplitRuleSet | dict[str, Any]) -> str:
"""
计算规则集内容指纹(排除 status / requires_confirmation / rule_version)。
核心逻辑:用于判断 confirmed 规则内容是否被篡改,需强制回退 Draft。
核心逻辑:只冻结 matcher 与 normalization;segment 的 Schema 映射字段不属于拆分逻辑,
后续绑定或解绑目标字段不得取消已确认状态。
Args:
rule_set: 模型或 dict。
@@ -345,12 +339,22 @@ def split_rule_content_fingerprint(rule_set: XfaSplitRuleSet | dict[str, Any]) -
import json
if isinstance(rule_set, XfaSplitRuleSet):
payload = rule_set.model_dump(mode='json')
payload = rule_set.model_dump(mode='json', by_alias=True)
else:
payload = dict(rule_set or {})
if 'rule_set_id' not in payload and payload.get('rule_id'):
payload['rule_set_id'] = payload['rule_id']
payload.pop('status', None)
payload.pop('requires_confirmation', None)
payload.pop('rule_version', None)
payload.pop('rule_id', None)
for rule in payload.get('rules') or []:
segment = rule.get('segment') if isinstance(rule, dict) else None
if not isinstance(segment, dict):
continue
segment.pop('handling', None)
segment.pop('target_field_id', None)
segment.pop('target_field_code', None)
return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
@@ -365,13 +369,13 @@ def validate_split_rules_against_schema(
相对冻结 Schema 与已知 path_id 校验拆分规则集。
核心逻辑:目标字段必须存在、启用且与拆分源节点 scope 一致;
source_path_id 必须已知(若提供集合)。
source_path_id 必须已知(若提供集合);优先使用 rule_set.source_scope。
Args:
rule_sets: 待校验规则集。
known_schema_fields: field_code → Schema 字段配置(仅 enabled)。
known_path_ids: 分析记录合法 path_id;None 时跳过路径存在性检查。
source_scopes: source_path_id → header/line;未提供时仅校验字段存在性。
source_scopes: source_path_id → header/line;未提供时使用 rule_set.source_scope。
Returns:
校验通过的同一列表。
@@ -379,13 +383,18 @@ def validate_split_rules_against_schema(
Raises:
ValueError: 契约或 Schema 引用非法。
"""
if len(rule_sets) > XFA_SPLIT_MAX_RULE_SETS:
raise ValueError(f'split_rules exceed max {XFA_SPLIT_MAX_RULE_SETS}')
max_sets = get_xfa_split_max_rule_sets()
if len(rule_sets) > max_sets:
raise ValueError(f'split_rules exceed max {max_sets}')
all_codes: list[str] = []
all_segment_ids: list[str] = []
for rule_set in rule_sets:
if known_path_ids is not None and rule_set.source_path_id not in known_path_ids:
raise ValueError(f'unknown source_path_id: {rule_set.source_path_id}')
expected_scope = str(rule_set.source_scope or '').strip().lower()
scoped = str((source_scopes or {}).get(rule_set.source_path_id) or '').strip().lower()
if scoped:
expected_scope = scoped
for rule in rule_set.rules:
all_codes.append(rule.segment.segment_code)
all_segment_ids.append(rule.segment.segment_id)
@@ -396,7 +405,6 @@ def validate_split_rules_against_schema(
if field is None:
raise ValueError(f'target Schema field not found or disabled: {code}')
scope = str(field.get('scope') or '').strip().lower()
expected_scope = str((source_scopes or {}).get(rule_set.source_path_id) or '').strip().lower()
if expected_scope and scope != expected_scope:
raise ValueError(
f'target Schema field {code} must have scope={expected_scope}; got {scope or "missing"}',
@@ -1,27 +1,34 @@
"""
services/shipping_notice/document_layout/xfa_split_rule_engine.py
用途:声明式执行 XFA 多阶段拆分流水线,产出 mapped Schema 值与 evidence_only 段。
依赖:xfa_split_rule_contract、concurrent.futures(正则超时)。
用途:按冻结优先级执行 XFA 字段拆分——prefix > regex > position > unmatched。
依赖:xfa_split_rule_contract、xfa_safe_regex、concurrent.futures。
逻辑:由预览 API 与正式提取调用;无网络、无脚本、无 LLM;
每条 rule 按 stages[] 顺序独立变换;显式 order 决定冲突判定次序;
同一行被多条流水线 select_line/select_line_range 认领 → needs_review;正式字段冲突 → needs_review。
逐行收集命中规则后按优先级决出唯一 segment;同优先级多个 mapped 命中 → needs_review;
全部候选命中写入 diagnostics;evidence_only 不写 Schema。
"""
from __future__ import annotations
import re
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import TimeoutError as FuturesTimeoutError
from dataclasses import dataclass, field
from typing import Any
from app.services.shipping_notice.document_layout.xfa_dataset import XfaLeafValue
from app.services.shipping_notice.document_layout.xfa_safe_regex import (
SafeRegexError,
compile_safe_regex,
search_safe,
)
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
XFA_SPLIT_REGEX_TIMEOUT_MS,
XFA_SPLIT_MATCHER_PRIORITY,
XfaSplitMatcher,
XfaSplitRule,
XfaSplitRuleSet,
XfaSplitStage,
get_xfa_split_max_input_length,
get_xfa_split_max_regex_groups,
get_xfa_split_max_regex_pattern_length,
get_xfa_split_regex_timeout_ms,
)
@@ -41,7 +48,7 @@ class XfaSplitSegmentResult:
target_field_code: str | None
rule_id: str
status: str
matcher_type: str # 兼容预览字段名:末级 stage type 或 unmatched
matcher_type: str
@dataclass
@@ -68,6 +75,18 @@ class XfaSplitEngineResult:
rule_version: int | None = None
@dataclass
class _LineMatch:
"""单行候选命中。"""
rule: XfaSplitRule
matcher_type: str
priority: int
line_text: str
normalized_text: str
raw_line: str
def _split_text_by_breaks(text: str, line_breaks: list[str]) -> list[str]:
"""
按声明的 line_breaks 切分文本(长分隔符优先)。
@@ -104,9 +123,9 @@ def _apply_line_normalization(
def _inventory_lines(raw_value: str, rule_set: XfaSplitRuleSet) -> list[str]:
"""
用规则集级 normalization 生成未匹配行盘点用的行清单。
用规则集级 normalization 生成行清单。
核心逻辑:尊重 normalization.line_breaks(不再忽略配置)。
核心逻辑:按 normalization.line_breaks 拆行并应用 trim / 去空行。
"""
norm = rule_set.normalization
lines = _split_text_by_breaks(raw_value or '', list(norm.line_breaks))
@@ -117,15 +136,20 @@ def _inventory_lines(raw_value: str, rule_set: XfaSplitRuleSet) -> list[str]:
)
def _extract_prefix(text: str, stage: XfaSplitStage) -> str | None:
"""前缀提取:标签 + 分隔符后的值。"""
label = str(stage.value or '')
hay = text if stage.case_sensitive else text.casefold()
needle = label if stage.case_sensitive else label.casefold()
def _extract_prefix_value(line: str, matcher: XfaSplitMatcher) -> str | None:
"""
前缀匹配:标签 + 分隔符后的值。
Returns:
提取值;无法匹配时 None。
"""
label = str(matcher.value or '')
hay = line if matcher.case_sensitive else line.casefold()
needle = label if matcher.case_sensitive else label.casefold()
if not hay.startswith(needle):
return None
rest = text[len(label):]
for sep in stage.separators:
rest = line[len(label):]
for sep in matcher.separators:
if rest.startswith(sep):
return rest[len(sep):].strip()
stripped = rest.lstrip()
@@ -134,50 +158,32 @@ def _extract_prefix(text: str, stage: XfaSplitStage) -> str | None:
return None
def _regex_search(text: str, pattern: str, *, case_sensitive: bool) -> re.Match[str] | None:
def _regex_extract_value(line: str, matcher: XfaSplitMatcher) -> tuple[str | None, str | None]:
"""
带超时的正则搜索。
Raises:
TimeoutError: 超过 XFA_SPLIT_REGEX_TIMEOUT_MS。
re.error: 编译失败。
"""
flags = 0 if case_sensitive else re.IGNORECASE
compiled = re.compile(pattern, flags)
timeout_s = max(XFA_SPLIT_REGEX_TIMEOUT_MS, 1) / 1000.0
def _run() -> re.Match[str] | None:
return compiled.search(text)
with ThreadPoolExecutor(max_workers=1) as pool:
future = pool.submit(_run)
try:
return future.result(timeout=timeout_s)
except FuturesTimeoutError as exc:
future.cancel()
raise TimeoutError('regex execution timed out') from exc
def _regex_capture(text: str, stage: XfaSplitStage) -> tuple[str | None, str | None]:
"""
正则捕获。
正则捕获单行文本。
Returns:
(value, error_code);成功时 error_code 为 None。
"""
pattern = str(matcher.pattern or '')
timeout_ms = get_xfa_split_regex_timeout_ms()
max_len = get_xfa_split_max_regex_pattern_length()
max_groups = get_xfa_split_max_regex_groups()
try:
matched = _regex_search(
text,
str(stage.pattern or ''),
case_sensitive=bool(stage.case_sensitive),
compiled = compile_safe_regex(
pattern,
case_sensitive=bool(matcher.case_sensitive),
max_length=max_len,
max_groups=max_groups,
)
matched = search_safe(compiled, line, timeout_ms=timeout_ms)
except SafeRegexError:
return None, 'regex_failed'
except TimeoutError:
return None, 'regex_timeout'
except re.error:
return None, 'regex_failed'
if not matched:
return None, 'regex_not_matched'
group = stage.capture_group
group = matcher.capture_group
try:
if group is None:
if matched.lastindex:
@@ -188,81 +194,104 @@ def _regex_capture(text: str, stage: XfaSplitStage) -> tuple[str | None, str | N
return None, 'regex_failed'
def _run_pipeline(
*,
raw_value: str,
rule: XfaSplitRule,
) -> tuple[str | None, set[int], str, str | None]:
def _match_line(line_no: int, line: str, rule: XfaSplitRule) -> tuple[_LineMatch | None, str | None]:
"""
执行单条规则的 stages 流水线。
判断单条规则是否命中指定行。
Returns:
(output_text, claimed_line_numbers, last_stage_type, error_code)
error_code 非空表示流水线失败。
(match, error_code):命中时 error_code 为 None;未命中时 match 为 None。
"""
state: str | list[str] = raw_value or ''
claimed_lines: set[int] = set()
last_type = 'pipeline'
for stage in rule.stages:
last_type = stage.type
if stage.type == 'split_lines':
if not isinstance(state, str):
return None, claimed_lines, last_type, 'stage_type_mismatch'
lines = _split_text_by_breaks(state, list(stage.line_breaks))
state = _apply_line_normalization(
lines,
trim=bool(stage.trim),
remove_empty_lines=bool(stage.remove_empty_lines),
)
continue
if stage.type == 'select_line':
if not isinstance(state, list):
return None, claimed_lines, last_type, 'stage_type_mismatch'
idx = int(stage.line_index or 0)
if idx < 1 or idx > len(state):
return None, claimed_lines, last_type, 'select_line_out_of_range'
claimed_lines = {idx}
state = state[idx - 1]
continue
if stage.type == 'select_line_range':
if not isinstance(state, list):
return None, claimed_lines, last_type, 'stage_type_mismatch'
start = int(stage.line_start or 0)
end = int(stage.line_end or 0)
if start < 1 or end < start or end > len(state):
return None, claimed_lines, last_type, 'select_line_range_out_of_range'
claimed_lines = set(range(start, end + 1))
separator = {'newline': '\n', 'space': ' ', 'comma': ', '}.get(stage.join_with, '\n')
state = separator.join(state[start - 1:end])
continue
if not isinstance(state, str):
return None, claimed_lines, last_type, 'stage_type_mismatch'
if stage.type == 'extract_prefix':
value = _extract_prefix(state, stage)
if value is None:
return None, claimed_lines, last_type, 'prefix_not_matched'
state = value
elif stage.type == 'regex_capture':
value, err = _regex_capture(state, stage)
if err:
return None, claimed_lines, last_type, err
state = str(value or '')
elif stage.type == 'replace':
state = state.replace(str(stage.find or ''), str(stage.replace_with or ''))
elif stage.type == 'substring':
start = int(stage.start or 0)
end = len(state) if stage.end is None else int(stage.end)
state = state[start:end]
elif stage.type == 'normalize':
text = state.strip() if stage.trim else state
if stage.remove_empty_lines:
text = re.sub(r'\s+', ' ', text).strip()
state = text
else:
return None, claimed_lines, last_type, 'unknown_stage'
if not isinstance(state, str):
return None, claimed_lines, last_type, 'pipeline_ended_on_lines'
return state, claimed_lines, last_type, None
matcher = rule.matcher
priority = XFA_SPLIT_MATCHER_PRIORITY.get(matcher.type)
if priority is None:
return None, 'unknown_matcher'
if matcher.type == 'position':
if int(matcher.line_index or 0) != line_no:
return None, None
normalized = line.strip() if line else ''
return _LineMatch(
rule=rule,
matcher_type='position',
priority=priority,
line_text=line,
normalized_text=normalized,
raw_line=line,
), None
if matcher.type == 'prefix':
extracted = _extract_prefix_value(line, matcher)
if extracted is None:
return None, None
return _LineMatch(
rule=rule,
matcher_type='prefix',
priority=priority,
line_text=line,
normalized_text=extracted,
raw_line=line,
), None
if matcher.type == 'regex':
value, err = _regex_extract_value(line, matcher)
if err:
return None, err
if value is None:
return None, None
return _LineMatch(
rule=rule,
matcher_type='regex',
priority=priority,
line_text=line,
normalized_text=value,
raw_line=line,
), None
return None, 'unknown_matcher'
def _pick_line_winner(
line_no: int,
matches: list[_LineMatch],
diagnostics: list[XfaSplitDiagnostic],
) -> _LineMatch | None:
"""
按 prefix > regex > position 决出单行唯一胜出规则。
核心逻辑:同优先级多个 mapped 命中 → duplicate_line_match;不同优先级取最高优先级。
"""
if not matches:
return None
diagnostics.append(XfaSplitDiagnostic(
code='line_match_candidates',
message='All matcher hits for line recorded',
line_no=line_no,
rule_ids=[item.rule.rule_id for item in matches],
))
best_priority = min(item.priority for item in matches)
tier = [item for item in matches if item.priority == best_priority]
mapped_tier = [item for item in tier if item.rule.segment.handling == 'mapped']
if len(mapped_tier) >= 2:
diagnostics.append(XfaSplitDiagnostic(
code='duplicate_line_match',
message='Multiple mapped rules matched the same line at the same priority',
line_no=line_no,
rule_ids=[item.rule.rule_id for item in mapped_tier],
))
if len(tier) == 1:
return tier[0]
if len(mapped_tier) == 1:
return mapped_tier[0]
if len(mapped_tier) >= 2:
return sorted(mapped_tier, key=lambda item: item.rule.rule_id)[0]
return sorted(tier, key=lambda item: item.rule.rule_id)[0]
def execute_split_rule_set(
@@ -272,87 +301,89 @@ def execute_split_rule_set(
lines: list[str] | None = None,
) -> XfaSplitEngineResult:
"""
对单个源字段原值执行多阶段拆分规则集。
对单个源字段原值执行拆分规则集。
核心逻辑:
1. 按 order 升序执行每条输出流水线;
2. select_line/select_line_range 认领行号;范围重叠 → duplicate_line_match;
3. 未认领行按 unmatched_line_policy;
4. 同一正式字段多段命中 → needs_review;
1. normalization.line_breaks 拆行;
2. 逐行收集命中规则,按 prefix > regex > position 决出唯一 segment;
3. 同优先级多个 mapped 命中 → duplicate_line_match / needs_review;
4. 未认领行按 unmatched_line_policy;
5. evidence_only 全部保留。
Args:
raw_value: 保留换行的原始叶子值。
rule_set: 已校验规则集。
lines: 可选预切分行(仅覆盖未匹配盘点;流水线仍从 raw 起步)。
lines: 可选预切分行(覆盖 normalization 结果)。
Returns:
XfaSplitEngineResult。
"""
if len(raw_value or '') > get_xfa_split_max_input_length():
return XfaSplitEngineResult(
status='needs_review',
diagnostics=[XfaSplitDiagnostic(
code='input_too_long',
message='Split source value exceeds max input length',
)],
rule_id=rule_set.rule_set_id,
rule_version=rule_set.rule_version,
)
inventory = list(lines) if lines is not None else _inventory_lines(raw_value, rule_set)
diagnostics: list[XfaSplitDiagnostic] = []
segments: list[XfaSplitSegmentResult] = []
line_claims: dict[int, list[str]] = {}
claimed_lines: set[int] = set()
ordered_rules = sorted(rule_set.rules, key=lambda item: (item.order, item.rule_id))
# [STEP 1] 逐行匹配并按优先级决出胜出规则。
for line_no, line in enumerate(inventory, start=1):
matches: list[_LineMatch] = []
for rule in rule_set.rules:
outcome, error = _match_line(line_no, line, rule)
if error:
diagnostics.append(XfaSplitDiagnostic(
code=error,
message=f'Rule {rule.rule_id} regex failed on line {line_no}',
line_no=line_no,
field_code=rule.segment.target_field_code,
rule_ids=[rule.rule_id],
))
continue
if outcome is not None:
matches.append(outcome)
# [STEP 1] 独立执行各输出流水线。
for rule in ordered_rules:
text, claimed_lines, last_type, error = _run_pipeline(raw_value=raw_value, rule=rule)
claimed_start = min(claimed_lines) if claimed_lines else None
claimed_end = max(claimed_lines) if claimed_lines else None
seg = rule.segment
if error:
diagnostics.append(XfaSplitDiagnostic(
code=error,
message=f'Pipeline {rule.rule_id} failed at stage type={last_type}: {error}',
line_no=claimed_start,
field_code=seg.target_field_code,
rule_ids=[rule.rule_id],
))
winner = _pick_line_winner(line_no, matches, diagnostics)
if winner is None:
continue
assert text is not None
for claimed_line in claimed_lines:
line_claims.setdefault(claimed_line, []).append(rule.rule_id)
claimed_lines.add(line_no)
seg = winner.rule.segment
status = 'parsed'
if not str(text).strip() and seg.handling == 'mapped':
if not str(winner.normalized_text).strip() and seg.handling == 'mapped':
status = 'needs_review'
diagnostics.append(XfaSplitDiagnostic(
code='mapped_value_empty',
message=f'Mapped segment {seg.segment_code} extracted empty value',
line_no=claimed_start,
line_no=line_no,
field_code=seg.target_field_code,
rule_ids=[rule.rule_id],
rule_ids=[winner.rule.rule_id],
))
segments.append(XfaSplitSegmentResult(
segment_id=seg.segment_id,
segment_code=seg.segment_code,
display_name=seg.display_name,
line_no=claimed_start,
line_end_no=claimed_end,
raw_text=str(text),
normalized_text=str(text).strip(),
line_no=line_no,
line_end_no=line_no,
raw_text=winner.raw_line,
normalized_text=winner.normalized_text,
handling=seg.handling,
target_field_id=seg.target_field_id,
target_field_code=seg.target_field_code,
rule_id=rule.rule_id,
rule_id=winner.rule.rule_id,
status=status,
matcher_type=last_type,
matcher_type=winner.matcher_type,
))
# [STEP 2] 同行多规则认领冲突(不再 break 短路)。
for line_no, rule_ids in sorted(line_claims.items()):
if len(rule_ids) > 1:
diagnostics.append(XfaSplitDiagnostic(
code='duplicate_line_match',
message='Multiple pipelines claimed the same line',
line_no=line_no,
rule_ids=list(rule_ids),
))
claimed_lines = set(line_claims)
# [STEP 3] 未匹配行。
# [STEP 2] 未匹配行。
for line_index, line in enumerate(inventory, start=1):
if line_index in claimed_lines:
continue
@@ -379,7 +410,7 @@ def execute_split_rule_set(
matcher_type='unmatched',
))
# [STEP 4] 聚合正式字段。
# [STEP 3] 聚合正式字段。
mapped_fields: dict[str, str] = {}
field_sources: dict[str, list[str]] = {}
overall = 'parsed'
@@ -410,9 +441,7 @@ def execute_split_rule_set(
overall = 'needs_review'
if any(d.code in {
'prefix_not_matched', 'regex_not_matched', 'regex_timeout', 'regex_failed',
'select_line_out_of_range', 'select_line_range_out_of_range',
'stage_type_mismatch', 'pipeline_ended_on_lines',
'regex_timeout', 'regex_failed', 'mapped_value_empty', 'input_too_long',
} for d in diagnostics):
overall = 'needs_review'
@@ -423,7 +452,7 @@ def execute_split_rule_set(
mapped_fields=mapped_fields,
evidence_only_segments=evidence_only,
diagnostics=diagnostics,
rule_id=rule_set.rule_id,
rule_id=rule_set.rule_set_id,
rule_version=rule_set.rule_version,
)
@@ -456,7 +485,7 @@ def project_split_result_safe(
核心逻辑:默认脱敏 mapped/segment 文本;仅当调用方已通过敏感读权限且
include_full_values=True 时返回 raw_text / 完整 mapped 值。
evidence_only_segments 仅作兼容字段;完整列表以 segments 为准。
evidence_only_segments 避免与 segments 重复展示(置空列表)。
Args:
result: 引擎输出。
@@ -498,7 +527,7 @@ def project_split_result_safe(
}
for item in result.segments
],
'evidence_only_segments': [], # 避免与 segments 重复展示;兼容字段置空
'evidence_only_segments': [],
'diagnostics': [
{
'code': item.code,
@@ -1,11 +1,11 @@
"""
backend/app/services/shipping_notice/document_layout/xfa_validation.py
用途:XFA 正式提取后的 AcroForm / 镜像集合 / 金额恒等式业务校验。
依赖:Decimal、xfa_contract、xfa_dataset、xfa_acroform、field_rules。
逻辑:由 order_extraction_workflow 在提取成功后调用;硬失败(mismatched/公式失败)
写入稳定 reason_code 进入 needs_review;AcroForm 状态区分
matched/partial/unavailable/skipped/mismatched,避免“缺字段却记 matched”。
用途:XFA 正式提取后的 AcroForm / 镜像集合 / 金额恒等式业务校验,以及统一视觉/证据指标。
依赖:Decimal、xfa_contract、xfa_dataset、xfa_acroform、split_rule_*。
逻辑:由 order_extraction_workflow / validation_service 在提取成功后调用;硬失败
(mismatched/公式失败)写入稳定 reason_code 进入 needs_review;AcroForm 状态区分
matched/partial/unavailable/skipped/mismatched;阶段 5 附加 visual/mirror/evidence 指标。
"""
from __future__ import annotations
@@ -22,6 +22,8 @@ from app.services.shipping_notice.document_layout.xfa_acroform import (
)
from app.services.shipping_notice.document_layout.xfa_contract import (
OrderXfaDatasetProfile,
XfaUnifiedFieldBinding,
is_formal_binding_publishable,
sanitize_xfa_dto,
)
from app.services.shipping_notice.document_layout.xfa_dataset import (
@@ -147,6 +149,38 @@ def _validate_line_amount_formula(line_maps: list[dict[str, Any]]) -> bool:
return True
def _line_amount_failures(line_maps: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""返回明细金额校验失败的具体行和值,供模板管理员定位映射或数据问题。"""
failures: list[dict[str, Any]] = []
for row_index, mapping in enumerate(line_maps, start=1):
quantity = _to_decimal(mapping.get('quantity'))
unit_price = _to_decimal(mapping.get('unit_price'))
amount = _to_decimal(mapping.get('amount'))
price_unit = _to_decimal(mapping.get('price_unit')) or Decimal('1')
if quantity is None or unit_price is None or amount is None or price_unit == 0:
failures.append({
'row_index': row_index,
'quantity': mapping.get('quantity'),
'unit_price': mapping.get('unit_price'),
'price_unit': mapping.get('price_unit'),
'amount': mapping.get('amount'),
'reason': 'missing_or_invalid_operand',
})
continue
expected = (quantity * unit_price) / price_unit
if expected.quantize(Decimal('0.01')) != amount.quantize(Decimal('0.01')) and expected != amount:
failures.append({
'row_index': row_index,
'quantity': str(quantity),
'unit_price': str(unit_price),
'price_unit': str(price_unit),
'amount': str(amount),
'expected_amount': str(expected),
'reason': 'amount_mismatch',
})
return failures
def _validate_total_equals_line_sum(
*,
header_fields: list[Any],
@@ -190,17 +224,17 @@ def _split_mirror_compare_plan(
)
]
path_id_to_data_path = {
str(item.path_id): str(item.data_path)
for item in profile.line_mapping.fields
if item.path_id and item.data_path
str(binding.value_binding.path_id): str(binding.value_binding.data_path)
for binding in profile.bindings
if binding.value_binding.path_id and binding.value_binding.data_path
}
split_source_paths: set[str] = set()
split_field_codes: set[str] = set()
line_fields = list(profile.line_mapping.fields)
line_bindings = [item for item in profile.bindings if item.scope == 'line']
for rule_set in rule_sets:
data_path = _resolve_split_source_data_path(
rule_set,
line_fields=line_fields,
line_bindings=line_bindings,
path_id_to_data_path=path_id_to_data_path,
)
if data_path:
@@ -244,7 +278,7 @@ def _validate_mirror_collections(
formal_rule_sets, split_source_paths, split_field_codes, path_id_to_data_path = (
_split_mirror_compare_plan(profile)
)
line_fields = list(profile.line_mapping.fields)
line_bindings = [item for item in profile.bindings if item.scope == 'line']
present_count = 0
for mirror_path in mirrors:
mirror_rows = read_collection_rows(dataset_analysis, mirror_path)
@@ -267,7 +301,7 @@ def _validate_mirror_collections(
for rule_set in formal_rule_sets:
auth_source_path = _resolve_split_source_data_path(
rule_set,
line_fields=line_fields,
line_bindings=line_bindings,
path_id_to_data_path=path_id_to_data_path,
)
if not auth_source_path:
@@ -319,7 +353,7 @@ def _validate_acroform(
profile: OrderXfaDatasetProfile,
extraction: XfaExtractionResult,
pdf_bytes: bytes | None,
) -> tuple[bool, str]:
) -> tuple[bool, str, list[dict[str, Any]]]:
"""
对账 datasets 标准化值与 AcroForm 展示值(表头单值 + 明细按行对齐)。
@@ -329,50 +363,61 @@ def _validate_acroform(
- 无 Fields / 无重叠字段 → unavailable;仅部分字段可对 → partial;冲突 → mismatched。
Returns:
(hard_ok, status):hard_ok=False 仅 mismatched;其余状态不阻断正式提取硬失败,
(hard_ok, status, mismatches):hard_ok=False 仅 mismatched;其余状态不阻断正式提取硬失败,
由 CQ 决定是否允许自动建单。
"""
if not profile.cross_checks.acroform_enabled:
return True, 'skipped'
return True, 'skipped', []
if not pdf_bytes:
return True, 'unavailable'
return True, 'unavailable', []
acro_fields = read_acroform_fields(pdf_bytes)
if not acro_fields:
return True, 'unavailable'
return True, 'unavailable', []
by_name = _acroform_values_by_local_name(acro_fields)
compared = 0
mismatched = 0
missing_counterpart = 0
mismatches: list[dict[str, Any]] = []
# [STEP 1] Header:每个映射对应短名的首个 AcroForm 实例。
for mapping in profile.header_mappings:
local = mapping.data_path.rsplit('/', 1)[-1].upper()
# [STEP 1] Header:每个 binding 对应短名的首个 AcroForm 实例。
for binding in profile.bindings:
if binding.scope != 'header':
continue
data_path = str(binding.value_binding.data_path or '')
local = data_path.rsplit('/', 1)[-1].upper()
acro_values = by_name.get(local) or []
if not acro_values:
missing_counterpart += 1
continue
dataset_value = None
for header in extraction.header_fields:
if header.mapping_id == mapping.mapping_id:
if header.mapping_id == binding.binding_id:
dataset_value = header.normalized_value
break
left = _normalize_comparable(dataset_value, value_type=mapping.value_type)
right = _normalize_comparable(acro_values[0], value_type=mapping.value_type)
left = _normalize_comparable(dataset_value)
right = _normalize_comparable(acro_values[0])
if left is None or right is None:
missing_counterpart += 1
continue
compared += 1
if left != right:
mismatched += 1
mismatches.append({
'scope': 'header', 'field_code': binding.field_code,
'dataset_value': left, 'acroform_value': right,
})
# [STEP 2] Line:按行索引对齐同名多实例 Widget。
for mapping in profile.line_mapping.fields:
local = mapping.data_path.rsplit('/', 1)[-1].upper()
for binding in profile.bindings:
if binding.scope != 'line':
continue
data_path = str(binding.value_binding.data_path or '')
local = data_path.rsplit('/', 1)[-1].upper()
acro_values = by_name.get(local) or []
dataset_values = _dataset_line_values_by_mapping(
extraction=extraction,
mapping_field_code=mapping.field_code,
mapping_field_code=binding.field_code,
)
if not dataset_values:
continue
@@ -383,22 +428,221 @@ def _validate_acroform(
if row_index >= len(acro_values):
missing_counterpart += 1
continue
left = _normalize_comparable(dataset_value, value_type=mapping.value_type)
right = _normalize_comparable(acro_values[row_index], value_type=mapping.value_type)
left = _normalize_comparable(dataset_value)
right = _normalize_comparable(acro_values[row_index])
if left is None or right is None:
missing_counterpart += 1
continue
compared += 1
if left != right:
mismatched += 1
mismatches.append({
'scope': 'line', 'row_index': row_index + 1,
'field_code': binding.field_code,
'dataset_value': left, 'acroform_value': right,
})
if mismatched > 0:
return False, 'mismatched'
return False, 'mismatched', mismatches
if compared == 0:
return True, 'unavailable'
return True, 'unavailable', []
if missing_counterpart > 0:
return True, 'partial'
return True, 'matched'
return True, 'partial', []
return True, 'matched', []
def collect_formal_schema_field_ids(
definition: dict[str, Any],
*,
schema_field_ids: set[str] | None = None,
) -> set[str]:
"""
收集正式 Schema 映射字段 ID(Header + Line + mapped split segments)。
核心逻辑:union bindings / header_mappings / line_mapping.fields / 已确认拆分 mapped 段的
target_field_id;若提供 schema_field_ids 则仅保留其中启用字段。
Args:
definition: XFA definition 字典。
schema_field_ids: 可选 Schema 启用字段 ID 集合;None 表示不过滤。
Returns:
正式字段 field_id 集合。
"""
formal: set[str] = set()
for item in definition.get('bindings') or []:
if isinstance(item, dict) and item.get('field_id'):
formal.add(str(item['field_id']))
for item in definition.get('header_mappings') or []:
if isinstance(item, dict) and item.get('field_id'):
formal.add(str(item['field_id']))
line_mapping = definition.get('line_mapping') if isinstance(definition.get('line_mapping'), dict) else {}
for item in line_mapping.get('fields') or []:
if isinstance(item, dict) and item.get('field_id'):
formal.add(str(item['field_id']))
for raw_rule in definition.get('split_rules') or []:
if not isinstance(raw_rule, dict):
continue
for rule in raw_rule.get('rules') or []:
if not isinstance(rule, dict):
continue
segment = rule.get('segment') if isinstance(rule.get('segment'), dict) else {}
if str(segment.get('handling') or '') != 'mapped':
continue
target_id = str(segment.get('target_field_id') or '').strip()
if target_id:
formal.add(target_id)
if schema_field_ids is not None:
formal &= set(schema_field_ids)
return {item for item in formal if item}
def compute_visual_coverage_rate(
definition: dict[str, Any],
*,
schema_field_ids: set[str] | None = None,
) -> float:
"""
计算正式字段视觉确认覆盖率。
核心逻辑:每个正式 Schema 字段须有一条 is_formal_binding_publishable 的统一绑定;
无正式字段时返回 1.0。
Args:
definition: XFA definition。
schema_field_ids: 可选 Schema 字段过滤。
Returns:
[0.0, 1.0] 覆盖率。
"""
formal_ids = collect_formal_schema_field_ids(definition, schema_field_ids=schema_field_ids)
if not formal_ids:
return 1.0
publishable_by_field: set[str] = set()
for raw in definition.get('bindings') or []:
if not isinstance(raw, dict):
continue
try:
binding = XfaUnifiedFieldBinding.model_validate(raw)
except (TypeError, ValueError):
continue
if is_formal_binding_publishable(binding):
publishable_by_field.add(str(binding.field_id))
covered = len(formal_ids & publishable_by_field)
return round(covered / len(formal_ids), 6)
def compute_mirror_consistency_rate(cross_check_summary: dict[str, Any] | None) -> float:
"""
由镜像对账摘要派生一致率。
核心逻辑:matched/skipped/unavailable → 1.0;mismatched → 0.0;未知 → 0.0。
Args:
cross_check_summary: validate_xfa_extraction 的 cross_check_summary。
Returns:
[0.0, 1.0] 一致率。
"""
summary = cross_check_summary if isinstance(cross_check_summary, dict) else {}
status = str(summary.get('mirror_status') or '').strip().lower()
if status in {'matched', 'skipped', 'unavailable'}:
return 1.0
if status == 'mismatched':
return 0.0
return 0.0
def compute_evidence_retention_rate(
*,
extraction: XfaExtractionResult | None = None,
evidence_segments: list[dict[str, Any]] | None = None,
expected_line_nos: set[int] | None = None,
) -> float:
"""
计算 evidence_only 行保留率。
核心逻辑:
1. 若给出 expected_line_nos,以提取结果中实际保留的 line_no 求交占比;
2. 否则从 extraction 的 split_evidence / evidence_summary.header_split_evidence 统计,
有拆分证据时视为 1.0(引擎已产出即保留),无拆分时 1.0。
Args:
extraction: 正式提取结果(可含 split_evidence)。
evidence_segments: 可选显式证据段列表。
expected_line_nos: 期望保留的行号集合(如 {2,4,5})。
Returns:
[0.0, 1.0] 保留率。
"""
segments: list[dict[str, Any]] = list(evidence_segments or [])
if extraction is not None and not segments:
for row in getattr(extraction, 'rows', None) or []:
if isinstance(row, dict):
segments.extend(
item for item in (row.get('split_evidence') or []) if isinstance(item, dict)
)
summary = getattr(extraction, 'evidence_summary', None) or {}
if isinstance(summary, dict):
segments.extend(
item for item in (summary.get('header_split_evidence') or []) if isinstance(item, dict)
)
if expected_line_nos is not None:
if not expected_line_nos:
return 1.0
retained: set[int] = set()
for item in segments:
raw_line = item.get('line_no')
if raw_line is None:
continue
try:
retained.add(int(raw_line))
except (TypeError, ValueError):
continue
return round(len(expected_line_nos & retained) / len(expected_line_nos), 6)
# 无期望行号:拆分引擎已写入的 evidence 视为完整保留。
return 1.0
def build_xfa_validation_metrics(
*,
definition: dict[str, Any],
extraction: XfaExtractionResult | None = None,
cross_check_summary: dict[str, Any] | None = None,
schema_field_ids: set[str] | None = None,
expected_evidence_line_nos: set[int] | None = None,
) -> dict[str, float]:
"""
组装统一验证指标(视觉覆盖 / 镜像一致 / 证据保留)。
Args:
definition: XFA definition。
extraction: 可选提取结果(证据保留率)。
cross_check_summary: 可选对账摘要(镜像一致率)。
schema_field_ids: 可选 Schema 字段过滤。
expected_evidence_line_nos: 可选期望 evidence_only 行号。
Returns:
含 visual_coverage_rate / mirror_consistency_rate / evidence_retention_rate 的字典。
"""
return {
'visual_coverage_rate': compute_visual_coverage_rate(
definition, schema_field_ids=schema_field_ids,
),
'mirror_consistency_rate': compute_mirror_consistency_rate(cross_check_summary),
'evidence_retention_rate': compute_evidence_retention_rate(
extraction=extraction,
expected_line_nos=expected_evidence_line_nos,
),
}
def definition_has_unified_bindings(definition: dict[str, Any]) -> bool:
"""判断 definition 是否已进入统一 bindings 模式(非空 bindings 列表)。"""
bindings = definition.get('bindings')
return isinstance(bindings, list) and len(bindings) > 0
def validate_xfa_extraction(
@@ -407,6 +651,8 @@ def validate_xfa_extraction(
dataset_analysis: XfaDatasetAnalysis,
extraction: XfaExtractionResult,
pdf_bytes: bytes | None = None,
schema_field_ids: set[str] | None = None,
expected_evidence_line_nos: set[int] | None = None,
) -> XfaValidationResult:
"""
执行 XFA 提取后的确定性业务校验。
@@ -415,13 +661,16 @@ def validate_xfa_extraction(
1. 镜像集合标准化一致性;
2. AcroForm 关键字段标准化一致性;
3. 明细金额公式 quantity×unit_price;
4. Header 总金额与明细合计。
4. Header 总金额与明细合计;
5. 附加 visual/mirror/evidence 指标(不直接因指标失败,由发布门禁消费)。
Args:
raw_profile: 冻结 Profile 快照。
dataset_analysis: datasets 分析。
extraction: 提取结果。
pdf_bytes: 可选原始 PDF,用于 AcroForm 对账。
schema_field_ids: 可选 Schema 字段过滤(视觉覆盖率)。
expected_evidence_line_nos: 可选期望 evidence_only 行号。
Returns:
XfaValidationResult。
@@ -438,7 +687,9 @@ def validate_xfa_extraction(
reason_codes: list[str] = []
line_field_paths = {
item.field_code: item.data_path for item in profile.line_mapping.fields
binding.field_code: str(binding.value_binding.data_path or '')
for binding in profile.bindings
if binding.scope == 'line' and binding.value_binding.data_path
}
summary: dict[str, Any] = {
'mirror_collection_policy': profile.cross_checks.mirror_collection_policy,
@@ -458,7 +709,7 @@ def validate_xfa_extraction(
summary['mirror_status'] = mirror_status
# [STEP 2] AcroForm(按行对齐;状态含 matched/partial/unavailable)
acro_ok, acro_status = _validate_acroform(
acro_ok, acro_status, acro_mismatches = _validate_acroform(
profile=profile,
extraction=extraction,
pdf_bytes=pdf_bytes,
@@ -466,16 +717,20 @@ def validate_xfa_extraction(
if not acro_ok:
reason_codes.append('xfa_acroform_mismatch')
summary['acroform_status'] = acro_status
summary['acroform_mismatches'] = acro_mismatches
line_maps = _field_map_from_rows(extraction.rows)
# [STEP 3] 明细金额公式
if profile.cross_checks.line_amount_formula == 'quantity_times_unit_price':
if not _validate_line_amount_formula(line_maps):
line_amount_failures = _line_amount_failures(line_maps)
if line_amount_failures:
reason_codes.append('xfa_business_validation_failed')
summary['line_amount_status'] = 'failed'
summary['line_amount_failures'] = line_amount_failures
else:
summary['line_amount_status'] = 'passed'
summary['line_amount_failures'] = []
else:
summary['line_amount_status'] = 'skipped'
@@ -493,6 +748,16 @@ def validate_xfa_extraction(
else:
summary['total_amount_status'] = 'skipped'
# [STEP 5] 统一验证指标(发布门禁消费;此处不直接 fail)
metrics = build_xfa_validation_metrics(
definition=definition,
extraction=extraction,
cross_check_summary=summary,
schema_field_ids=schema_field_ids,
expected_evidence_line_nos=expected_evidence_line_nos,
)
summary.update(metrics)
return XfaValidationResult(
passed=not reason_codes,
reason_codes=reason_codes,
@@ -0,0 +1,336 @@
"""
backend/app/services/shipping_notice/document_layout/xfa_visual_binding.py
用途:XFA 统一视觉绑定的候选评分、歧义诊断与建议结果组装(纯函数,不写数据库)。
依赖:xfa_acroform、xfa_dataset、xfa_contract(归一化框与 path 哈希)。
逻辑:由 order_document_profile_visual_binding_service 调用;画框或 Widget 命中后
返回 suggested 候选列表与 diagnostics;高置信也不得自动 confirmed。
"""
from __future__ import annotations
import hashlib
from dataclasses import dataclass, field
from typing import Any, Literal
from app.services.shipping_notice.document_layout.xfa_acroform import (
XfaAcroformWidget,
build_widget_path_candidates,
read_acroform_widgets,
)
from app.services.shipping_notice.document_layout.xfa_contract import hash_data_path
from app.services.shipping_notice.document_layout.xfa_dataset import XfaDatasetAnalysis
VisualCandidateStatus = Literal['suggested']
@dataclass(frozen=True)
class VisualPathCandidate:
"""datasets 路径候选摘要(不含完整 XPath 明文时可仅含 hash)。"""
path_id: str
data_path_hash: str
dataset_value_masked: str
match_hint: str
confidence: float
@dataclass
class VisualBindingCandidate:
"""单个 Widget/区域视觉绑定候选;status 恒为 suggested,禁止自动 confirmed。"""
candidate_id: str
widget_id: str
page_no: int
normalized_bbox: dict[str, float]
acroform_field_name_tail: str
display_value_masked: str
path_candidates: list[VisualPathCandidate] = field(default_factory=list)
overlap_score: float = 0.0
value_match_score: float = 0.0
confidence: float = 0.0
status: VisualCandidateStatus = 'suggested'
@dataclass
class VisualBindingDiagnostics:
"""歧义与覆盖诊断;供管理员确认前展示。"""
candidate_count: int = 0
ambiguous: bool = False
ambiguity_reason: str | None = None
top_confidence: float = 0.0
second_confidence: float = 0.0
auto_confirm_blocked: bool = True
notes: list[str] = field(default_factory=list)
def _bbox_area(bbox: dict[str, float]) -> float:
"""计算归一化框面积;非法框返回 0。"""
x0 = float(bbox.get('x0') or 0)
y0 = float(bbox.get('y0') or 0)
x1 = float(bbox.get('x1') or 0)
y1 = float(bbox.get('y1') or 0)
if x1 <= x0 or y1 <= y0:
return 0.0
return (x1 - x0) * (y1 - y0)
def _bbox_intersection_area(a: dict[str, float], b: dict[str, float]) -> float:
"""两框交集面积。"""
x0 = max(float(a.get('x0') or 0), float(b.get('x0') or 0))
y0 = max(float(a.get('y0') or 0), float(b.get('y0') or 0))
x1 = min(float(a.get('x1') or 0), float(b.get('x1') or 0))
y1 = min(float(a.get('y1') or 0), float(b.get('y1') or 0))
if x1 <= x0 or y1 <= y0:
return 0.0
return (x1 - x0) * (y1 - y0)
def _bbox_overlap_score(region: dict[str, float], widget_bbox: dict[str, float]) -> float:
"""
区域与 Widget 框重叠得分(IoU 优先,退化时为交集占区域面积比)。
Args:
region: 用户画框或查询区域(0..1)。
widget_bbox: AcroForm Widget 归一化框。
Returns:
0..1 重叠得分。
"""
intersection = _bbox_intersection_area(region, widget_bbox)
if intersection <= 0:
return 0.0
region_area = _bbox_area(region)
widget_area = _bbox_area(widget_bbox)
union = region_area + widget_area - intersection
if union > 0:
return intersection / union
return intersection / region_area if region_area > 0 else 0.0
def _normalize_compare_value(value: str) -> str:
"""值对账用的空白无关规范化。"""
return ''.join(str(value or '').casefold().split())
def _value_match_score(display_value: str, dataset_value: str) -> float:
"""
页面展示值与 datasets 叶子值的标准化匹配分。
Returns:
1.0 精确匹配;0.5 包含关系;0 不匹配。
"""
left = _normalize_compare_value(display_value)
right = _normalize_compare_value(dataset_value)
if not left or not right:
return 0.0
if left == right:
return 1.0
if left in right or right in left:
return 0.5
return 0.0
def _candidate_id(widget_id: str, path_id: str) -> str:
"""生成稳定的候选 ID(不含敏感明文)。"""
digest = hashlib.sha256(f'{widget_id}:{path_id}'.encode('utf-8')).hexdigest()[:16]
return f'vbc-{digest}'
def _diagnose_ambiguity(candidates: list[VisualBindingCandidate]) -> VisualBindingDiagnostics:
"""
诊断候选歧义;同分或接近时标记 ambiguous,且始终阻断自动确认。
Args:
candidates: 已按 confidence 降序排列的候选。
Returns:
诊断摘要。
"""
diagnostics = VisualBindingDiagnostics(candidate_count=len(candidates))
if not candidates:
diagnostics.notes.append('no_widget_overlap')
return diagnostics
diagnostics.top_confidence = float(candidates[0].confidence)
if len(candidates) > 1:
diagnostics.second_confidence = float(candidates[1].confidence)
# [STEP 1] 高置信接近时视为歧义,禁止自动确认
if len(candidates) >= 2 and abs(diagnostics.top_confidence - diagnostics.second_confidence) < 0.05:
diagnostics.ambiguous = True
diagnostics.ambiguity_reason = 'top_candidates_too_close'
elif len(candidates) >= 2 and diagnostics.top_confidence >= 0.85 and diagnostics.second_confidence >= 0.75:
diagnostics.ambiguous = True
diagnostics.ambiguity_reason = 'multiple_high_confidence'
top_paths = candidates[0].path_candidates
if len(top_paths) > 1:
diagnostics.ambiguous = True
diagnostics.ambiguity_reason = diagnostics.ambiguity_reason or 'multiple_path_candidates'
diagnostics.auto_confirm_blocked = True
return diagnostics
def suggest_visual_binding_candidates(
*,
page_no: int,
normalized_bbox: dict[str, float],
dataset_analysis: XfaDatasetAnalysis,
pdf_bytes: bytes | None = None,
widgets: list[XfaAcroformWidget] | None = None,
min_overlap: float = 0.05,
) -> dict[str, Any]:
"""
为指定页面区域生成 AcroForm Widget → datasets 路径的视觉绑定候选。
核心逻辑:按框重叠筛选 Widget → 为每个 Widget 生成路径候选 → 综合重叠与值匹配
评分;所有候选 status 恒为 suggested,歧义写入 diagnostics。
Args:
page_no: 目标 PDF 页码(1-based)。
normalized_bbox: 用户画框或查询区域(0..1,左上原点)。
dataset_analysis: 已解析的 datasets 结构。
pdf_bytes: 原始 PDF;widgets 未传入时用于读取 AcroForm Widget。
widgets: 可选预读 Widget 列表(测试/mock 用)。
min_overlap: 最小 IoU/重叠阈值。
Returns:
{candidates, diagnostics, page_no, normalized_bbox} 安全 DTO。
"""
region = {
'x0': float(normalized_bbox.get('x0') or 0),
'y0': float(normalized_bbox.get('y0') or 0),
'x1': float(normalized_bbox.get('x1') or 0),
'y1': float(normalized_bbox.get('y1') or 0),
}
if _bbox_area(region) <= 0:
return {
'page_no': int(page_no),
'normalized_bbox': region,
'candidates': [],
'diagnostics': VisualBindingDiagnostics(
candidate_count=0,
notes=['invalid_region_bbox'],
).__dict__,
}
widget_list = list(widgets or [])
if not widget_list and pdf_bytes:
widget_list = read_acroform_widgets(pdf_bytes)
candidates: list[VisualBindingCandidate] = []
for widget in widget_list:
if int(widget.page_no) != int(page_no):
continue
overlap = _bbox_overlap_score(region, widget.normalized_bbox)
if overlap < float(min_overlap):
continue
path_items = build_widget_path_candidates(
widget=widget,
dataset_analysis=dataset_analysis,
)
path_candidates: list[VisualPathCandidate] = []
best_value_score = 0.0
for item in path_items:
value_score = _value_match_score(widget.value, item.get('raw_value') or '')
best_value_score = max(best_value_score, value_score)
path_candidates.append(VisualPathCandidate(
path_id=str(item.get('path_id') or ''),
data_path_hash=str(item.get('data_path_hash') or ''),
dataset_value_masked=str(item.get('dataset_value_masked') or ''),
match_hint=str(item.get('match_hint') or 'unmatched'),
confidence=round(min(1.0, overlap * 0.6 + value_score * 0.4), 4),
))
confidence = round(min(1.0, overlap * 0.55 + best_value_score * 0.45), 4)
top_path_id = path_candidates[0].path_id if path_candidates else ''
candidates.append(VisualBindingCandidate(
candidate_id=_candidate_id(widget.widget_id, top_path_id or widget.widget_id),
widget_id=widget.widget_id,
page_no=int(widget.page_no),
normalized_bbox=dict(widget.normalized_bbox),
acroform_field_name_tail=widget.short_name,
display_value_masked=widget.value_masked,
path_candidates=path_candidates,
overlap_score=round(overlap, 4),
value_match_score=round(best_value_score, 4),
confidence=confidence,
status='suggested',
))
candidates.sort(key=lambda item: (-item.confidence, item.widget_id))
diagnostics = _diagnose_ambiguity(candidates)
return {
'page_no': int(page_no),
'normalized_bbox': region,
'candidates': [
{
'candidate_id': item.candidate_id,
'widget_id': item.widget_id,
'page_no': item.page_no,
'normalized_bbox': item.normalized_bbox,
'acroform_field_name_tail': item.acroform_field_name_tail,
'display_value_masked': item.display_value_masked,
'path_candidates': [
{
'path_id': path.path_id,
'data_path_hash': path.data_path_hash,
'dataset_value_masked': path.dataset_value_masked,
'match_hint': path.match_hint,
'confidence': path.confidence,
}
for path in item.path_candidates
],
'overlap_score': item.overlap_score,
'value_match_score': item.value_match_score,
'confidence': item.confidence,
'status': item.status,
}
for item in candidates
],
'diagnostics': {
'candidate_count': diagnostics.candidate_count,
'ambiguous': diagnostics.ambiguous,
'ambiguity_reason': diagnostics.ambiguity_reason,
'top_confidence': diagnostics.top_confidence,
'second_confidence': diagnostics.second_confidence,
'auto_confirm_blocked': diagnostics.auto_confirm_blocked,
'notes': list(diagnostics.notes),
},
}
def visual_binding_audit_snapshot(binding: dict[str, Any] | None) -> dict[str, Any] | None:
"""
提取视觉绑定审计摘要(before/after 用),不含 datasets 明文路径。
Args:
binding: 统一 binding 字典或 None。
Returns:
含 status、bbox、page_no、confidence 的摘要;None 表示无绑定。
"""
if not isinstance(binding, dict):
return None
visual = binding.get('visual_binding') if isinstance(binding.get('visual_binding'), dict) else {}
if not visual:
return None
bbox = visual.get('normalized_bbox') if isinstance(visual.get('normalized_bbox'), dict) else {}
value = binding.get('value_binding') if isinstance(binding.get('value_binding'), dict) else {}
return {
'binding_id': binding.get('binding_id'),
'field_id': binding.get('field_id'),
'field_code': binding.get('field_code'),
'status': visual.get('status'),
'page_no': visual.get('page_no'),
'normalized_bbox': {
'x0': bbox.get('x0'),
'y0': bbox.get('y0'),
'x1': bbox.get('x1'),
'y1': bbox.get('y1'),
},
'source': visual.get('source'),
'confidence': visual.get('confidence'),
'path_id': value.get('path_id'),
'data_path_hash': hash_data_path(str(value.get('data_path') or '')) if value.get('data_path') else None,
}