feat(shipping-notice): 落地 XFA 拆分、版面签名、统一进度与处理域履约

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
hugoandCursor committed 2026-08-06 10:18:37 +08:00
1 parent 3a9fbac2fc
commit d2b3d74def
571 files changed
+78064 -24681

No files matched your search

@@ -1,11 +1,12 @@
"""
backend/app/services/shipping_notice/document_layout/contracts.py
用途:定义解析器无关的 shipping_document_layout.v1 契约、稳定标识和完整性校验。
用途:定义解析器无关的 shipping_document_layout.v1 契约、稳定标识和完整性校验;
并再导出 XFA 阶段 0 契约入口,供布局与 Profile 模块统一引用。
依赖:Pydantic 2、标准库 hashlib/json/unicodedata;字段高亮质量枚举与
field_highlight_contract 对齐(本模块只声明可挂载到 LayoutCell 的状态字面量)。
field_highlight_contract 对齐;XFA 鉴别联合与路径语法见同目录 xfa_contract。
逻辑:PDF/OCR/HTML 解析器先构造 LayoutDocument;持久化、Schema 映射和评测只接受通过
本模块校验的结果;复核高亮投影消费 cell/token 坐标,但不在本契约内裁决绘制质量。
本模块校验的结果;XFA datasets 模式不走本模块几何契约,改由 xfa_contract 约束。
"""
from __future__ import annotations
@@ -18,6 +19,21 @@ from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from app.services.shipping_notice.document_layout.xfa_contract import ( # noqa: F401
ORDER_PROFILE_TEMPLATE_MODES,
XFA_CONTRACT_VERSION,
XFA_DOCUMENT_KINDS,
XFA_DTO_FORBIDDEN_KEYS,
XFA_EVIDENCE_SOURCES,
XFA_SUPPORTED_DOCUMENT_KINDS,
OrderXfaDatasetProfile,
compute_dataset_structure_fingerprint,
normalize_template_mode,
sanitize_xfa_dto,
validate_controlled_data_path,
validate_xfa_dataset_definition,
)
LAYOUT_SCHEMA_VERSION = 'shipping_document_layout.v1'
# 与 field_highlight_contract.HIGHLIGHT_QUALITY_VALUES 对齐;Cell 可选挂载,禁止自创同义状态。
@@ -1,26 +1,99 @@
"""
services/shipping_notice/document_layout/coordinate_region_text.py
用途:统一从页面坐标字符中读取受控区域文字。
依赖:冻结 layout 的 page_glyphs/tables 字符坐标契约。
逻辑:标注取字、模板匹配和版本诊断共同使用视觉行聚类与行内横坐标排序,避免阅读顺序分叉。
用途:统一从页面坐标字符中读取受控区域文字,并恢复可靠的原始文本流空白。
依赖:冻结 layout 的 page_glyphs/tables 字符坐标契约、PositionedCharacter 可选边界字段。
逻辑:标注取字、模板匹配、字段抽取和版本诊断共享“原始边界优先、几何间距兜底”的渲染规则。
"""
from __future__ import annotations
from typing import Any
from typing import Any, Literal
def visual_text_lines(glyphs: list[dict[str, Any]]) -> list[str]:
def render_positioned_row(
glyphs: list[Any], *, geometry_gap_limit: float | None = None,
geometry_gap_ratio: float | None = None,
geometry_width_mode: Literal['previous', 'average'] = 'average',
minimum_gap_limit: float = 0.0,
) -> str:
"""
将坐标字符按视觉行恢复为阅读顺序文本。
将单个视觉行按横坐标渲染,优先采用 PDF 原始文本流的明确空白边界。
核心逻辑:boundary_before 为 space/line_break 时恢复一个普通空格;只有旧版证据或
OCR 没有该边界时,才按调用方提供的几何阈值兜底,避免料号、金额被全局拆分。
Args:
glyphs: 含 text 与 bbox 的页面字符;无效字符会被忽略。
glyphs: 字典或 PositionedCharacter;必须包含 text 与 bbox。
geometry_gap_limit: 可选固定几何阈值,适合以中位字宽计算的旧链路。
geometry_gap_ratio: 可选动态比例;按相邻字宽逐对计算,保持旧版模板阈值口径。
geometry_width_mode: previous 使用左字符宽度,average 使用相邻平均字宽。
minimum_gap_limit: 动态阈值的最小页面距离,防止极窄 glyph 过度分词。
Returns:
从上到下的文本行;同行字符按 x0 排序,并按视觉间距恢复单个空格。
保留原文字面值的单行文本;相邻重复空白折叠为一个普通空格。
"""
ordered = sorted(glyphs, key=lambda item: (_glyph_bbox_value(item, 'x0'), _glyph_source_index(item)))
parts: list[str] = []
previous_x1: float | None = None
previous_width: float | None = None
for glyph in ordered:
text = _glyph_value(glyph, 'text')
if not text:
continue
boundary = str(_glyph_value(glyph, 'boundary_before') or 'none')
x0, x1 = _glyph_bbox_value(glyph, 'x0'), _glyph_bbox_value(glyph, 'x1')
width = max(0.01, x1 - x0)
explicit_space = boundary in {'space', 'line_break'}
resolved_gap_limit = geometry_gap_limit
if geometry_gap_ratio is not None and previous_width is not None:
reference_width = (
previous_width if geometry_width_mode == 'previous'
else (previous_width + width) / 2
)
resolved_gap_limit = max(minimum_gap_limit, reference_width * geometry_gap_ratio)
fallback_space = (
boundary == 'none'
and resolved_gap_limit is not None
and previous_x1 is not None
and x0 - previous_x1 > resolved_gap_limit
)
if (explicit_space or fallback_space) and parts and not parts[-1].endswith(' ') and not text.isspace():
parts.append(' ')
parts.append(text)
previous_x1 = x1
previous_width = width
return ''.join(parts).strip()
def _glyph_value(glyph: Any, key: str) -> Any:
"""兼容冻结字典和 Pydantic 字符模型读取字段,避免各坐标链路重复分支。"""
return glyph.get(key) if isinstance(glyph, dict) else getattr(glyph, key, None)
def _glyph_bbox_value(glyph: Any, key: str) -> float:
"""从字典或 LayoutBBox 中读取坐标;调用方已过滤缺失 bbox 的异常字符。"""
bbox = _glyph_value(glyph, 'bbox')
value = bbox.get(key) if isinstance(bbox, dict) else getattr(bbox, key)
return float(value)
def _glyph_source_index(glyph: Any) -> int:
"""以原始文本流序号稳定同坐标字符顺序;旧证据缺失时保持横坐标排序结果。"""
value = _glyph_value(glyph, 'source_index')
return int(value) if value is not None else 0
def visual_glyph_rows(glyphs: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
"""将坐标字符按视觉行分组,供表头签名与运行时 Matcher 共享同一阅读顺序。
Args:
glyphs: 含 text 与 bbox 的页面字符。
Returns:
从上到下的字符行;每行字符已按 x0 排序。
"""
# 行高容差与锨点匹配保持一致,防止同一 PDF 在签名和运行比对时产生不同行序。
rows: list[list[dict[str, Any]]] = []
for glyph in sorted(
glyphs,
@@ -46,20 +119,75 @@ def visual_text_lines(glyphs: list[dict[str, Any]]) -> list[str]:
continue
rows.append([glyph])
lines: list[str] = []
for row in rows:
ordered = sorted(row, key=lambda item: float((item.get('bbox') or {}).get('x0', 0)))
parts: list[str] = []
return [
sorted(row, key=lambda item: float((item.get('bbox') or {}).get('x0', 0)))
for row in rows
]
def positioned_token_spans(
glyphs: list[dict[str, Any]], *, respect_explicit_spaces: bool = True,
) -> list[dict[str, Any]]:
"""
从视觉行中恢复带横向边界的 token。
Args:
glyphs: 含坐标的页面字符。
respect_explicit_spaces: False 时仅依赖显著几何间隔分列,用于抹平新旧
PDF 证据是否保存 boundary_before 的差异。
Returns:
从上到下、从左到右的 token 及其绝对横向边界。
"""
spans: list[dict[str, Any]] = []
for row in visual_glyph_rows(glyphs):
current: list[dict[str, Any]] = []
previous_x1: float | None = None
previous_width = 0.0
for item in ordered:
box = item['bbox']
x0, x1 = float(box['x0']), float(box['x1'])
if previous_x1 is not None and x0 - previous_x1 > max(1.5, previous_width * 1.45):
parts.append(' ')
parts.append(str(item.get('text') or ''))
previous_x1, previous_width = x1, max(1.0, x1 - x0)
text = ''.join(parts).strip()
previous_width: float | None = None
for glyph in row:
bbox = glyph.get('bbox') or {}
try:
x0, x1 = float(bbox['x0']), float(bbox['x1'])
except (KeyError, TypeError, ValueError):
continue
width = max(0.01, x1 - x0)
boundary = str(glyph.get('boundary_before') or 'none')
geometry_space = (
previous_x1 is not None
and previous_width is not None
and x0 - previous_x1 > max(1.5, previous_width * (1.45 if respect_explicit_spaces else 0.75))
)
explicit_space = respect_explicit_spaces and boundary in {'space', 'line_break'}
if current and (explicit_space or geometry_space):
spans.append(_positioned_span(current))
current = []
current.append(glyph)
previous_x1, previous_width = x1, width
if current:
spans.append(_positioned_span(current))
return [item for item in spans if item.get('text')]
def _positioned_span(glyphs: list[dict[str, Any]]) -> dict[str, Any]:
"""渲染单个 token 并返回其绝对横向边界。"""
ordered = sorted(glyphs, key=lambda item: float((item.get('bbox') or {}).get('x0', 0)))
return {
'text': render_positioned_row(ordered),
'x0': min(float(item['bbox']['x0']) for item in ordered),
'x1': max(float(item['bbox']['x1']) for item in ordered),
}
def visual_text_lines(glyphs: list[dict[str, Any]]) -> list[str]:
"""将坐标字符按视觉行恢复为阅读顺序文本。"""
lines: list[str] = []
for ordered in visual_glyph_rows(glyphs):
text = render_positioned_row(
ordered,
geometry_gap_ratio=1.45,
geometry_width_mode='previous',
minimum_gap_limit=1.5,
)
if text:
lines.append(text)
return lines
@@ -15,6 +15,7 @@ from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, model_validator
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.coordinate_region_text import render_positioned_row
from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter
from app.services.shipping_notice.document_layout.order_profile_extractors import extract_profile_field_value
from app.services.shipping_notice.reservation_id import validated_reservation_id
@@ -186,9 +187,10 @@ class HeaderLayoutSuggestion(CoordinateReconstructionModel):
class CoordinateProfileLogicalRow(CoordinateReconstructionModel):
"""v2 坐标模板重建的一条逻辑明细,字段仍由上层 Schema 规范化。"""
"""坐标模板重建的一条逻辑明细,并保留每个字段的原生 glyph 几何证据。"""
fields: dict[str, str] = Field(default_factory=dict)
field_evidence: dict[str, dict[str, Any]] = Field(default_factory=dict)
source_row_indices: list[int] = Field(min_length=1)
role: Literal['data', 'deleted'] = 'data'
issues: list[str] = Field(default_factory=list)
@@ -354,9 +356,12 @@ def reconstruct_coordinate_profile_rows(
if relative_y_rows is not None:
return relative_y_rows
def values_for(band: list[tuple[int, PositionedCharacter]], layout: dict[str, Any]) -> tuple[dict[str, str], list[str]]:
"""按当前物理行读取字段列;标注区域的纵向位置只表达子行版式,不限定绝对页坐标。"""
def values_for(
band: list[tuple[int, PositionedCharacter]], layout: dict[str, Any],
) -> tuple[dict[str, str], dict[str, dict[str, Any]], list[str]]:
"""读取字段值和同源 glyph 几何;纵向位置只表达子行版式,不限定绝对页坐标。"""
values: dict[str, str] = {}
evidence: dict[str, dict[str, Any]] = {}
issues: list[str] = []
for field in layout.get('field_regions') or []:
if not isinstance(field, dict) or not isinstance(field.get('region'), dict):
@@ -365,7 +370,8 @@ def reconstruct_coordinate_profile_rows(
if not code:
continue
region = _absolute_relative_region(bbox, field['region'])
text = _text_in_horizontal_region(band, region)
selected = [item for item in band if _inside_horizontal_region(item[1].bbox, region)]
text = _text_in_horizontal_region(selected, region)
if text:
extracted = extract_profile_field_value(
extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=text,
@@ -378,21 +384,24 @@ def reconstruct_coordinate_profile_rows(
issues.append(f'coordinate_profile_composite_conflict:{extracted_code}')
else:
values[extracted_code] = extracted_value
return values, issues
evidence[extracted_code] = _field_glyph_evidence(selected, text=text)
return values, evidence, issues
results: list[CoordinateProfileLogicalRow] = []
current: dict[str, str] | None = dict(initial_fields) if initial_fields else None
current_evidence: dict[str, dict[str, Any]] = {}
sources: list[int] = []
next_offset = initial_next_offset if current is not None else 0
current_issues: list[str] = []
def flush(*, role: Literal['data', 'deleted'] = 'data') -> None:
nonlocal current, sources, next_offset, current_issues
nonlocal current, current_evidence, sources, next_offset, current_issues
if current is not None and (sources or initial_fields):
results.append(CoordinateProfileLogicalRow(
fields=current, source_row_indices=sources, role=role, issues=current_issues,
fields=current, field_evidence=current_evidence,
source_row_indices=sources, role=role, issues=current_issues,
))
current, sources, next_offset, current_issues = None, [], 0, []
current, current_evidence, sources, next_offset, current_issues = None, {}, [], 0, []
for row_index, band in enumerate(_group_visual_rows(glyphs)):
text = ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)).strip()
@@ -404,10 +413,11 @@ def reconstruct_coordinate_profile_rows(
# the role to exclude it rather than silently losing the document row.
flush(role='deleted')
continue
main_values, main_issues = values_for(band, ordered_layouts[0])
main_values, main_evidence, main_issues = values_for(band, ordered_layouts[0])
if is_valid_line_start_value(main_values.get(start_field_code, '')):
flush()
current, sources, next_offset, current_issues = main_values, [row_index], 1, main_issues
current, current_evidence = main_values, main_evidence
sources, next_offset, current_issues = [row_index], 1, main_issues
continue
if current is None or next_offset >= len(ordered_layouts):
if include_unanchored_rows and main_values:
@@ -418,7 +428,7 @@ def reconstruct_coordinate_profile_rows(
current_issues.append('coordinate_profile_layout_region_mismatch')
flush()
continue
continuation, continuation_issues = values_for(band, ordered_layouts[next_offset])
continuation, continuation_evidence, continuation_issues = values_for(band, ordered_layouts[next_offset])
if not continuation:
# Once a logical row has started, its declared physical rows must be consecutive.
# Continuing after an unexpected region would silently mix two visual records.
@@ -432,6 +442,8 @@ def reconstruct_coordinate_profile_rows(
current_issues.append(f'coordinate_profile_composite_conflict:{code}')
else:
current[code] = value
if code in continuation_evidence:
current_evidence[code] = continuation_evidence[code]
sources.append(row_index)
current_issues.extend(continuation_issues)
next_offset += 1
@@ -1310,15 +1322,7 @@ def _text_in_region(
return ''
widths = [glyph.bbox.x1 - glyph.bbox.x0 for _, glyph in selected]
gap_limit = max(1.5, median(widths) * 0.65)
result: list[str] = []
for index, (_, glyph) in enumerate(selected):
if index:
previous = selected[index - 1][1]
gap = glyph.bbox.x0 - previous.bbox.x1
if gap > gap_limit and not result[-1].isspace() and not glyph.text.isspace():
result.append(' ')
result.append(glyph.text)
return ''.join(result).strip()
return render_positioned_row([glyph for _, glyph in selected], geometry_gap_limit=gap_limit)
def _text_in_horizontal_region(
@@ -1333,15 +1337,7 @@ def _text_in_horizontal_region(
return ''
widths = [glyph.bbox.x1 - glyph.bbox.x0 for _, glyph in selected]
gap_limit = max(1.5, median(widths) * 0.65)
result: list[str] = []
for index, (_, glyph) in enumerate(selected):
if index:
previous = selected[index - 1][1]
gap = glyph.bbox.x0 - previous.bbox.x1
if gap > gap_limit and not result[-1].isspace() and not glyph.text.isspace():
result.append(' ')
result.append(glyph.text)
return ''.join(result).strip()
return render_positioned_row([glyph for _, glyph in selected], geometry_gap_limit=gap_limit)
def _normalized_header_text(value: str) -> str:
@@ -1461,15 +1457,46 @@ def _field_content_score(text: str, field_code: str | None) -> float:
def _cell_from_glyphs(column_index: int, glyphs: list[tuple[int, PositionedCharacter]]) -> ReconstructedCell:
"""合并同一视觉行、同一列的 glyph,保留按页面位置排序的证据索引。"""
"""合并同一视觉行、同一列 glyph,保留原始空白和按页面位置排序的证据索引。"""
ordered = sorted(glyphs, key=lambda item: item[1].bbox.x0)
boxes = [item.bbox for _, item in ordered]
return ReconstructedCell(
column_index=column_index,
text=''.join(item.text for _, item in ordered).strip(),
text=render_positioned_row([item for _, item in ordered]),
bbox=LayoutBBox(
x0=min(item.x0 for item in boxes), y0=min(item.y0 for item in boxes),
x1=max(item.x1 for item in boxes), y1=max(item.y1 for item in boxes),
),
glyph_indices=[index for index, _ in ordered],
)
def _field_glyph_evidence(
glyphs: list[tuple[int, PositionedCharacter]], *, text: str,
) -> dict[str, Any]:
"""
汇总字段实际消费的原生字符,供上层 Observation 生成字段级高亮。
Args:
glyphs: 已按字段横向区域筛选的字符及稳定来源索引。
text: 字段解析器消费的原始引文。
Returns:
value_bbox、glyph_indices 与独立 bbox_text;无字符时返回空字典。
"""
if not glyphs:
return {}
boxes = [glyph.bbox for _, glyph in glyphs]
return {
'value_bbox': {
'x0': min(item.x0 for item in boxes), 'y0': min(item.y0 for item in boxes),
'x1': max(item.x1 for item in boxes), 'y1': max(item.y1 for item in boxes),
},
'glyph_indices': [index for index, _glyph in glyphs],
'bbox_text': text[:1000],
'quote_source': 'glyph_region',
'source': 'pdf_coordinate',
'has_value_coordinate': True,
'coordinate_status': 'candidate',
'highlight_quality': 'candidate',
}
@@ -1,7 +1,7 @@
"""
backend/app/services/shipping_notice/document_layout/lifecycle.py
用途:管理 ShippingNoticeDocument 的版面版本、checksum、大小门禁和当前成功快照。
用途:管理 ShippingOrderDocument 的版面版本、checksum、大小门禁和当前成功快照。
依赖:ShippingDocumentLayoutVersion、Flask 配置、SQLAlchemy Session、workflow_ledger_service
(claim/complete/recovery 尽力同步 WorkflowItem,缺 Item 不阻断版面收口)。
逻辑:相同内容/parser/checksum 幂等复用;失败版本保留审计,只有可用终态更新 Document 当前引用。
@@ -20,7 +20,7 @@ from flask import current_app
from sqlalchemy import and_, func, or_, update
from app.extensions import db
from app.models import ShippingDocumentLayoutVersion, ShippingNoticeDocument, ShippingNoticeIntake
from app.models import ShippingDocumentLayoutVersion, ShippingOrderDocument, ShippingOrderIntake
_LOGGER = logging.getLogger(__name__)
@@ -38,6 +38,34 @@ LAYOUT_FINGERPRINT_FILES = (
)
CURRENT_LAYOUT_STATUSES = frozenset({'ready', 'needs_review'})
TERMINAL_LAYOUT_STATUSES = frozenset({'ready', 'needs_review', 'failed', 'unsupported'})
ON_DEMAND_COORDINATE_COMPACTION_ISSUES = frozenset({
'shipping_document_layout_page_glyphs_compacted',
'shipping_document_layout_table_glyphs_compacted',
'shipping_document_layout_page_metadata_compacted',
'shipping_document_layout_candidate_glyphs_compacted',
'shipping_document_layout_candidate_page_metadata_compacted',
})
def _ready_layout_evidence_complete(*, document: ShippingOrderDocument, payload: dict[str, Any]) -> bool:
"""判断布局快照是否可直接使用,或可由原 PDF 在订单识别时按需恢复。"""
if str(payload.get('provider') or '') == 'xfa':
capability = payload.get('xfa_capability') if isinstance(payload.get('xfa_capability'), dict) else {}
return bool(capability.get('structure_analysis_ready')) and str(payload.get('status') or '') == 'ready'
if Path(str(document.filename or '')).suffix.lower() != '.pdf':
return True
evidence = payload.get('coordinate_evidence') if isinstance(payload.get('coordinate_evidence'), dict) else {}
complete = isinstance(evidence.get('pages'), dict) and isinstance(evidence.get('page_glyphs'), dict)
recoverable = bool(document.asset_id) and isinstance(payload.get('layout_candidate'), dict)
return complete or recoverable
def _layout_version_reusable(*, document: ShippingOrderDocument, version: ShippingDocumentLayoutVersion) -> bool:
"""仅复用可直接读取或能从原附件按需恢复坐标的成功布局版本。"""
if str(version.status or '') not in CURRENT_LAYOUT_STATUSES:
return False
payload = version.payload_json if isinstance(version.payload_json, dict) else {}
return _ready_layout_evidence_complete(document=document, payload=payload)
def _conversation_id_for_document(document_id: int) -> str | None:
@@ -45,15 +73,15 @@ def _conversation_id_for_document(document_id: int) -> str | None:
从 Document → Intake 解析会话 ID,供 WorkflowItem 定位。
Args:
document_id: ShippingNoticeDocument 主键。
document_id: ShippingOrderDocument 主键。
Returns:
conversation_id 或 None。
"""
row = (
db.session.query(ShippingNoticeIntake.conversation_id)
.join(ShippingNoticeDocument, ShippingNoticeDocument.intake_id == ShippingNoticeIntake.id)
.filter(ShippingNoticeDocument.id == int(document_id))
db.session.query(ShippingOrderIntake.conversation_id)
.join(ShippingOrderDocument, ShippingOrderDocument.intake_id == ShippingOrderIntake.id)
.filter(ShippingOrderDocument.id == int(document_id))
.first()
)
if row is None:
@@ -70,65 +98,15 @@ def _sync_workflow_item_for_layout(
reason: str | None = None,
) -> None:
"""
尽力同步版面阶段的 WorkflowItem 状态/事件;Item 缺失时仅记日志。
历史:同步版面阶段 WorkflowItem;co8 后台账已 DROP,本函数为 no-op。
Args:
document_id: 版面所属 Document。
lifecycle_status: 可选目标生命周期(queued/layout_parsing/failed 等)。
event_code: 可选用户可见事件码(如 layout_completed)。
reason: 迁移理由。
document_id: 版面所属 Document(忽略)。
lifecycle_status: 忽略。
event_code: 忽略。
reason: 忽略。
"""
try:
from app.models.shipping_notice_workflow import ShippingNoticeWorkflow
from app.services.shipping_notice.workflow_ledger_service import (
append_workflow_event,
find_item_by_root,
transition_item_status,
)
conversation_id = _conversation_id_for_document(int(document_id))
if not conversation_id:
return
item = find_item_by_root(
conversation_id=conversation_id,
root_document_id=int(document_id),
for_update=True,
)
if item is None:
return
if lifecycle_status and str(item.lifecycle_status or '') != str(lifecycle_status):
if str(item.lifecycle_status or '') not in {
'closed', 'cancelled', 'manual_upload_pending', 'pending_review',
}:
transition_item_status(
item=item,
lifecycle_status=str(lifecycle_status),
stage=str(lifecycle_status),
actor_type='system',
actor_id='layout',
reason=reason or f'layout:{lifecycle_status}',
)
if event_code:
workflow = db.session.get(ShippingNoticeWorkflow, int(item.workflow_id))
if workflow is not None:
append_workflow_event(
workflow=workflow,
item=item,
event_code=str(event_code),
stage_code=str(item.current_stage or item.lifecycle_status),
message_code=f'shipping.workflow_item.{event_code}',
actor_type='system',
actor_id='layout',
payload={'document_id': int(document_id)},
reason=reason,
)
except Exception:
_LOGGER.exception(
'layout workflow sync skipped document_id=%s status=%s event=%s',
document_id,
lifecycle_status,
event_code,
)
del document_id, lifecycle_status, event_code, reason
def layout_parser_implementation_fingerprint() -> str:
@@ -176,8 +154,8 @@ def _fit_layout_payload_to_budget(
) -> tuple[dict[str, Any] | None, list[str], int]:
"""按证据优先级压缩布局快照,避免可重建证据阻断业务表保存。
核心逻辑:表格 HTML/结构是模板建模的核心;整页 glyph、文本块和页面尺寸
属于可选证据。压缩过程只删除可重建字段,并返回最终大小与诊断码。
核心逻辑:表格 HTML/结构是模板建模的核心;整页/表内 glyph、文本块和页面尺寸
属于可从原 PDF 按需恢复的证据。压缩过程只删除可重建字段,并返回最终大小与诊断码。
"""
candidate = json.loads(json.dumps(payload, ensure_ascii=True))
issues: list[str] = []
@@ -185,16 +163,6 @@ def _fit_layout_payload_to_budget(
if size <= max_bytes:
return candidate, issues, size
evidence = candidate.get('coordinate_evidence')
if isinstance(evidence, dict):
if evidence.pop('page_glyphs', None) is not None:
issues.append('shipping_document_layout_page_glyphs_compacted')
if evidence.pop('pages', None) is not None:
issues.append('shipping_document_layout_page_metadata_compacted')
_, size = canonical_layout_payload(candidate)
if size <= max_bytes:
return candidate, issues, size
if candidate.pop('text_blocks', None) is not None:
issues.append('shipping_document_layout_text_blocks_compacted')
_, size = canonical_layout_payload(candidate)
@@ -208,12 +176,22 @@ def _fit_layout_payload_to_budget(
if layout_candidate.pop('pages', None) is not None:
issues.append('shipping_document_layout_candidate_page_metadata_compacted')
_, size = canonical_layout_payload(candidate)
if size <= max_bytes:
return candidate, issues, size
coordinate_evidence = candidate.get('coordinate_evidence')
if isinstance(coordinate_evidence, dict):
if coordinate_evidence.pop('page_glyphs', None) is not None:
issues.append('shipping_document_layout_page_glyphs_compacted')
if coordinate_evidence.pop('tables', None) is not None:
issues.append('shipping_document_layout_table_glyphs_compacted')
_, size = canonical_layout_payload(candidate)
if size <= max_bytes:
return candidate, issues, size
return None, issues + ['shipping_document_layout_snapshot_size_exceeded'], size
def current_layout_snapshot(document: ShippingNoticeDocument) -> dict[str, Any] | None:
def current_layout_snapshot(document: ShippingOrderDocument) -> dict[str, Any] | None:
"""读取 Document 当前可用冻结 payload;失败历史版本永不作为运行输入。"""
version = document.current_layout_version
if (
@@ -226,7 +204,7 @@ def current_layout_snapshot(document: ShippingNoticeDocument) -> dict[str, Any]
def record_inline_layout_snapshot(
document: ShippingNoticeDocument,
document: ShippingOrderDocument,
snapshot: dict[str, Any],
*,
parser_key: str | None = None,
@@ -276,6 +254,8 @@ def record_inline_layout_snapshot(
'ready', 'needs_review', 'failed', 'unsupported',
} else 'failed'
issues = sorted({str(item) for item in (payload.get('issues') or []) if str(item)} | set(compact_issues))
if status == 'ready' and ON_DEMAND_COORDINATE_COMPACTION_ISSUES.intersection(compact_issues):
issues = sorted(set(issues) | {'shipping_document_layout_coordinate_evidence_on_demand'})
stored_payload: dict[str, Any] | None = fitted_payload
if stored_payload is None:
status = 'failed'
@@ -309,7 +289,7 @@ def record_inline_layout_snapshot(
def _clone_reusable_layout_for_document(
document: ShippingNoticeDocument,
document: ShippingOrderDocument,
reusable: ShippingDocumentLayoutVersion,
) -> ShippingDocumentLayoutVersion | None:
"""
@@ -335,7 +315,7 @@ def _clone_reusable_layout_for_document(
def schedule_layout_version(
document: ShippingNoticeDocument,
document: ShippingOrderDocument,
*,
force: bool = False,
created_by_id: int | None = None,
@@ -355,22 +335,27 @@ def schedule_layout_version(
if len(source_hash) != 64:
return None
# Identical files from the same owner reuse a completed layout rather than waiting for MinerU again.
owner_id = db.session.query(ShippingNoticeIntake.user_id).filter(
ShippingNoticeIntake.id == document.intake_id,
owner_id = db.session.query(ShippingOrderIntake.user_id).filter(
ShippingOrderIntake.id == document.intake_id,
).scalar()
if not force:
reusable_from_owner = (
ShippingDocumentLayoutVersion.query
.join(ShippingNoticeDocument, ShippingNoticeDocument.id == ShippingDocumentLayoutVersion.document_id)
.join(ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingNoticeDocument.intake_id)
.join(ShippingOrderDocument, ShippingOrderDocument.id == ShippingDocumentLayoutVersion.document_id)
.join(ShippingOrderIntake, ShippingOrderIntake.id == ShippingOrderDocument.intake_id)
.filter(
ShippingNoticeIntake.user_id == owner_id,
ShippingNoticeDocument.content_hash == source_hash,
ShippingOrderIntake.user_id == owner_id,
ShippingOrderDocument.content_hash == source_hash,
ShippingDocumentLayoutVersion.parser_key == current_layout_parser_key(),
ShippingDocumentLayoutVersion.status.in_(tuple(CURRENT_LAYOUT_STATUSES)),
)
.order_by(ShippingDocumentLayoutVersion.finished_at.desc(), ShippingDocumentLayoutVersion.id.desc())
.first()
.all()
)
reusable_from_owner = next(
(version for version in reusable_from_owner
if _layout_version_reusable(document=document, version=version)),
None,
)
if reusable_from_owner is not None:
localized = _clone_reusable_layout_for_document(document, reusable_from_owner)
@@ -383,12 +368,17 @@ def schedule_layout_version(
if active is not None:
return active
if not force:
reusable = ShippingDocumentLayoutVersion.query.filter_by(
reusable_candidates = ShippingDocumentLayoutVersion.query.filter_by(
document_id=int(document.id), source_content_hash=source_hash,
parser_key=current_layout_parser_key(),
).filter(ShippingDocumentLayoutVersion.status.in_(tuple(CURRENT_LAYOUT_STATUSES))).order_by(
ShippingDocumentLayoutVersion.version.desc(),
).first()
).all()
reusable = next(
(version for version in reusable_candidates
if _layout_version_reusable(document=document, version=version)),
None,
)
if reusable is not None:
document.current_layout_version_id = reusable.id
return reusable
@@ -416,7 +406,7 @@ def schedule_layout_version(
def schedule_document_layouts(
documents: list[ShippingNoticeDocument], *, created_by_id: int | None = None,
documents: list[ShippingOrderDocument], *, created_by_id: int | None = None,
) -> list[ShippingDocumentLayoutVersion]:
"""在 Document 持久化事务内为支持附件建立独立布局版本,超量文档保留 skipped 审计。"""
from pathlib import Path
@@ -424,7 +414,7 @@ def schedule_document_layouts(
from app.services.shipping_notice.document_layout.mineru import MINERU_SUPPORTED_EXTENSIONS
max_documents = max(int(current_app.config.get(
'SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', 4,
'SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', 10,
)), 0)
eligible = [
item for item in documents
@@ -495,7 +485,7 @@ def serialize_layout_version(version: ShippingDocumentLayoutVersion) -> dict[str
def list_layout_versions(document_id: int) -> list[dict[str, Any]]:
"""列出一个 Document 的布局版本安全摘要。"""
document = db.session.get(ShippingNoticeDocument, int(document_id))
document = db.session.get(ShippingOrderDocument, int(document_id))
if document is None:
from app.core.errors import NotFoundError
@@ -511,7 +501,7 @@ def request_layout_reparse(
document_id: int, *, created_by_id: int | None,
) -> dict[str, Any]:
"""管理员显式创建下一布局版本;活动版本存在时幂等返回同一版本。"""
document = db.session.get(ShippingNoticeDocument, int(document_id))
document = db.session.get(ShippingOrderDocument, int(document_id))
if document is None:
from app.core.errors import NotFoundError
@@ -591,6 +581,14 @@ def complete_layout_version(
issues = sorted({str(item) for item in (snapshot.get('issues') or []) if str(item)} | set(compact_issues))
provider_status = str(snapshot.get('status') or 'failed')
status = provider_status if provider_status in TERMINAL_LAYOUT_STATUSES else 'failed'
if status == 'ready' and not _ready_layout_evidence_complete(
document=version.document, payload=snapshot,
):
status = 'failed'
issues = sorted(set(issues) | {'shipping_document_layout_coordinate_evidence_incomplete'})
elif status == 'ready' and ON_DEMAND_COORDINATE_COMPACTION_ISSUES.intersection(compact_issues):
# [STEP] 快照压缩只影响持久化体积;原 PDF 仍可读时由订单识别按需恢复坐标。
issues = sorted(set(issues) | {'shipping_document_layout_coordinate_evidence_on_demand'})
stored_payload: dict[str, Any] | None = fitted_snapshot
if stored_payload is None:
status = 'failed'
@@ -73,7 +73,10 @@ def extract_native_pdf_pages(
content: bytes, *, render_scale: float = 2.0, render_images: bool = True,
) -> list[NativePdfPage]:
"""
从 PDF bytes 提取左上原点字符坐标和页面图。
从 PDF bytes 提取左上原点字符坐标、原始文本流边界和页面图。
核心逻辑:可见字符保留 PDFium 原始 char_index;零 bbox 空白不生成伪坐标,
而是记录到下一个有效字符的 boundary_before,供文本重建优先于几何猜测使用。
Args:
content: 原始 PDF 字节,不写文件和日志。
@@ -93,12 +96,21 @@ def extract_native_pdf_pages(
width, height = page.get_size()
text_page = page.get_textpage()
characters: list[PositionedCharacter] = []
pending_boundary: str = 'none'
for char_index in range(text_page.count_chars()):
text = text_page.get_text_range(char_index, 1)
if not text or not normalize_layout_text(text):
if not text:
continue
if not normalize_layout_text(text):
if any(character in {'\r', '\n'} for character in text):
pending_boundary = 'line_break'
elif pending_boundary == 'none' and any(character.isspace() for character in text):
pending_boundary = 'space'
continue
left, bottom, right, top = text_page.get_charbox(char_index, loose=True)
if right <= left or top <= bottom:
# 非空白可见字符若无有效坐标,不得把之前的空白错误转嫁到后续字符。
pending_boundary = 'none'
continue
try:
# 不修改 PDFium 原始坐标;仅转为左上原点页面坐标。
@@ -107,9 +119,12 @@ def extract_native_pdf_pages(
bbox=LayoutBBox(
x0=left, y0=height - top, x1=right, y1=height - bottom,
),
source_index=len(characters),
source_index=char_index,
boundary_before=pending_boundary,
))
pending_boundary = 'none'
except ValueError:
pending_boundary = 'none'
continue
characters = _assign_page_line_ids(characters, page_no=page_index + 1)
rotation = int(getattr(page, 'get_rotation', lambda: 0)() or 0) % 360
@@ -316,7 +331,7 @@ def build_native_pdf_layout_candidate(
组合 MinerU HTML 与 PDFium 独立证据,生成始终 needs_review 的 layout.v1 候选。
Args:
document_id: 当前 ShippingNoticeDocument 主键。
document_id: 当前 ShippingOrderDocument 主键。
content_hash: 当前附件 SHA-256,用于稳定 ID 和契约校验。
content: 原始 PDF 字节。
mineru: 同一文件的 MinerU pipeline 候选。
@@ -0,0 +1,115 @@
"""按需从原始 PDF 恢复坐标证据;不改变上传阶段的轻量布局快照。"""
from __future__ import annotations
from typing import Any
from app import db
from app.models import FileAsset, ShippingOrderDocument
def _coordinate_mapping(value: Any) -> dict[str, Any]:
"""仅接受坐标证据的键值映射;业务表格列表不得被 `dict(...)` 误解释。"""
return dict(value) if isinstance(value, dict) else {}
def ensure_on_demand_coordinate_evidence(
*, document: ShippingOrderDocument, layout: dict[str, Any], page_nos: set[int] | None,
table_by_page: dict[int, dict[str, Any] | list[dict[str, Any]]] | None = None,
) -> dict[str, Any]:
"""为盲测和正式抽取恢复所需页坐标;同页多表必须分别保留字符证据。"""
if not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'):
return layout
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
# 兼容历史布局快照:布局任务曾将坐标证据写在顶层,正式抽取仍需复用它。
if not evidence:
legacy_keys = ('pages', 'page_glyphs', 'sources', 'tables')
evidence = {
key: layout.get(key)
for key in legacy_keys
if isinstance(layout.get(key), dict)
}
# Run 快照可能早于最近一次布局重试;读取当前成功/失败版本仅作本次内存补充。
current_version = getattr(document, 'current_layout_version', None)
current_payload = getattr(current_version, 'payload_json', None)
if isinstance(current_payload, dict):
current_evidence = current_payload.get('coordinate_evidence')
if isinstance(current_evidence, dict):
evidence = {**current_evidence, **evidence}
for key in ('pages', 'page_glyphs', 'sources', 'tables'):
if key not in evidence and isinstance(current_payload.get(key), dict):
evidence[key] = current_payload[key]
pages = _coordinate_mapping(evidence.get('pages'))
page_glyphs = _coordinate_mapping(evidence.get('page_glyphs'))
sources = _coordinate_mapping(evidence.get('sources'))
source_pages = _coordinate_mapping(sources.get('pages'))
tables = _coordinate_mapping(evidence.get('tables'))
if page_nos is not None and page_nos.issubset({int(p) for p in page_glyphs if str(p).isdigit()}):
return layout
tables_by_page: dict[int, list[dict[str, Any]]] = {}
for raw_table in layout.get('tables') or []:
if not isinstance(raw_table, dict):
continue
tables_by_page.setdefault(int(raw_table.get('page_no') or 1), []).append(raw_table)
for raw_page_no, raw_tables in (table_by_page or {}).items():
candidates = raw_tables if isinstance(raw_tables, list) else [raw_tables]
page_tables = tables_by_page.setdefault(int(raw_page_no), [])
existing_ids = {str(item.get('table_id') or '') for item in page_tables}
for raw_table in candidates:
if not isinstance(raw_table, dict):
continue
table_id = str(raw_table.get('table_id') or '')
if table_id and table_id not in existing_ids:
page_tables.append(raw_table)
existing_ids.add(table_id)
from app.services.file_assets.service import read_asset_bytes
from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages
from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines
from app.services.shipping_notice.order_document_profile_service import (
_native_characters_in_table, _ocr_lines_to_characters, _ocr_lines_to_page_characters,
)
asset = db.session.get(FileAsset, int(document.asset_id))
if asset is None:
return layout
try:
native_pages = extract_native_pdf_pages(read_asset_bytes(asset))
except Exception:
return layout
for page in native_pages:
if page_nos is not None and int(page.page_no) not in page_nos:
continue
glyphs = [item.model_dump(mode='json') for item in getattr(page, 'characters', []) or []]
source = 'pdf_coordinate'
if not glyphs:
try:
lines = extract_ocr_lines(page.image, page_width=page.width, page_height=page.height)
glyphs = _ocr_lines_to_page_characters(lines=lines)
source = 'ocr_coordinate'
except Exception:
glyphs = []
if not glyphs:
continue
page_key = str(page.page_no)
pages[page_key] = {'width': page.width, 'height': page.height}
page_glyphs[page_key] = glyphs
source_pages[page_key] = source
for table in tables_by_page.get(int(page.page_no), []):
table_id = str(table.get('table_id') or '')
chars = _native_characters_in_table(
characters=list(getattr(page, 'characters', []) or []),
table_bbox=table.get('bbox') or {},
)
if not chars:
try:
lines = extract_ocr_lines(page.image, page_width=page.width, page_height=page.height)
chars = _ocr_lines_to_characters(lines=lines, table_bbox=table.get('bbox') or {})
except Exception:
chars = []
if table_id and chars:
tables[table_id] = chars
next_layout = dict(layout)
next_layout['coordinate_evidence'] = {
**evidence, 'pages': pages, 'page_glyphs': page_glyphs,
'tables': tables, 'sources': {**sources, 'pages': source_pages},
}
return next_layout
@@ -2,7 +2,7 @@
backend/app/services/shipping_notice/document_layout/order_field_extraction.py
用途:从冻结的整页 PDF/OCR 字符坐标中确定性提取独立订单级字段。
依赖:OrderCoordinateProfileV2、冻结 Schema 字段规则和 LayoutBBox。
依赖:OrderCoordinateProfile、冻结 Schema 字段规则和 LayoutBBox。
逻辑:订单工作流先唯一匹配模板,再调用本模块;本模块仅返回可追溯候选,绝不回读资产、数据库或调用模型。
"""
@@ -14,10 +14,11 @@ from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.coordinate_region_text import render_positioned_row
from app.services.shipping_notice.document_layout.order_profile import (
AnchorRelativeRegion,
AnchorRule,
OrderCoordinateProfileV2,
OrderCoordinateProfile,
OrderFieldLayout,
RelativeRegion,
)
@@ -46,14 +47,14 @@ class OrderFieldExtraction(BaseModel):
def extract_order_fields(
*, profile: OrderCoordinateProfileV2, schema_fields: dict[str, dict[str, Any]],
*, profile: OrderCoordinateProfile, schema_fields: dict[str, dict[str, Any]],
coordinate_evidence: dict[str, Any],
) -> list[OrderFieldExtraction]:
"""
用唯一文字锚点和相对值区读取订单字段,缺少页级证据时严格失败关闭。
Args:
profile: Run 冻结的 v2 坐标模板,不得包含待重新绑定字段。
profile: Run 冻结的坐标模板,不得包含待重新绑定字段。
schema_fields: 以 stable field_id 为键的冻结启用 Schema 字段。
coordinate_evidence: 冻结页尺寸、page_glyphs 与来源;不接受表格内 glyph 兜底。
@@ -405,18 +406,14 @@ def _render_value(selected: list[tuple[int, dict[str, Any]]], *, multi_line: boo
def _render_visual_row(row: list[tuple[int, dict[str, Any]]]) -> str:
"""以字距推断缺失的 PDF 空白;仅大于常规字符间隔时补一个普通空格。"""
rendered: list[str] = []
previous: LayoutBBox | None = None
for _index, glyph in row:
bbox = _glyph_bbox(glyph)
if previous is not None:
typical_width = max((previous.x1 - previous.x0 + bbox.x1 - bbox.x0) / 2, 0.01)
if bbox.x0 - previous.x1 > typical_width * 0.75:
rendered.append(' ')
rendered.append(str(glyph.get('text') or ''))
previous = bbox
return ''.join(rendered).strip()
"""优先恢复原始 PDF 空白;旧证据继续沿用既有平均字宽阈值,避免模板行为漂移。"""
glyphs = [glyph for _index, glyph in row]
return render_positioned_row(
glyphs,
geometry_gap_ratio=0.75,
geometry_width_mode='average',
minimum_gap_limit=0.01,
)
def _visual_rows(items: list[tuple[int, dict[str, Any]]]) -> list[list[tuple[int, dict[str, Any]]]]:
@@ -1,38 +1,26 @@
"""
backend/app/services/shipping_notice/document_layout/order_profile.py
用途:定义订单文档坐标模板 v2 的纯契约和受控字段绑定。
用途:定义唯一的订单文档坐标模板契约与 v2 版面签名匹配评分维度。
依赖:Pydantic、坐标 bbox 契约、订单字段规则和已注册解析器。
逻辑:管理员保存稳定锚点、相对区域和 field_code 绑定;运行时匹配器与坐标解析器只消费该不可变定义。
逻辑:管理员保存稳定锚点、相对区域和 field_code 绑定;order_profile_matcher 消费
DocumentMatchProfile 分项权重与 negative_anchors;order_profile_signature 生成
matching_signature 供运行时硬门禁与维度比对。
"""
from __future__ import annotations
import hashlib
import html
import json
import re
from decimal import Decimal
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, model_validator
from app.core.errors import ValidationError
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.html_table import HtmlGrid, parse_html_grid
from app.services.shipping_notice.notice_line_values import parse_number
from app.services.shipping_notice.notice_lines import resolve_composite_part_numbers
from app.services.shipping_notice.order_schema.field_rules import (
normalize_order_field_value,
validate_order_field_value,
)
from app.services.shipping_notice.order_schema.table_contract import (
TableHeaderContract,
normalize_table_header,
)
from app.services.shipping_notice.document_layout.html_table import HtmlGrid
ORDER_PROFILE_VERSION = 'order_coordinate_profile.v2'
PROFILE_EXTRACTORS = frozenset({'direct', 'temp_internal_parts', 'quantity_uom', 'amount_currency', 'price_currency'})
HEADER_LINE_ITEM_VALUE_PATTERN = re.compile(
r'\b(?:item|line)\s*(?:no\.?|number|#)?\s*[:#-]?\s*0{2,}\d+\b',
@@ -319,27 +307,64 @@ class TableRegionProfile(OrderProfileModel):
SCORING_DIMENSION_KEYS = (
'table_topology',
'row_structure',
'anchor_geometry',
'header_regions',
'header_semantic_position',
'column_topology',
'table_geometry',
'page_structure',
'header_path',
'customer_hint',
'field_spatial_relation',
'optional_static_text',
'trusted_business_context',
)
CRITICAL_STRUCTURE_DIMENSION_KEYS = ('table_topology', 'row_structure', 'anchor_geometry')
CRITICAL_STRUCTURE_DIMENSION_KEYS = (
'header_semantic_position',
'column_topology',
'table_geometry',
)
# 历史 v1 权重键 → v2 键;供 model_validator 迁移旧模板配置。
_LEGACY_SCORING_WEIGHT_KEYS: dict[str, str] = {
'table_topology': 'column_topology',
'row_structure': 'table_geometry',
'anchor_geometry': 'header_semantic_position',
'header_regions': 'field_spatial_relation',
'page_structure': 'page_structure',
'header_path': 'optional_static_text',
'customer_hint': 'trusted_business_context',
}
MatchDimensionState = Literal['matched', 'mismatched', 'unavailable']
class MatchDimensionResult(OrderProfileModel):
"""单维匹配结果:三态 + 0~1 得分;unavailable 不计入相似度分母。"""
state: MatchDimensionState
score: float = Field(ge=0, le=1)
class ProfileScoringWeights(OrderProfileModel):
"""分项权重;七维之和必须为 1.0,供 matcher 加权汇总确定性评分。"""
"""v2 分项权重;七维之和必须为 1.0,供 matcher 加权汇总确定性评分。"""
table_topology: float = Field(default=0.25, ge=0, le=1)
row_structure: float = Field(default=0.20, ge=0, le=1)
anchor_geometry: float = Field(default=0.20, ge=0, le=1)
header_regions: float = Field(default=0.10, ge=0, le=1)
header_semantic_position: float = Field(default=0.30, ge=0, le=1)
column_topology: float = Field(default=0.25, ge=0, le=1)
table_geometry: float = Field(default=0.15, ge=0, le=1)
page_structure: float = Field(default=0.10, ge=0, le=1)
header_path: float = Field(default=0.10, ge=0, le=1)
customer_hint: float = Field(default=0.05, ge=0, le=1)
field_spatial_relation: float = Field(default=0.10, ge=0, le=1)
optional_static_text: float = Field(default=0.05, ge=0, le=1)
trusted_business_context: float = Field(default=0.05, ge=0, le=1)
@model_validator(mode='before')
@classmethod
def migrate_legacy_weight_keys(cls, value: Any) -> Any:
"""将 v1 七维权重键映射为 v2,避免历史模板在升级前无法解析。"""
if not isinstance(value, dict):
return value
if any(key in value for key in SCORING_DIMENSION_KEYS):
return value
migrated = dict(value)
for legacy_key, new_key in _LEGACY_SCORING_WEIGHT_KEYS.items():
if legacy_key in migrated and new_key not in migrated:
migrated[new_key] = migrated.pop(legacy_key)
return migrated
@model_validator(mode='after')
def validate_weight_sum(self) -> 'ProfileScoringWeights':
@@ -351,10 +376,11 @@ class ProfileScoringWeights(OrderProfileModel):
class ProfileScoringThresholds(OrderProfileModel):
"""自动决胜与关键结构单项阈值;与 minimum_score/minimum_margin 并存,服务多候选评分决胜。"""
"""自动决胜阈值;evidence_coverage_minimum 与 matcher 硬门禁对齐。"""
auto_select_minimum_score: float = Field(default=0.95, ge=0, le=1)
auto_select_minimum_margin: float = Field(default=0.15, ge=0, le=1)
auto_select_minimum_score: float = Field(default=0.90, ge=0, le=1)
auto_select_minimum_margin: float = Field(default=0.12, ge=0, le=1)
evidence_coverage_minimum: float = Field(default=0.70, ge=0, le=1)
critical_structure_minimum: float = Field(default=0.90, ge=0, le=1)
@@ -378,24 +404,26 @@ class DocumentMatchProfile(OrderProfileModel):
page_pattern: Literal['one_or_more'] = 'one_or_more'
required_anchors: list[DocumentMatchAnchor] = Field(default_factory=list)
optional_anchors: list[DocumentMatchAnchor] = Field(default_factory=list)
negative_anchors: list[DocumentMatchAnchor] = Field(default_factory=list)
minimum_score: float = Field(default=0.9, ge=0, le=1)
minimum_margin: float = Field(default=0.15, ge=0, le=1)
minimum_margin: float = Field(default=0.12, ge=0, le=1)
scoring_weights: ProfileScoringWeights = Field(default_factory=ProfileScoringWeights)
scoring_thresholds: ProfileScoringThresholds = Field(default_factory=ProfileScoringThresholds)
@model_validator(mode='after')
def validate_anchor_ids(self) -> 'DocumentMatchProfile':
"""要求必选和可选锚点名称唯一,避免评分器使用含糊证据。"""
ids = [item.anchor_id for item in self.required_anchors + self.optional_anchors]
"""要求必选、可选与排除锚点名称唯一,避免评分器使用含糊证据。"""
ids = [
item.anchor_id
for item in self.required_anchors + self.optional_anchors + self.negative_anchors
]
if len(ids) != len(set(ids)):
raise ValueError('document match anchor ids must be unique')
return self
class OrderCoordinateProfileV2(OrderProfileModel):
"""保存阶段 0 评审中的订单坐标模板 v2 定义,尚未接入旧运行路径。"""
contract_version: Literal[ORDER_PROFILE_VERSION] = ORDER_PROFILE_VERSION
class OrderCoordinateProfile(OrderProfileModel):
"""唯一的订单坐标模板定义;运行时和管理端只消费这一种契约。"""
profile_code: str = Field(pattern=r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
version: int = Field(ge=1)
document_match: DocumentMatchProfile
@@ -404,7 +432,7 @@ class OrderCoordinateProfileV2(OrderProfileModel):
draft_unbound_order_field_layouts: list[DraftUnboundOrderFieldLayout] = Field(default_factory=list)
@model_validator(mode='after')
def validate_profile_rules(self) -> 'OrderCoordinateProfileV2':
def validate_profile_rules(self) -> 'OrderCoordinateProfile':
"""阻断重复表区和重叠表区,确保一个字段位置只有唯一模板解释。"""
ids = [item.region_id for item in self.table_regions]
if len(ids) != len(set(ids)):
@@ -414,7 +442,14 @@ class OrderCoordinateProfileV2(OrderProfileModel):
# Different exact pages may use identical coordinates without competing at runtime.
if _table_regions_can_apply_same_page(left, right):
_validate_non_overlapping_regions([left.region, right.region])
anchor_ids = {item.anchor_id for item in self.document_match.required_anchors + self.document_match.optional_anchors}
anchor_ids = {
item.anchor_id
for item in (
self.document_match.required_anchors
+ self.document_match.optional_anchors
+ self.document_match.negative_anchors
)
}
for table in self.table_regions:
if not set(table.continuation_rule.required_anchor_ids).issubset(anchor_ids):
raise ValueError('cross-page continuation anchor must be a document match anchor')
@@ -451,108 +486,6 @@ def _table_regions_can_apply_same_page(left: TableRegionProfile, right: TableReg
return left.page_scope == right.page_scope
# Transitional adapters keep the currently deployed extraction workflow importable while its
# callers are migrated to the v2 coordinate runtime in later gated stages. They are not part
# of the persisted v2 contract and must not be used by new Profile writes.
class OrderProfileColumnRule(OrderProfileModel):
"""Legacy runtime column rule retained only until the frozen-run migration is complete."""
column_index: int = Field(ge=0)
extractor_key: Literal['direct', 'temp_internal_parts']
target_field_codes: list[str] = Field(min_length=1)
@model_validator(mode='after')
def validate_extractor_targets(self) -> 'OrderProfileColumnRule':
"""Preserve the established finite extractor whitelist for historical frozen snapshots."""
targets = set(self.target_field_codes)
if len(targets) != len(self.target_field_codes):
raise ValueError('order profile target fields must be unique')
if self.extractor_key == 'direct' and len(targets) != 1:
raise ValueError('direct order profile extractor requires one target field')
if self.extractor_key == 'temp_internal_parts' and targets != {'customer_part_number', 'part_number'}:
raise ValueError('TEMP/internal extractor targets are fixed')
return self
class CoordinateReconstructionProfile(OrderProfileModel):
"""Legacy frozen-run coordinate reconstruction adapter; v2 uses FieldRegion instead."""
method: Literal['native_pdf_coordinates.v1', 'ocr_pdf_coordinates.v1'] = 'native_pdf_coordinates.v1'
column_boundaries: list[float] = Field(default_factory=list)
column_field_codes: list[str | None] = Field(default_factory=list)
line_start_column_index: int = Field(default=0, ge=0)
subrow_layouts: list[dict[str, Any]] = Field(default_factory=list)
@model_validator(mode='after')
def validate_boundaries(self) -> 'CoordinateReconstructionProfile':
"""Validate historical settings so existing frozen Run snapshots remain safe to load."""
if self.subrow_layouts:
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import CoordinateSubrowLayout
layouts = [CoordinateSubrowLayout.model_validate(item) for item in self.subrow_layouts]
offsets = [item.row_offset for item in layouts]
if len(offsets) != len(set(offsets)) or sorted(offsets) != list(range(len(offsets))) or sum(item.role == 'main' for item in layouts) != 1:
raise ValueError('coordinate subrow layouts require contiguous offsets and one main row')
return self
if len(self.column_boundaries) < 3 or self.column_boundaries[0] != 0 or self.column_boundaries[-1] != 1:
raise ValueError('coordinate reconstruction boundaries must cover the table')
if any(left >= right for left, right in zip(self.column_boundaries, self.column_boundaries[1:])):
raise ValueError('coordinate reconstruction boundaries must be strictly increasing')
if self.column_field_codes and len(self.column_field_codes) != len(self.column_boundaries) - 1:
raise ValueError('coordinate reconstruction field codes must match column count')
return self
class OrderDocumentProfile(OrderProfileModel):
"""保存当前已发布运行路径的模板结构、列覆盖、数据起始行和质量策略。"""
contract_version: Literal['shipping_order_document_profile.v1'] = 'shipping_order_document_profile.v1'
profile_code: str = Field(pattern=r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
version: int = Field(ge=1)
structure_fingerprint: str = Field(pattern=r'^[0-9a-f]{64}$')
header_row_index: int = Field(ge=0)
data_start_row_index: int = Field(ge=1)
row_structure: Literal['preserved', 'unsupported_row_structure'] = 'preserved'
column_rules: list[OrderProfileColumnRule] = Field(default_factory=list)
coordinate_reconstruction: CoordinateReconstructionProfile | None = None
drop_zero_qty: bool = True
@model_validator(mode='after')
def validate_profile_rules(self) -> 'OrderDocumentProfile':
"""禁止列规则重复;不支持的行结构只能作为识别/路由 Profile,不能配置字段解析。"""
columns = [item.column_index for item in self.column_rules]
if len(columns) != len(set(columns)):
raise ValueError('order profile source columns must be unique')
targets = [code for item in self.column_rules for code in item.target_field_codes]
if len(targets) != len(set(targets)):
raise ValueError('order profile target fields must be unique across columns')
if self.data_start_row_index <= self.header_row_index:
raise ValueError('order profile data rows must start after the header')
if self.row_structure == 'unsupported_row_structure' and self.column_rules:
raise ValueError('unsupported row structure profile cannot expose column mappings')
if self.row_structure == 'preserved' and not self.column_rules:
raise ValueError('preserved row structure profile requires column mappings')
return self
class OrderProfileRowResult(OrderProfileModel):
"""保存一条模板行的字段值或删除/复核状态,不包含来源原文。"""
row_index: int = Field(ge=0)
status: Literal['parsed', 'deleted', 'needs_review']
fields: dict[str, Any] = Field(default_factory=dict)
issues: list[str] = Field(default_factory=list)
class OrderProfileParseResult(OrderProfileModel):
"""汇总 Profile 是否精确命中以及模板行解析结果。"""
matched: bool
profile_code: str | None = None
profile_version: int | None = Field(default=None, ge=1)
rows: list[OrderProfileRowResult] = Field(default_factory=list)
issues: list[str] = Field(default_factory=list)
def diagnose_order_profile_header(grid: HtmlGrid, *, header_row_index: int) -> list[str]:
"""
诊断管理员所选表头是否已经混入明显的订单明细值。
@@ -606,266 +539,3 @@ def order_profile_structure_fingerprint(
}
encoded = json.dumps(payload, sort_keys=True, ensure_ascii=True, separators=(',', ':')).encode()
return hashlib.sha256(encoded).hexdigest()
def reconstruct_order_profile_html(
*, characters: list[dict[str, Any]], table_bbox: dict[str, Any],
reconstruction: CoordinateReconstructionProfile,
) -> str:
"""
利用冻结坐标证据生成带稳定虚拟表头的逻辑明细 HTML。
核心逻辑:先按 x/y 重建物理行,再将 continuation 按列并入最近 data 行;deleted
回写最近明细状态,summary 终止数据区。虚拟表头只表达列序,不依赖数据页表头是否完整。
Args:
characters: 当前表格 bbox 内的原生或 OCR 字符坐标。
table_bbox: 当前表格页面坐标。
reconstruction: 管理员确认的相对列边界。
Returns:
可由既有 Profile 解析器消费的 HTML;行角色保存在 ``data-row-role`` 属性中。
"""
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
CoordinateColumnAnchor,
reconstruct_multi_subrow_table,
reconstruct_table_from_positioned_text,
)
bbox = LayoutBBox.model_validate(table_bbox)
if reconstruction.subrow_layouts:
logical_rows = reconstruct_multi_subrow_table(
characters=characters,
table_bbox=bbox,
subrow_layouts=reconstruction.subrow_layouts,
)
field_codes = []
for layout in reconstruction.subrow_layouts:
for code in layout.get('column_field_codes') or []:
if code and code not in field_codes:
field_codes.append(code)
header = '<tr data-row-role="header">' + ''.join(
f'<th>{html.escape(code)}</th>' for code in field_codes
) + '</tr>'
body = ''.join(
'<tr data-row-role="{}" data-source-rows="{}">{}</tr>'.format(
row.role, ','.join(str(index) for index in row.source_row_indices),
''.join(f'<td>{html.escape(row.fields.get(code, ""))}</td>' for code in field_codes),
)
for row in logical_rows
)
return f'<table>{header}{body}</table>'
boundaries = reconstruction.column_boundaries
width = bbox.x1 - bbox.x0
anchors = [CoordinateColumnAnchor(
column_index=index,
field_code=(reconstruction.column_field_codes[index] if reconstruction.column_field_codes else None),
bbox=LayoutBBox(
x0=bbox.x0 + width * boundaries[index], y0=bbox.y0,
x1=bbox.x0 + width * boundaries[index + 1], y1=bbox.y1,
),
) for index in range(len(boundaries) - 1)]
result = reconstruct_table_from_positioned_text(
characters=characters, table_bbox=bbox, column_anchors=anchors,
line_start_column_index=reconstruction.line_start_column_index,
)
if not result.rows:
raise ValidationError(
'No coordinate reconstruction rows were produced',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE',
)
logical_rows: list[dict[str, Any]] = []
for row in result.rows:
values = {cell.column_index: cell.text for cell in row.cells}
if row.role == 'data':
logical_rows.append({'role': 'data', 'values': values, 'source_rows': [row.row_index]})
elif row.role == 'continuation' and logical_rows:
current = logical_rows[-1]
for column_index, value in values.items():
previous = str(current['values'].get(column_index) or '').strip()
current['values'][column_index] = f'{previous} {value}'.strip()
current['source_rows'].append(row.row_index)
elif row.role == 'deleted' and logical_rows:
logical_rows[-1]['role'] = 'deleted'
logical_rows[-1]['source_rows'].append(row.row_index)
elif row.role == 'summary':
break
header = '<tr data-row-role="header">' + ''.join(
f'<th>coordinate_column_{index + 1}</th>' for index in range(len(anchors))
) + '</tr>'
body = ''.join(
'<tr data-row-role="{}" data-source-rows="{}">{}</tr>'.format(
row['role'], ','.join(str(index) for index in row['source_rows']),
''.join(
f'<td>{html.escape(str(row["values"].get(index, "")))}</td>'
for index in range(len(anchors))
),
)
for row in logical_rows
)
return f'<table>{header}{body}</table>'
def parse_html_table_with_order_profile(
html: str,
*,
table_id: str,
profile: OrderDocumentProfile,
contract: TableHeaderContract,
) -> OrderProfileParseResult:
"""
在结构指纹精确命中时按模板列规则解析订单行。
Args:
html: MinerU 或 EML 提供的单张 HTML table。
table_id: 当前文档内稳定表格 ID。
profile: Run 锁定的 published 模板 Profile 快照。
contract: Run 锁定订单 Schema 表头/字段契约。
Returns:
未命中时不产生行;不支持行结构时返回阻断问题;命中时逐行解析。
"""
grid = parse_html_grid(html, table_id=table_id)
actual = order_profile_structure_fingerprint(
grid,
header_row_index=profile.header_row_index,
)
if actual != profile.structure_fingerprint:
return OrderProfileParseResult(matched=False, issues=['order_profile_structure_mismatch'])
if profile.row_structure == 'unsupported_row_structure':
return OrderProfileParseResult(
matched=True,
profile_code=profile.profile_code,
profile_version=profile.version,
issues=['order_profile_row_structure_unsupported'],
)
if any(rule.column_index >= grid.column_count for rule in profile.column_rules):
return OrderProfileParseResult(
matched=True,
profile_code=profile.profile_code,
profile_version=profile.version,
issues=['order_profile_column_out_of_range'],
)
row_roles = _profile_html_row_roles(html)
rows = [
_parse_profile_row(
grid,
row_index=index,
profile=profile,
contract=contract,
source_role=row_roles[index] if index < len(row_roles) else 'data',
)
for index in range(profile.data_start_row_index, grid.row_count)
]
if not rows:
return OrderProfileParseResult(matched=False)
return OrderProfileParseResult(
matched=True,
profile_code=profile.profile_code,
profile_version=profile.version,
rows=rows,
)
def _parse_profile_row(
grid: HtmlGrid,
*,
row_index: int,
profile: OrderDocumentProfile,
contract: TableHeaderContract,
source_role: str = 'data',
) -> OrderProfileRowResult:
"""执行一条逻辑模板行;坐标重建删除状态和零 Qty 均映射为 deleted。"""
fields: dict[str, Any] = {}
issues: list[str] = []
explicit_qty: float | None = None
for rule in profile.column_rules:
slot = grid.rows[row_index][rule.column_index]
raw = slot.text.strip() if slot is not None else ''
extracted = (
{rule.target_field_codes[0]: raw}
if rule.extractor_key == 'direct'
else _apply_profile_extractor(rule.extractor_key, raw)
)
for code in rule.target_field_codes:
candidate = extracted.get(code)
if candidate in (None, ''):
continue
if code == 'qty':
explicit_qty = parse_number(candidate)
config = contract.fields_by_code.get(code)
value = _normalize_profile_value(candidate, config)
if value is None:
issues.append(f'order_profile_field_invalid:{code}')
continue
fields[code] = _profile_json_value(value)
if source_role == 'deleted' or (profile.drop_zero_qty and explicit_qty == 0):
return OrderProfileRowResult(row_index=row_index, status='deleted')
required_build = {'part_number', 'qty'}
if not required_build.issubset(fields):
issues.append('order_profile_build_fields_missing')
return OrderProfileRowResult(
row_index=row_index,
status='parsed' if not issues else 'needs_review',
fields=fields,
issues=sorted(set(issues)),
)
def _profile_html_row_roles(source_html: str) -> list[str]:
"""读取坐标重建写入的受控行角色;普通 MinerU HTML 默认按 data 处理。"""
from bs4 import BeautifulSoup
table = BeautifulSoup(source_html or '', 'html.parser').find('table')
if table is None:
return []
return [str(row.get('data-row-role') or 'data') for row in table.find_all('tr')]
def _apply_profile_extractor(extractor_key: str, raw: str) -> dict[str, Any]:
"""执行代码注册的有限解析器;未知 key 不允许运行。"""
if extractor_key == 'temp_internal_parts':
resolved = resolve_composite_part_numbers(raw)
if resolved:
return resolved
customer = re.search(r'\b(?:AM)?TEMP-[A-Z0-9._-]+\b', raw, re.IGNORECASE)
internal = re.search(r'\bD4-[A-Z0-9._-]+\b', raw, re.IGNORECASE)
if customer and internal:
return {
'customer_part_number': customer.group(0),
'part_number': internal.group(0),
}
return {}
raise ValueError('order profile extractor is not registered')
def _normalize_profile_value(raw: Any, config: dict[str, Any] | None) -> Any:
"""按冻结 Schema 类型和 validator 规范化模板字段;模板日期兼容常见美式订单格式。"""
if config is None:
return None
value_type = str(config.get('value_type') or 'string')
candidate = raw
if value_type == 'date':
text = str(raw or '').strip()
matched = re.fullmatch(r'(\d{1,2})/(\d{1,2})/(\d{4})', text)
if matched:
candidate = f'{matched.group(3)}-{int(matched.group(1)):02d}-{int(matched.group(2)):02d}'
if value_type in {'decimal', 'integer'}:
candidate = parse_number(raw)
if candidate is None:
return None
if value_type == 'integer':
if not float(candidate).is_integer():
return None
candidate = int(candidate)
try:
value = normalize_order_field_value(candidate, config)
return value if value is not None and validate_order_field_value(value, config) else None
except (ArithmeticError, TypeError, ValueError, ValidationError):
return None
def _profile_json_value(value: Any) -> Any:
"""把字段规则返回值转换为数据库 JSON 可序列化标量。"""
if isinstance(value, Decimal):
return int(value) if value == value.to_integral_value() else float(value)
return value.isoformat() if hasattr(value, 'isoformat') else value
@@ -4,6 +4,7 @@ services/shipping_notice/document_layout/order_profile_extractors.py
用途:执行订单坐标 Profile v2 的有限注册字段解析器。
依赖:订单料号复合解析与数值解析。
逻辑:坐标重建先取得管理员框选的原文,本模块再将其安全拆成固定业务字段;任何拆分失败均不返回部分字段。
另提供 XFA/坐标共用的 ``unit_price / price_unit``(如 ``898.72 / 1``)确定性拆分。
"""
from __future__ import annotations
@@ -18,9 +19,44 @@ from app.services.shipping_notice.reservation_id import validated_reservation_id
_NUMBER_UNIT = re.compile(r'^\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*([A-Za-z]{1,12})\s*$')
_MONEY_CURRENCY = re.compile(r'^\s*([A-Za-z]{3}|[$€£¥])\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*$')
_CURRENCY_MONEY = re.compile(r'^\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*([A-Za-z]{3}|[$€£¥])\s*$')
# 真实 XFA NETPR 常见写法:单价 / 价格单位,例如 ``898.72 / 1``。
_UNIT_PRICE_PER_PRICE_UNIT = re.compile(
r'^\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*/\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*$'
)
_CURRENCY_SYMBOLS = {'$': 'USD', '€': 'EUR', '£': 'GBP', '¥': 'CNY'}
def parse_unit_price_with_price_unit(raw: str | None) -> dict[str, str] | None:
"""
解析 ``单价 / 价格单位`` 复合文本。
核心逻辑:仅接受确定性 ``number / number``;逗号千分位剔除后返回两段字符串。
不匹配时返回 None(调用方回退单字段 Decimal 解析)。
Args:
raw: datasets / 单元格原文,例如 ``898.72 / 1``。
Returns:
``{'unit_price': '...', 'price_unit': '...'}`` 或 None。
"""
text = str(raw or '').strip()
if not text or '/' not in text:
return None
matched = _UNIT_PRICE_PER_PRICE_UNIT.fullmatch(text)
if not matched:
return None
unit_price = matched.group(1).replace(',', '')
price_unit = matched.group(2).replace(',', '')
try:
Decimal(unit_price)
Decimal(price_unit)
except (InvalidOperation, ValueError):
return None
if not unit_price or not price_unit:
return None
return {'unit_price': unit_price, 'price_unit': price_unit}
def extract_profile_field_value(*, extractor_key: str, field_code: str, raw: str) -> dict[str, str]:
"""将已确认区域按注册解析器拆分,并把预约单号统一为合法纯数字。"""
text = str(raw or '').strip()
@@ -56,6 +92,8 @@ def extract_profile_field_value(*, extractor_key: str, field_code: str, raw: str
'line_amount_before_tax' if extractor_key == 'amount_currency' else 'unit_price': amount.replace(',', ''),
'currency': _CURRENCY_SYMBOLS.get(currency, currency.upper()),
}
if extractor_key == 'unit_price_price_unit':
return parse_unit_price_with_price_unit(text) or {}
return {}
@@ -71,4 +109,6 @@ def registered_extractor_output_codes(*, extractor_key: str, field_code: str) ->
return {'line_amount_before_tax', 'currency'}
if extractor_key == 'price_currency':
return {'unit_price', 'currency'}
if extractor_key == 'unit_price_price_unit':
return {'unit_price', 'price_unit'}
return set()
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,257 @@
"""
services/shipping_notice/document_layout/order_profile_parse_validation.py
用途:对模板匹配候选做只读解析可行性校验,不创建 Candidate/Order/Task。
依赖:OrderCoordinateProfile、coordinate_region_text、order_profile 契约。
逻辑:由 order_extraction_workflow 在 matcher 硬门禁后调用;确定性/idempotent;
返回 passed/reason_codes/metrics 供 unique_match 二次裁决。
"""
from __future__ import annotations
import re
from typing import Any
from app.services.shipping_notice.document_layout.coordinate_region_text import read_coordinate_region_text
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile
_NUMERIC_PATTERN = re.compile(r'^-?\d+([.,]\d+)?$')
_DATE_PATTERN = re.compile(
r'^(?:\d{4}[-/\.]\d{1,2}[-/\.]\d{1,2}|\d{1,2}[-/\.]\d{1,2}[-/\.]\d{4})$',
)
def validate_profile_parse_candidate(
*,
profile_snapshot: dict[str, Any],
layout: dict[str, Any],
definition: dict[str, Any],
) -> dict[str, Any]:
"""
校验 Profile 是否具备在当前 layout 上完成坐标解析的结构前提。
核心逻辑:解析模板定义 → 统计 header/line 字段区覆盖 → 估计明细行数 →
检测未知列与基础类型合理性;只读,不写入任何业务实体。
Args:
profile_snapshot: 冻结 Profile 快照(含 definition)。
layout: 冻结 layout 快照,含 coordinate_evidence。
definition: Schema definition_json,用于字段 scope/类型参考。
Returns:
{passed: bool, reason_codes: list[str], metrics: dict}。
"""
reason_codes: list[str] = []
profile_def = profile_snapshot.get('definition') if isinstance(profile_snapshot.get('definition'), dict) else {}
try:
profile = OrderCoordinateProfile(
profile_code=str(profile_snapshot.get('profile_code') or profile_def.get('profile_code') or 'TMP'),
version=int(profile_snapshot.get('version') or profile_def.get('version') or 1),
document_match=profile_def.get('document_match') or {'required_anchors': [], 'optional_anchors': []},
table_regions=profile_def.get('table_regions') or [],
order_field_layouts=profile_def.get('order_field_layouts') or [],
)
except (TypeError, ValueError):
return {
'passed': False,
'reason_codes': ['profile_parse_definition_invalid'],
'metrics': {},
}
schema_fields = {
str(item.get('field_code') or ''): item
for item in definition.get('fields') or []
if isinstance(item, dict) and item.get('enabled', True) and item.get('field_code')
}
glyphs, page = _page_glyphs(layout)
if glyphs is None or page is None:
return {
'passed': False,
'reason_codes': ['profile_parse_evidence_missing'],
'metrics': {'layouts_with_pages': 0},
}
# [STEP 1] Header 字段覆盖
header_required = [
item for item in profile.order_field_layouts
if item.scope == 'header' and item.required
]
header_bound = [item for item in profile.order_field_layouts if item.scope == 'header']
header_coverage = _field_region_coverage(
fields=header_bound, glyphs=glyphs, page=page,
)
# [STEP 2] Line 字段覆盖
line_fields = [
field for table in profile.table_regions for layout in table.line_layouts
for field in layout.field_regions if field.scope == 'line'
]
line_coverage = _field_region_coverage(fields=line_fields, glyphs=glyphs, page=page)
# [STEP 3] 明细行数启发式
line_count = _estimate_line_count(profile=profile, glyphs=glyphs, page=page)
min_lines = 1
max_lines = max(500, len(glyphs) // max(1, len(line_fields) or 1))
valid_line_count = min_lines <= line_count <= max_lines
if not valid_line_count:
reason_codes.append('profile_parse_line_count_invalid')
# [STEP 4] 未知列启发式:line 字段区无文字的比例
empty_regions = line_coverage.get('empty_region_count', 0)
total_regions = line_coverage.get('total_region_count', 0)
unknown_column_ratio = (empty_regions / total_regions) if total_regions else 0.0
if unknown_column_ratio > 0.6:
reason_codes.append('profile_parse_unknown_columns')
# [STEP 5] 类型 sanity(轻量)
type_issues = _type_sanity_issues(
line_fields=line_fields, glyphs=glyphs, page=page, schema_fields=schema_fields,
)
if type_issues:
reason_codes.append('profile_parse_type_sanity_failed')
required_header_ratio = header_coverage.get('coverage_ratio', 0.0)
if header_required and required_header_ratio < 0.5:
reason_codes.append('profile_parse_header_coverage_insufficient')
required_line_codes = {
field.field_code
for table in profile.table_regions
for layout in table.line_layouts
for field in layout.field_regions
if field.scope == 'line'
}
if required_line_codes and line_coverage.get('coverage_ratio', 0.0) < 0.4:
reason_codes.append('profile_parse_line_coverage_insufficient')
metrics = {
'header_field_count': len(header_bound),
'header_coverage_ratio': round(required_header_ratio, 4),
'line_field_count': len(line_fields),
'line_coverage_ratio': round(line_coverage.get('coverage_ratio', 0.0), 4),
'estimated_line_count': line_count,
'unknown_column_ratio': round(unknown_column_ratio, 4),
'type_issue_count': len(type_issues),
}
passed = not reason_codes
if not passed:
reason_codes.append('profile_parse_validation_failed')
return {
'passed': passed,
'reason_codes': sorted(set(reason_codes)),
'metrics': metrics,
}
def _page_glyphs(layout: dict[str, Any]) -> tuple[list[dict[str, Any]] | None, dict[str, Any] | None]:
"""读取首页字符与页尺寸。"""
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
page = pages.get('1') or pages.get(1)
if not isinstance(page, dict):
return None, None
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
glyphs = page_glyphs.get('1') or page_glyphs.get(1)
if not isinstance(glyphs, list):
glyphs = []
for table_glyphs in glyph_tables.values():
if isinstance(table_glyphs, list):
glyphs.extend(table_glyphs)
if not isinstance(glyphs, list) or not glyphs:
return None, page
return glyphs, page
def _field_region_coverage(
*,
fields: list[Any],
glyphs: list[dict[str, Any]],
page: dict[str, Any],
) -> dict[str, Any]:
"""统计字段区域是否有非空文字。"""
if not fields:
return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0}
non_empty = 0
measurable = 0
for field in fields:
region = _field_validation_region(field)
if region is None:
continue
measurable += 1
text = read_coordinate_region_text(glyphs=glyphs, page=page, region=region)
if str(text or '').strip():
non_empty += 1
total = measurable
return {
'coverage_ratio': non_empty / total if total else 1.0,
'empty_region_count': total - non_empty,
'total_region_count': total,
}
def _field_validation_region(field: Any) -> dict[str, Any] | None:
"""
读取 FieldRegion 或 OrderFieldLayout 可直接验证的绝对区域。
核心逻辑:订单头相对 anchor 的 value_region 需要先定位锚点,当前轻量验证器不重复执行字段抽取;
仅验证 absolute_value_region/fallback_value_region,无法直接度量时返回 None 而不是抛异常。
"""
for key in ('region', 'absolute_value_region', 'fallback_value_region'):
value = getattr(field, key, None)
if value is not None:
return value.model_dump() if hasattr(value, 'model_dump') else value
return None
def _estimate_line_count(
*,
profile: OrderCoordinateProfile,
glyphs: list[dict[str, Any]],
page: dict[str, Any],
) -> int:
"""按主表区垂直带内非空行带估计明细行数。"""
if not profile.table_regions:
return 0
table = profile.table_regions[0]
region = table.region.model_dump()
height = float(page.get('height') or 1)
y0 = float(region.get('y0', 0)) * height
y1 = float(region.get('y1', 1)) * height
row_height = max(8.0, (y1 - y0) / max(1, len(table.line_layouts) or 1) / 3)
lines: set[int] = set()
for glyph in glyphs:
bbox = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else {}
try:
center_y = (float(bbox.get('y0', 0)) + float(bbox.get('y1', 0))) / 2
except (TypeError, ValueError):
continue
if y0 <= center_y <= y1 and str(glyph.get('text') or '').strip():
lines.add(int(center_y // row_height))
return max(0, len(lines))
def _type_sanity_issues(
*,
line_fields: list[Any],
glyphs: list[dict[str, Any]],
page: dict[str, Any],
schema_fields: dict[str, dict[str, Any]],
) -> list[str]:
"""对数量/日期类字段做轻量类型检查。"""
issues: list[str] = []
for field in line_fields:
schema = schema_fields.get(field.field_code) or {}
value_type = str(schema.get('value_type') or schema.get('type') or '').lower()
if value_type not in {'number', 'integer', 'decimal', 'date', 'datetime'}:
continue
region = field.region.model_dump() if hasattr(field.region, 'model_dump') else field.region
text = str(read_coordinate_region_text(glyphs=glyphs, page=page, region=region) or '').strip()
if not text:
continue
if value_type in {'number', 'integer', 'decimal'} and not _NUMERIC_PATTERN.match(text.replace(',', '')):
issues.append(field.field_code)
if value_type in {'date', 'datetime'} and not _DATE_PATTERN.match(text):
issues.append(field.field_code)
return issues
@@ -0,0 +1,576 @@
"""
services/shipping_notice/document_layout/order_profile_signature.py
用途:从模板定义与冻结样本坐标证据生成不可变版面签名(统计摘要,不含正文/URL)。
依赖:order_profile 契约、coordinate_region_text、标准库 hashlib/json/statistics。
逻辑:由 validation_service 在发布检查前调用;本模块不负责数据库提交或 Profile 引用更新。
"""
from __future__ import annotations
import hashlib
import json
import re
import statistics
from typing import Any
from app.services.shipping_notice.document_layout.coordinate_region_text import (
positioned_token_spans,
read_coordinate_region_text,
)
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile, RelativeRegion
from app.services.shipping_notice.order_extraction_route_contract import PROFILE_SCORING_POLICY_ID
# 稳定签名类型用于审计识别,不参与运行时版本分支。
LAYOUT_SIGNATURE_ID = 'order-profile-layout-signature'
MATCHER_POLICY_ID = PROFILE_SCORING_POLICY_ID
# 动态业务值不得进入表头签名;仅保留多样本稳定出现的固定文字。
_DYNAMIC_TOKEN_PATTERNS = (
re.compile(r'^\d{4}[-/\.]\d{1,2}[-/\.]\d{1,2}$'),
re.compile(r'^\d{1,2}[-/\.]\d{1,2}[-/\.]\d{2,4}$'),
re.compile(r'^[A-Z]{0,4}\d{5,}[A-Z0-9\-]*$', re.IGNORECASE),
re.compile(r'^\d+([.,]\d+)?$'),
re.compile(r'^(po|p\.?o\.?|qty|quantity|amount|price|date|no\.?|#)\s*[:#-]?\s*\S+', re.IGNORECASE),
)
def build_layout_signature(
*,
definition: dict[str, Any],
sample_layouts: list[dict[str, Any]],
source_sample_refs: list[dict[str, Any]] | None = None,
layout_version_refs: list[dict[str, Any]] | None = None,
provider_versions: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""
生成版面签名快照;相同输入必须得到相同 checksum。
核心逻辑:解析模板表区/表头/字段关系 → 从样本区域读取固定文字 → 多样本聚合
中位数与容差 → 过滤动态值与单样本噪声 → 计算稳定 checksum。
Args:
definition: 当前草稿或冻结 Profile 定义 JSON。
sample_layouts: 冻结 layout 快照列表,含 coordinate_evidence。
source_sample_refs: 安全样本身份引用(id/role/content_hash),不含文件名正文。
layout_version_refs: Layout 版本身份引用。
provider_versions: Provider/Parser 版本摘要。
Returns:
含 signature / signature_checksum / matcher_policy_version 的快照字典。
Raises:
ValueError: 定义无法解析为 OrderCoordinateProfile。
"""
# [STEP 1] 解析模板契约
profile = OrderCoordinateProfile(
profile_code=str(definition.get('profile_code') or 'TMP'),
version=int(definition.get('version') or 1),
document_match=definition.get('document_match') or {
'required_anchors': [], 'optional_anchors': [],
},
table_regions=definition.get('table_regions') or [],
order_field_layouts=definition.get('order_field_layouts') or [],
)
# [STEP 2] 页面与表区几何模式
page_patterns = _build_page_patterns(sample_layouts=sample_layouts)
table_patterns = [
_build_table_pattern(table=table, sample_layouts=sample_layouts)
for table in profile.table_regions
]
field_relation_graph = _build_field_relation_graph(profile, sample_layouts=sample_layouts)
evidence_quality = _build_evidence_quality(
sample_layouts=sample_layouts,
table_patterns=table_patterns,
source_sample_count=len(sample_layouts),
)
signature = {
'signature_version': LAYOUT_SIGNATURE_ID,
'page_patterns': page_patterns,
'table_patterns': table_patterns,
'field_relation_graph': field_relation_graph,
'applicable_dimensions': [
'header_semantic_position',
'column_topology',
'table_geometry',
'page_structure',
'field_spatial_relation',
'optional_static_text',
'trusted_business_context',
],
'evidence_quality': evidence_quality,
}
checksum = signature_checksum(signature)
return {
'signature': signature,
'signature_checksum': checksum,
'source_sample_refs': list(source_sample_refs or []),
'layout_version_refs': list(layout_version_refs or []),
'provider_versions': list(provider_versions or []),
'matcher_policy_version': MATCHER_POLICY_ID,
}
def signature_checksum(signature: dict[str, Any]) -> str:
"""
对签名主体计算稳定 SHA-256;忽略非签名元数据字段。
Args:
signature: 签名主体(不含 checksum / refs)。
Returns:
64 位十六进制 checksum。
"""
encoded = json.dumps(signature, sort_keys=True, ensure_ascii=True, separators=(',', ':')).encode()
return hashlib.sha256(encoded).hexdigest()
def signature_is_safe_for_audit(snapshot: dict[str, Any]) -> bool:
"""
检查签名快照是否不含原件 URL、凭据或超长正文。
Args:
snapshot: ValidationRun.result_snapshot_json 候选。
Returns:
True 表示可通过审计安全边界。
"""
forbidden_substrings = ('http://', 'https://', 'minio', 'password', 'token=', 'secret')
blob = json.dumps(snapshot, ensure_ascii=True).casefold()
if any(item in blob for item in forbidden_substrings):
return False
# 表头 token 单条过长视为可能混入正文
signature = snapshot.get('signature') if isinstance(snapshot.get('signature'), dict) else {}
for table in signature.get('table_patterns') or []:
for token in (table.get('header_tokens') or []):
if len(str(token)) > 80:
return False
return True
def _build_page_patterns(*, sample_layouts: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""汇总首页宽高比与表格数量范围。"""
ratios: list[float] = []
table_counts: list[int] = []
for layout in sample_layouts:
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
first = pages.get('1') or pages.get(1) or next(iter(pages.values()), None)
if isinstance(first, dict):
width = float(first.get('width') or 0)
height = float(first.get('height') or 0)
if width > 0 and height > 0:
ratios.append(width / height)
tables = [item for item in (layout.get('tables') or []) if isinstance(item, dict)]
if tables:
table_counts.append(len(tables))
# Evidence missing in every sample is not a template-shaped default. The
# matcher will mark this dimension unavailable instead of rewarding config.
if not ratios or not table_counts:
return []
median_ratio = statistics.median(ratios)
low = min(table_counts)
high = max(table_counts)
return [{
'page_scope': 'first_page',
'aspect_ratio': {
'median': round(median_ratio, 4),
'tolerance': 0.03,
},
'table_count_range': [low, high],
}]
def _build_table_pattern(*, table: Any, sample_layouts: list[dict[str, Any]]) -> dict[str, Any]:
"""从样本实际表格与字符坐标聚合版面特征,不以标注框伪造观测结果。"""
region = table.region
bbox_samples: list[list[float]] = []
header_tokens_by_sample: list[list[str]] = []
column_centers_by_sample: list[list[float]] = []
column_widths_by_sample: list[list[float]] = []
header_layouts = list(table.header_layouts or [])
header_region = _union_relative_regions([item.region for item in header_layouts])
field_regions = [
field for layout in header_layouts for field in (layout.field_regions or [])
] or [
field for layout in (table.line_layouts or []) for field in (layout.field_regions or [])
]
column_count = len(field_regions) or max(
(len(layout.field_regions or []) for layout in (table.line_layouts or [])),
default=0,
)
for layout in sample_layouts:
observed = _observe_sample_table(
layout, target_region=region, header_region=header_region,
)
if observed is None:
continue
bbox_samples.append(observed['bbox'])
header_tokens_by_sample.append(observed['header_tokens'])
if observed['column_centers']:
column_centers_by_sample.append(observed['column_centers'])
column_widths_by_sample.append(observed['column_width_ratios'])
stable_tokens = _stable_tokens(header_tokens_by_sample)
median_bbox = _median_vector(bbox_samples)
median_centers = _median_columns(column_centers_by_sample)
median_widths = _median_columns(column_widths_by_sample)
return {
'region_id': table.region_id,
'page_scope': table.page_scope,
'bbox': {
'median': [round(v, 4) for v in median_bbox] if median_bbox else None,
'tolerance': [0.03, 0.04, 0.03, 0.05],
},
'header_bbox': [
header_region.x0, header_region.y0, header_region.x1, header_region.y1,
] if header_region is not None else None,
'header_row_count': max(1, len(header_layouts)),
'column_count': int(len(median_centers) or column_count),
'column_centers': median_centers,
'column_width_ratios': median_widths,
'header_tokens': stable_tokens,
'header_order': list(stable_tokens),
}
def _build_field_relation_graph(
profile: OrderCoordinateProfile, *, sample_layouts: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""记录样本中实际静态标签的相对位置;缺观测不以模板坐标替代。"""
relations: list[dict[str, Any]] = []
layouts = list(profile.order_field_layouts or [])
for index, left in enumerate(layouts):
if left.anchor is None:
continue
left_label = str(left.anchor.text or '').strip()
if not left_label:
continue
for right in layouts[index + 1:]:
if right.anchor is None:
continue
right_label = str(right.anchor.text or '').strip()
if not right_label:
continue
offsets = []
for sample in sample_layouts:
left_center = _find_text_center(sample, left_label)
right_center = _find_text_center(sample, right_label)
if left_center and right_center:
offsets.append((right_center[0] - left_center[0], right_center[1] - left_center[1]))
if not offsets:
continue
relations.append({
'left_field_code': left.field_code,
'right_field_code': right.field_code,
'left_label': left_label,
'right_label': right_label,
'dx': round(statistics.median(item[0] for item in offsets), 4),
'dy': round(statistics.median(item[1] for item in offsets), 4),
})
return relations[:32]
def _observe_sample_table(
layout: dict[str, Any], *, target_region: RelativeRegion,
header_region: RelativeRegion | None,
) -> dict[str, Any] | None:
"""读取样本中与标注区域重叠最高的真实表格及其页级字符几何。"""
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
selected: tuple[dict[str, Any], dict[str, Any], list[float]] | None = None
for item in tables:
page = pages.get(str(item.get('page_no') or 1)) or pages.get(item.get('page_no') or 1)
bbox = item.get('bbox') if isinstance(item.get('bbox'), dict) else {}
if not isinstance(page, dict):
continue
normalized = _normalized_bbox(bbox, page=page)
if normalized is None:
glyphs = page_glyphs.get(str(item.get('page_no') or 1)) or page_glyphs.get(item.get('page_no') or 1) or []
normalized = _glyph_union_bbox(glyphs, page=page)
if normalized is None:
continue
overlap = _bbox_overlap(normalized, [target_region.x0, target_region.y0, target_region.x1, target_region.y1])
if selected is None or overlap > _bbox_overlap(selected[2], [target_region.x0, target_region.y0, target_region.x1, target_region.y1]):
selected = (item, page, normalized)
if selected is None:
return None
item, page, bbox = selected
glyphs = page_glyphs.get(str(item.get('page_no') or 1)) or page_glyphs.get(item.get('page_no') or 1) or []
if not isinstance(glyphs, list):
return None
table_glyphs = [glyph for glyph in glyphs if _glyph_center_in_bbox(glyph, bbox, page=page)]
header_bbox = (
[header_region.x0, header_region.y0, header_region.x1, header_region.y1]
if header_region is not None else None
)
header_glyphs = _header_glyphs(
table_glyphs, page=page, bbox=bbox, header_bbox=header_bbox,
)
header_tokens, centers, widths = _header_observation(
header_glyphs, page=page, bbox=bbox,
)
return {
'bbox': bbox,
'header_tokens': header_tokens,
'column_centers': centers,
'column_width_ratios': widths,
}
def _normalized_bbox(bbox: dict[str, Any], *, page: dict[str, Any]) -> list[float] | None:
"""将 MinerU/PDF 表格 bbox 统一为 0..1 坐标。"""
try:
raw = [float(bbox[key]) for key in ('x0', 'y0', 'x1', 'y1')]
width, height = float(page.get('width')), float(page.get('height'))
except (KeyError, TypeError, ValueError):
return None
if width <= 0 or height <= 0 or raw[2] <= raw[0] or raw[3] <= raw[1]:
return None
if max(raw) <= 1.0:
return raw
return [raw[0] / width, raw[1] / height, raw[2] / width, raw[3] / height]
def _bbox_overlap(left: list[float], right: list[float]) -> float:
"""计算两个规范化矩形的 IoU,供选择实际表格。"""
x0, y0 = max(left[0], right[0]), max(left[1], right[1])
x1, y1 = min(left[2], right[2]), min(left[3], right[3])
intersection = max(0.0, x1 - x0) * max(0.0, y1 - y0)
union = (left[2] - left[0]) * (left[3] - left[1]) + (right[2] - right[0]) * (right[3] - right[1]) - intersection
return intersection / union if union > 0 else 0.0
def _glyph_center_in_bbox(glyph: dict[str, Any], bbox: list[float], *, page: dict[str, Any]) -> bool:
"""判断字符中心是否位于真实表格中。"""
raw = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else {}
try:
x = (float(raw.get('x0')) + float(raw.get('x1'))) / 2 / float(page['width'])
y = (float(raw.get('y0')) + float(raw.get('y1'))) / 2 / float(page['height'])
except (KeyError, TypeError, ValueError):
return False
return bbox[0] <= x <= bbox[2] and bbox[1] <= y <= bbox[3]
def _header_glyphs(
glyphs: list[dict[str, Any]], *, page: dict[str, Any], bbox: list[float],
header_bbox: list[float] | None,
) -> list[dict[str, Any]]:
"""优先消费管理员标注的表头区域;旧定义缺失时才使用保守顶部区域。"""
region = header_bbox or [
bbox[0], bbox[1], bbox[2],
bbox[1] + max(0.06, (bbox[3] - bbox[1]) * 0.18),
]
return [
item for item in glyphs
if _glyph_center_in_bbox(item, region, page=page)
]
def _union_relative_regions(regions: list[RelativeRegion]) -> RelativeRegion | None:
"""合并多行表头标注区域,冻结为 Matcher 可直接消费的唯一相对坐标框。"""
if not regions:
return None
return RelativeRegion(
x0=min(item.x0 for item in regions), y0=min(item.y0 for item in regions),
x1=max(item.x1 for item in regions), y1=max(item.y1 for item in regions),
)
def _header_observation(
glyphs: list[dict[str, Any]], *, page: dict[str, Any], bbox: list[float],
) -> tuple[list[str], list[float], list[float]]:
"""从表头 token 边界生成文本、中心和宽度,禁止按单字符连续间距伪造业务列。"""
try:
page_width = float(page['width'])
except (KeyError, TypeError, ValueError):
return [], [], []
spans = [
item for item in positioned_token_spans(glyphs, respect_explicit_spaces=False)
if _usable_header_token(str(item.get('text') or ''))
][:32]
tokens = [_normalize_header_token(str(item['text'])) for item in spans]
centers = [round((float(item['x0']) + float(item['x1'])) / 2 / page_width, 4) for item in spans]
span = max(bbox[2] - bbox[0], 0.0001)
widths = [round((float(item['x1']) - float(item['x0'])) / page_width / span, 4) for item in spans]
return tokens, centers, widths
def _usable_header_token(token: str) -> bool:
"""过滤分隔线、动态值和无意义短 token,仅冻结稳定表头文字。"""
normalized = _normalize_header_token(token)
if not normalized or not re.search(r'[A-Za-z\u3400-\u9fff]', normalized):
return False
return not _is_dynamic_token(normalized)
def _find_text_center(layout: dict[str, Any], text: str) -> tuple[float, float] | None:
"""在页级字符中定位静态标签中心;仅返回归一化坐标。"""
expected = ''.join(text.casefold().split())
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
glyph_pages = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
for key, page in pages.items():
glyphs = glyph_pages.get(key) or glyph_pages.get(str(key)) or []
if not isinstance(page, dict) or not isinstance(glyphs, list):
continue
ordered = sorted((item for item in glyphs if isinstance(item.get('bbox'), dict)), key=lambda item: (item['bbox'].get('y0', 0), item['bbox'].get('x0', 0)))
joined = ''.join(str(item.get('text') or '') for item in ordered).casefold()
start = ''.join(joined.split()).find(expected)
if start < 0:
continue
# Character evidence is normally one glyph per character; find the matching
# compact-text span without persisting any document text.
compact_index = 0
matched: list[dict[str, Any]] = []
for item in ordered:
chars = ''.join(str(item.get('text') or '').casefold().split())
if not chars:
continue
if start <= compact_index < start + len(expected):
matched.append(item)
compact_index += len(chars)
if matched:
try:
width, height = float(page['width']), float(page['height'])
xs = [(float(item['bbox']['x0']) + float(item['bbox']['x1'])) / 2 / width for item in matched]
ys = [(float(item['bbox']['y0']) + float(item['bbox']['y1'])) / 2 / height for item in matched]
return statistics.median(xs), statistics.median(ys)
except (KeyError, TypeError, ValueError):
continue
return None
def _glyph_union_bbox(glyphs: Any, *, page: dict[str, Any]) -> list[float] | None:
"""在 Provider 未给表框时由实际表内字符求并集,绝不回退模板标注框。"""
if not isinstance(glyphs, list):
return None
try:
width, height = float(page['width']), float(page['height'])
boxes = [item['bbox'] for item in glyphs if isinstance(item, dict) and isinstance(item.get('bbox'), dict)]
if not boxes:
return None
return [
min(float(box['x0']) for box in boxes) / width,
min(float(box['y0']) for box in boxes) / height,
max(float(box['x1']) for box in boxes) / width,
max(float(box['y1']) for box in boxes) / height,
]
except (KeyError, TypeError, ValueError, ZeroDivisionError):
return None
def _build_evidence_quality(
*,
sample_layouts: list[dict[str, Any]],
table_patterns: list[dict[str, Any]],
source_sample_count: int,
) -> dict[str, Any]:
"""输出证据质量摘要,供发布门禁与审计使用。"""
headers_with_tokens = sum(1 for item in table_patterns if item.get('header_tokens'))
pages_present = sum(
1 for layout in sample_layouts
if isinstance((layout.get('coordinate_evidence') or {}).get('pages'), dict)
and (layout.get('coordinate_evidence') or {}).get('pages')
)
return {
'source_sample_count': int(source_sample_count),
'layouts_with_pages': pages_present,
'tables_with_header_tokens': headers_with_tokens,
'header_token_coverage': (
round(headers_with_tokens / max(1, len(table_patterns)), 4) if table_patterns else 0.0
),
}
def _read_region_text(layout: dict[str, Any], region: RelativeRegion) -> str:
"""从冻结 layout 首页坐标证据读取区域内文字;失败返回空串。"""
try:
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
page = pages.get('1') or pages.get(1)
if not isinstance(page, dict):
return ''
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
glyphs = page_glyphs.get('1') or page_glyphs.get(1) or []
if not glyphs:
for table_glyphs in glyph_tables.values():
if isinstance(table_glyphs, list):
glyphs = list(glyphs) + table_glyphs
if not isinstance(glyphs, list) or not glyphs:
return ''
return read_coordinate_region_text(
glyphs=glyphs,
page=page,
region={'x0': region.x0, 'y0': region.y0, 'x1': region.x1, 'y1': region.y1},
)
except Exception:
return ''
def _normalize_header_token(text: str) -> str:
"""规范化表头 token:折叠空白并截断。"""
return ' '.join(str(text or '').split())[:80]
def _split_header_tokens(text: str) -> list[str]:
"""将表头区域整体文字按空白拆成候选 token。"""
return [_normalize_header_token(part) for part in re.split(r'[\s|/]+', text) if part.strip()]
def _is_dynamic_token(token: str) -> bool:
"""判断 token 是否像 PO/日期/数量等动态值。"""
compact = token.strip()
if not compact or len(compact) <= 1:
return True
return any(pattern.search(compact) for pattern in _DYNAMIC_TOKEN_PATTERNS)
def _stable_tokens(samples: list[list[str]]) -> list[str]:
"""仅保留在多数样本中出现的 token,排除单样本噪声。"""
if not samples:
return []
threshold = max(1, (len(samples) + 1) // 2)
counts: dict[str, int] = {}
for tokens in samples:
for token in dict.fromkeys(tokens):
counts[token] = counts.get(token, 0) + 1
stable = [token for token, count in counts.items() if count >= threshold]
# 保持首次样本中的相对顺序
order_index = {token: index for index, token in enumerate(samples[0])}
return sorted(stable, key=lambda item: order_index.get(item, 10_000))
def _median_vector(vectors: list[list[float]]) -> list[float] | None:
"""计算等长向量各维中位数。"""
if not vectors:
return None
width = len(vectors[0])
return [
round(statistics.median(row[index] for row in vectors if len(row) == width), 4)
for index in range(width)
]
def _median_columns(samples: list[list[float]]) -> list[float]:
"""对列中心/列宽多样本取中位数;列数取众数。"""
if not samples:
return []
lengths = [len(item) for item in samples]
target = max(set(lengths), key=lengths.count)
aligned = [item for item in samples if len(item) == target]
if not aligned:
return list(samples[0])
return [
round(statistics.median(row[index] for row in aligned), 4)
for index in range(target)
]
@@ -37,6 +37,53 @@ def _enabled() -> bool:
return bool(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED', False))
def _try_build_xfa_layout_snapshot(
*,
content: bytes,
document_id: int | None = None,
content_hash: str | None = None,
timings: dict[str, int] | None = None,
) -> dict[str, Any] | None:
"""
在 MinerU/PDFium 表格路径前探测 XFA;supported hybrid 直接返回 XFA capability 快照。
核心逻辑:仅对 PDF 字节调用 xfa_analysis;xfa_hybrid 成功时跳过 MinerU,不要求 table ready。
Args:
content: PDF 原始字节。
document_id/content_hash: 文档身份(写入 capability 摘要)。
timings: 可选运维耗时字典。
Returns:
XFA 快照;非 XFA 或 plain/acroform 时返回 None 以继续常规 layout 路径。
"""
if not content or not content.startswith(b'%PDF'):
return None
started = perf_counter()
from app.services.shipping_notice.document_layout.xfa_analysis import analyze_xfa_pdf
from app.services.shipping_notice.document_layout.xfa_contract import default_xfa_resource_limits
limits = default_xfa_resource_limits()
outcome = analyze_xfa_pdf(content, limits=limits)
if timings is not None:
timings['xfa_probe_ms'] = round((perf_counter() - started) * 1000)
packet_result = outcome.packet_result
if packet_result is None:
return None
# plain_pdf / acroform:不拦截,继续 MinerU 表格路径。
if packet_result.document_kind in {'plain_pdf', 'acroform'}:
return None
snapshot = dict(outcome.snapshot)
if document_id:
capability = snapshot.get('xfa_capability') if isinstance(snapshot.get('xfa_capability'), dict) else {}
capability['document_id'] = int(document_id)
if content_hash:
capability['content_hash'] = str(content_hash)
snapshot['xfa_capability'] = capability
snapshot['capability'] = capability
return snapshot
def mineru_layout_capture_enabled(filename: str) -> bool:
"""判断文件是否需要读取二进制并调用 MinerU,供上传链避免默认关闭时重复对象存储 I/O。"""
return _enabled() and Path(str(filename or '')).suffix.lower() in MINERU_SUPPORTED_EXTENSIONS
@@ -54,8 +101,8 @@ def build_mineru_table_snapshot(
"""
为一个受支持附件生成紧凑 MinerU 文本与表格快照。
核心逻辑:文字型 PDF 先用本地坐标和严格表头门槛恢复表格,成功即跳过 MinerU;
本地证据不足时再调用 MinerU。两条路径都冻结相同的页面坐标契约。
核心逻辑:PDFium 仅在 MinerU 前轻量预读原生字符;表格结构始终优先调用 MinerU。
MinerU 空表、配置缺失、调用失败或响应非法时,才允许严格原生文字回退。
Args:
filename: 原附件名,仅用于扩展名和 MinerU multipart,不进入返回错误详情。
@@ -68,6 +115,15 @@ def build_mineru_table_snapshot(
extension = Path(str(filename or '')).suffix.lower()
if not mineru_layout_capture_enabled(filename) or not content:
return None
if extension == '.pdf':
xfa_snapshot = _try_build_xfa_layout_snapshot(
content=content,
document_id=document_id,
content_hash=content_hash,
timings=timings,
)
if xfa_snapshot is not None:
return xfa_snapshot
native_pages: list[Any] | None = None
if extension == '.pdf' and document_id and content_hash:
try:
@@ -77,24 +133,17 @@ def build_mineru_table_snapshot(
native_pages = extract_native_pdf_pages(content, render_images=False)
if timings is not None:
timings['native_pdf_extract_ms'] = round((perf_counter() - native_started) * 1000)
fast_snapshot = _native_pdf_fast_snapshot(
content=content,
document_id=int(document_id),
content_hash=str(content_hash),
native_pages=native_pages,
timings=timings,
)
if fast_snapshot is not None:
if timings is not None:
timings['layout_fast_path'] = 1
return fast_snapshot
except Exception:
native_pages = None
if native_pages is not None:
# 本地文字门槛未命中时,后续 MinerU 增强路径需要完整页面图,按需重新提取。
native_pages = None
base_url = str(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL') or '').strip()
if not base_url:
fallback = _native_pdf_fallback_snapshot(
content=content, document_id=document_id, content_hash=content_hash,
native_pages=native_pages, timings=timings,
provider_issue='mineru_base_url_missing',
)
if fallback is not None:
return fallback
return {
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
'provider': 'mineru',
@@ -124,6 +173,13 @@ def build_mineru_table_snapshot(
if timings is not None:
timings['mineru_result_parse_ms'] = round((perf_counter() - result_parse_started) * 1000)
except AppError as exc:
fallback = _native_pdf_fallback_snapshot(
content=content, document_id=document_id, content_hash=content_hash,
native_pages=native_pages, timings=timings,
provider_issue=str(exc.code),
)
if fallback is not None:
return fallback
return {
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
'provider': 'mineru',
@@ -133,6 +189,13 @@ def build_mineru_table_snapshot(
'issues': [str(exc.code)],
}
except (TypeError, ValueError):
fallback = _native_pdf_fallback_snapshot(
content=content, document_id=document_id, content_hash=content_hash,
native_pages=native_pages, timings=timings,
provider_issue='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
)
if fallback is not None:
return fallback
return {
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
'provider': 'mineru',
@@ -152,6 +215,7 @@ def build_mineru_table_snapshot(
total_html_chars = 0
total_text_chars = 0
issues = list(candidate.capability.issues)
mineru_has_tables = any(page.tables for page in candidate.pages)
for page in candidate.pages:
for block in sorted(
page.text_blocks,
@@ -209,16 +273,18 @@ def build_mineru_table_snapshot(
extract_native_pdf_pages,
)
if native_pages is None:
native_started = perf_counter()
native_pages = extract_native_pdf_pages(content)
if timings is not None:
timings['native_pdf_extract_ms'] = round((perf_counter() - native_started) * 1000)
# MinerU 成功后进入坐标增强链;此时按需补齐页面图,供严格 OpenCV/OCR 门禁使用。
# 前置轻量预读只缓存字符,不得因为已有无图页面而跳过必要的增强证据。
native_started = perf_counter()
native_pages = extract_native_pdf_pages(content)
if timings is not None:
timings['native_pdf_extract_ms'] = round((perf_counter() - native_started) * 1000)
layout_source_candidate = candidate
# MinerU occasionally returns only text blocks for unbordered purchase-order lines.
# Restrict the fallback to an otherwise empty table result so normal templates retain
# the provider's original table structure unchanged.
if not tables:
if not tables and not mineru_has_tables:
fallback_tables = build_native_pdf_text_table_fallbacks(
content,
native_pages=native_pages,
@@ -226,15 +292,26 @@ def build_mineru_table_snapshot(
if fallback_tables:
tables.extend(fallback_tables)
snapshot['tables'] = tables
snapshot['issues'] = sorted(set(
issue for issue in snapshot['issues']
if issue not in {'mineru_table_structure_missing', 'mineru_cell_coordinates_missing'}
) | {'native_pdf_text_table_fallback_used'})
layout_source_candidate = _native_pdf_candidate_from_tables(
native_pages=native_pages,
tables=fallback_tables,
)
snapshot.update({
'provider': 'pdfium',
'provider_version': 'native-text-v1',
'backend': 'native_pdf',
'capability': layout_source_candidate.capability.model_dump(mode='json'),
})
snapshot['issues'] = sorted(set(snapshot['issues']) | {
'mineru_provider_fallback_used',
'mineru_table_structure_missing',
'native_pdf_text_table_fallback_used',
})
layout_started = perf_counter()
layout = build_native_pdf_layout_candidate(
document_id=int(document_id), content_hash=str(content_hash),
content=content, mineru=candidate, native_pages=native_pages,
content=content, mineru=layout_source_candidate, native_pages=native_pages,
)
if timings is not None:
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
@@ -260,37 +337,89 @@ def build_mineru_table_snapshot(
return snapshot
def _native_pdf_fast_snapshot(
*, content: bytes, document_id: int, content_hash: str,
native_pages: list[Any], timings: dict[str, int] | None,
def _native_pdf_fallback_snapshot(
*, content: bytes, document_id: int | None, content_hash: str | None,
native_pages: list[Any] | None, timings: dict[str, int] | None,
provider_issue: str,
) -> dict[str, Any] | None:
"""
用严格原生文字表格证据生成可立即消费的布局快照。
在 MinerU 不可用时,用严格原生文字表格证据生成降级布局快照。
AI/调用方触发时机:版面 Job 收到文字型 PDF 时先调用;只有表头、列边界和
数据行同时成立才返回快照,否则返回 None 继续 MinerU,禁止宽松猜测表格。
AI/调用方触发时机:仅在 MinerU 配置缺失、调用失败或响应非法后调用;MinerU
正常返回时不得调用本函数替换 Provider 表格。只有表头、列边界和数据行同时成立
才返回快照,否则返回 None 并保留原 Provider 失败,禁止宽松猜测表格。
Args:
content: 当前 PDF 字节,仅传给既有布局构建器,不持久化。
document_id/content_hash: 当前不可变 Document 身份。
native_pages: 已完成一次 PDFium 提取的页面,后续阶段必须复用。
document_id/content_hash: 当前不可变 Document 身份;缺失时禁止降级。
native_pages: MinerU 调用前已轻量预读的 PDFium 页面;缺失时禁止降级。
timings: 可选运维阶段耗时,不进入快照。
provider_issue: 触发降级的 MinerU 稳定问题码。
Returns:
证据充分时返回 ready 快照;无法证明业务表格时返回 None。
证据充分时返回带 Provider 失败原因的 ready 降级快照;否则返回 None。
"""
from app.services.shipping_notice.document_layout.native_pdf import (
build_native_pdf_layout_candidate,
build_native_pdf_text_table_fallbacks,
)
if not document_id or not content_hash or not native_pages:
return None
try:
from app.services.shipping_notice.document_layout.native_pdf import (
build_native_pdf_layout_candidate,
build_native_pdf_text_table_fallbacks,
)
fallback_started = perf_counter()
tables = build_native_pdf_text_table_fallbacks(content, native_pages=native_pages)
if timings is not None:
timings['native_table_detect_ms'] = round((perf_counter() - fallback_started) * 1000)
if not tables:
fallback_started = perf_counter()
tables = build_native_pdf_text_table_fallbacks(content, native_pages=native_pages)
if timings is not None:
timings['native_table_detect_ms'] = round((perf_counter() - fallback_started) * 1000)
if not tables:
return None
candidate = _native_pdf_candidate_from_tables(
native_pages=native_pages,
tables=tables,
)
layout_started = perf_counter()
layout = build_native_pdf_layout_candidate(
document_id=int(document_id), content_hash=str(content_hash),
content=content, mineru=candidate, native_pages=native_pages,
)
if timings is not None:
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
layout_payload_preview = layout.model_dump(mode='json')
capability = _capability_with_layout_cells(
candidate.capability.model_dump(mode='json'),
layout_payload=layout_payload_preview,
)
evidence_started = perf_counter()
# Fallback snapshots only need table-local glyphs for template modeling. Keeping
# every page glyph can exceed the persisted snapshot budget on text-heavy PDFs.
evidence = _table_coordinate_evidence(
pages=native_pages, tables=tables, include_page_glyphs=False,
)
if timings is not None:
timings['coordinate_evidence_ms'] = round((perf_counter() - evidence_started) * 1000)
return {
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
'provider': 'pdfium', 'provider_version': 'native-text-v1', 'backend': 'native_pdf',
'status': 'ready', 'text_blocks': [], 'tables': tables,
'capability': capability,
'layout_candidate': layout_payload_preview,
'coordinate_evidence': evidence,
'issues': sorted({
'mineru_provider_fallback_used',
'native_pdf_text_table_fallback_used',
str(provider_issue or 'mineru_provider_failed'),
}),
}
except Exception:
# 降级链不是新的业务真相来源;自身异常时保留 MinerU 原始失败,禁止反向覆盖。
return None
def _native_pdf_candidate_from_tables(
*, native_pages: list[Any], tables: list[dict[str, Any]],
) -> MinerUParseCandidate:
"""把严格 PDFium 回退表转换为统一布局候选;仅供 MinerU 空表或失败降级使用。"""
page_candidates = []
for page in native_pages:
page_tables = []
@@ -308,7 +437,7 @@ def _native_pdf_fast_snapshot(
page_no=int(page.page_no), width=float(page.width), height=float(page.height),
text_blocks=[], tables=page_tables,
))
candidate = MinerUParseCandidate(
return MinerUParseCandidate(
provider_version='pdfium-native-text-v1', backend='native_pdf', pages=page_candidates,
capability=MinerUCapabilityReport(
provider_version='pdfium-native-text-v1', backend='native_pdf',
@@ -322,35 +451,6 @@ def _native_pdf_fast_snapshot(
issues=['native_pdf_text_table_fallback_used'],
),
)
layout_started = perf_counter()
layout = build_native_pdf_layout_candidate(
document_id=document_id, content_hash=content_hash,
content=content, mineru=candidate, native_pages=native_pages,
)
if timings is not None:
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
layout_payload_preview = layout.model_dump(mode='json')
capability = _capability_with_layout_cells(
candidate.capability.model_dump(mode='json'),
layout_payload=layout_payload_preview,
)
evidence_started = perf_counter()
# Fallback snapshots only need table-local glyphs for template modeling. Keeping
# every page glyph can exceed the persisted snapshot budget on text-heavy PDFs.
evidence = _table_coordinate_evidence(
pages=native_pages, tables=tables, include_page_glyphs=False,
)
if timings is not None:
timings['coordinate_evidence_ms'] = round((perf_counter() - evidence_started) * 1000)
return {
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
'provider': 'pdfium', 'provider_version': 'native-text-v1', 'backend': 'native_pdf',
'status': 'ready', 'text_blocks': [], 'tables': tables,
'capability': capability,
'layout_candidate': layout_payload_preview,
'coordinate_evidence': evidence,
'issues': ['native_pdf_text_table_fallback_used'],
}
def _table_coordinate_evidence(
@@ -505,7 +605,7 @@ def attach_mineru_layout_snapshots(result: Any, *, root_asset_bytes: bytes | Non
and mineru_layout_capture_enabled(str(item.get('filename') or ''))
]
max_documents = max(int(current_app.config.get(
'SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', 4,
'SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', 10,
)), 0)
concurrency = max(int(current_app.config.get(
'SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY', 2,
@@ -32,12 +32,13 @@ class TextCellAlignmentModel(BaseModel):
class PositionedCharacter(TextCellAlignmentModel):
"""保存 PDF 原生文本层的单个可见字符、页面坐标与视觉行身份。"""
"""保存 PDF 原生可见字符、坐标及其前置文本流边界;零 bbox 空白不伪造成 glyph。"""
text: str = Field(min_length=1, max_length=8)
bbox: LayoutBBox
source_index: int | None = Field(default=None, ge=0)
line_id: str | None = None
boundary_before: Literal['none', 'space', 'line_break'] = 'none'
class TextAlignedCell(TextCellAlignmentModel):
@@ -0,0 +1,218 @@
"""
backend/app/services/shipping_notice/document_layout/xfa_acroform.py
用途:读取 AcroForm 字段值并生成与 datasets 叶子节点的对账候选。
依赖:pypdf、xfa_dataset.XfaDatasetAnalysis。
逻辑:由 xfa_analysis / xfa_validation 调用;按短名聚合多实例值供行对齐对账;
此处只做候选与分组,不因 display formatting 差异判失败。
"""
from __future__ import annotations
import re
import unicodedata
from dataclasses import dataclass
from io import BytesIO
from typing import Any
from pypdf import PdfReader
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
@dataclass
class XfaAcroformField:
"""单个 AcroForm 字段摘要。"""
qualified_name: str
short_name: str
value: str
value_masked: str
@dataclass
class XfaReconciliationCandidate:
"""datasets 叶子与 AcroForm 字段的对账候选。"""
data_path_hash: str
dataset_value_masked: str
acroform_field_name: str | None
acroform_value_masked: str | None
match_hint: str
def _local_tail(name: str) -> str:
"""
取 SOM 路径最后一段业务短名(忽略实例下标)。
核心逻辑:`form[0].ITEMS[1].MENGE[0]` → `MENGE`;数字段与空段丢弃,
便于按短名聚合多行 Widget 实例。
"""
text = str(name or '').strip()
if not text:
return ''
parts = [part for part in re.split(r'[\.\[\]]+', text) if part and not part.isdigit()]
return parts[-1] if parts else text
def _instance_sort_key(qualified_name: str) -> tuple[int, ...]:
"""
从 SOM 限定名提取实例下标序列,用于多行 Widget 与明细行对齐排序。
Args:
qualified_name: 如 `form[0].Page1[0].MENGE[2]`。
Returns:
下标元组;无下标时返回 (0,)。
"""
matches = re.findall(r'\[(\d+)\]', str(qualified_name or ''))
if not matches:
return (0,)
return tuple(int(item) for item in matches)
def _normalize_key(value: str) -> str:
"""用于候选匹配的规范化键(大小写/空白/标点无关)。"""
text = unicodedata.normalize('NFKC', str(value or '')).strip().lower()
return re.sub(r'[^a-z0-9]+', '', text)
def read_acroform_fields(pdf_bytes: bytes) -> list[XfaAcroformField]:
"""
读取 PDF AcroForm 字段值。
核心逻辑:通过 pypdf get_fields 读取 `/V` 展示值;不执行任何脚本。
Args:
pdf_bytes: 原始 PDF 字节。
Returns:
AcroForm 字段摘要列表;无 AcroForm 时返回空列表。
"""
try:
reader = PdfReader(BytesIO(pdf_bytes), strict=False)
raw_fields = reader.get_fields() or {}
except Exception:
return []
result: list[XfaAcroformField] = []
for qualified_name, field_obj in raw_fields.items():
if not isinstance(field_obj, dict):
continue
value = field_obj.get('/V')
if value is None:
continue
text = str(getattr(value, 'name', value) or value).strip()
if not text:
continue
short_name = _local_tail(str(qualified_name))
result.append(XfaAcroformField(
qualified_name=str(qualified_name),
short_name=short_name,
value=text,
value_masked=mask_value_for_dto(text),
))
return result
def build_reconciliation_candidates(
*,
dataset_analysis: XfaDatasetAnalysis,
acroform_fields: list[XfaAcroformField],
) -> list[XfaReconciliationCandidate]:
"""
为 datasets 叶子生成 AcroForm 对账候选。
核心逻辑:按 localName / 路径尾段做弱匹配;不在此阶段因 display formatting 差异判失败。
Args:
dataset_analysis: datasets 结构分析。
acroform_fields: AcroForm 字段列表。
Returns:
对账候选列表。
"""
by_short_name: dict[str, list[XfaAcroformField]] = {}
by_normalized: dict[str, list[XfaAcroformField]] = {}
ordered = sorted(acroform_fields, key=lambda item: _instance_sort_key(item.qualified_name))
for item in ordered:
by_short_name.setdefault(item.short_name.upper(), []).append(item)
by_normalized.setdefault(_normalize_key(item.short_name), []).append(item)
candidates: list[XfaReconciliationCandidate] = []
for data_path, raw_value in dataset_analysis.leaf_values_by_path.items():
local_name = data_path.rsplit('/', 1)[-1]
dataset_masked = mask_value_for_dto(raw_value)
matched: XfaAcroformField | None = None
match_hint = 'unmatched'
exact = by_short_name.get(local_name.upper()) or []
if len(exact) == 1:
matched = exact[0]
match_hint = 'local_name_exact'
elif len(exact) > 1:
matched = exact[0]
match_hint = 'local_name_ambiguous'
else:
normalized = _normalize_key(local_name)
fuzzy = by_normalized.get(normalized) or []
if len(fuzzy) == 1:
matched = fuzzy[0]
match_hint = 'normalized_exact'
elif len(fuzzy) > 1:
matched = fuzzy[0]
match_hint = 'normalized_ambiguous'
candidates.append(XfaReconciliationCandidate(
data_path_hash=hash_data_path(data_path),
dataset_value_masked=dataset_masked,
acroform_field_name=matched.qualified_name if matched else None,
acroform_value_masked=matched.value_masked if matched else None,
match_hint=match_hint,
))
return candidates
def group_acroform_values_by_short_name(fields: list[XfaAcroformField]) -> dict[str, list[str]]:
"""
按短名聚合 AcroForm 多实例值(SOM 下标排序)。
核心逻辑:同名多 Widget 全部保留,供明细行一一对账;禁止只取首个。
Args:
fields: AcroForm 字段列表。
Returns:
short_name.upper() → 按实例顺序排列的原始展示值列表。
"""
buckets: dict[str, list[XfaAcroformField]] = {}
for item in fields:
key = str(item.short_name or '').strip().upper()
if not key:
continue
buckets.setdefault(key, []).append(item)
result: dict[str, list[str]] = {}
for key, items in buckets.items():
ordered = sorted(items, key=lambda field: _instance_sort_key(field.qualified_name))
result[key] = [field.value for field in ordered]
return result
def serialize_acroform_fields(fields: list[XfaAcroformField]) -> list[dict[str, Any]]:
"""
序列化 AcroForm 字段供安全 DTO 返回。
Args:
fields: AcroForm 字段列表。
Returns:
不含原始 PDF 或完整路径明文的摘要列表。
"""
return [
{
'qualified_name_tail': item.short_name,
'value_masked': item.value_masked,
}
for item in fields
]
@@ -0,0 +1,437 @@
"""
backend/app/services/shipping_notice/document_layout/xfa_analysis.py
用途:编排 XFA packet 读取、datasets 解析、签名计算与布局快照/持久化。
依赖:xfa_packets、xfa_dataset、xfa_signature、xfa_acroform、xfa_contract、
ShippingXfaStructureAnalysis 模型。
逻辑:由 runtime 与 shipping_document_layout Job 调用;成功时写入结构分析记录并返回
不含 XML/PDF 正文的 capability 快照。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any
from app.extensions import db
from app.models import ShippingXfaStructureAnalysis
from app.services.shipping_notice.document_layout.xfa_acroform import (
build_reconciliation_candidates,
read_acroform_fields,
serialize_acroform_fields,
)
from app.services.shipping_notice.document_layout.xfa_contract import (
XFA_CONTRACT_VERSION,
XFA_PARSER_IDENTITY,
hash_data_path,
sanitize_xfa_dto,
)
from app.services.shipping_notice.document_layout.xfa_dataset import (
XfaDatasetAnalysis,
XfaDatasetParseError,
parse_xfa_datasets,
serialize_tree_node,
)
from app.services.shipping_notice.document_layout.xfa_packets import (
XfaPacketError,
XfaPacketReadResult,
is_deterministic_xfa_error,
read_xfa_packets,
)
from app.services.shipping_notice.document_layout.xfa_signature import build_signature_summary
from app.services.shipping_notice.document_layout.runtime import LAYOUT_SNAPSHOT_VERSION
@dataclass
class XfaAnalysisOutcome:
"""XFA 结构分析完整结果。"""
snapshot: dict[str, Any]
packet_result: XfaPacketReadResult | None = None
dataset_analysis: XfaDatasetAnalysis | None = None
error_code: str | None = None
route_reason: str | None = None
deterministic: bool = False
analysis_record: ShippingXfaStructureAnalysis | None = None
issues: list[str] = field(default_factory=list)
def analyze_xfa_pdf(
pdf_bytes: bytes,
*,
limits: dict[str, int] | None = None,
) -> XfaAnalysisOutcome:
"""
对 PDF 执行完整 XFA 结构分析(纯函数,不写数据库)。
Args:
pdf_bytes: 原始 PDF 字节。
limits: 可选资源上限。
Returns:
XfaAnalysisOutcome:含 layout 快照或结构化失败码。
"""
issues: list[str] = []
try:
packet_result = read_xfa_packets(pdf_bytes, limits=limits)
except XfaPacketError as exc:
return XfaAnalysisOutcome(
snapshot=_failed_snapshot(
document_kind='unsupported',
error_code=exc.error_code,
route_reason=exc.route_reason,
issues=[exc.route_reason],
),
error_code=exc.error_code,
route_reason=exc.route_reason,
deterministic=is_deterministic_xfa_error(exc.error_code),
issues=[exc.route_reason],
)
document_kind = packet_result.document_kind
if packet_result.error_code and not packet_result.supported:
return XfaAnalysisOutcome(
snapshot=_failed_snapshot(
document_kind=document_kind,
error_code=packet_result.error_code,
route_reason=packet_result.route_reason or 'xfa_unsupported_document',
issues=[packet_result.route_reason or packet_result.error_code],
packet_result=packet_result,
),
packet_result=packet_result,
error_code=packet_result.error_code,
route_reason=packet_result.route_reason,
deterministic=is_deterministic_xfa_error(packet_result.error_code),
issues=[packet_result.route_reason or packet_result.error_code],
)
if not packet_result.supported:
return XfaAnalysisOutcome(
snapshot=_unsupported_snapshot(packet_result),
packet_result=packet_result,
error_code='XFA_UNSUPPORTED_DOCUMENT',
route_reason='xfa_unsupported_document',
deterministic=True,
issues=['xfa_unsupported_document'],
)
datasets_bytes = packet_result.packet_bytes_by_name.get('datasets')
if not datasets_bytes:
return XfaAnalysisOutcome(
snapshot=_failed_snapshot(
document_kind=document_kind,
error_code='XFA_DATASET_MISSING',
route_reason='xfa_dataset_missing',
issues=['xfa_dataset_missing'],
packet_result=packet_result,
),
packet_result=packet_result,
error_code='XFA_DATASET_MISSING',
route_reason='xfa_dataset_missing',
deterministic=True,
issues=['xfa_dataset_missing'],
)
try:
dataset_analysis = parse_xfa_datasets(datasets_bytes, limits=limits)
except XfaDatasetParseError as exc:
return XfaAnalysisOutcome(
snapshot=_failed_snapshot(
document_kind=document_kind,
error_code=exc.error_code,
route_reason=exc.route_reason,
issues=[exc.route_reason],
packet_result=packet_result,
),
packet_result=packet_result,
error_code=exc.error_code,
route_reason=exc.route_reason,
deterministic=is_deterministic_xfa_error(exc.error_code),
issues=[exc.route_reason],
)
template_bytes = packet_result.packet_bytes_by_name.get('template')
signatures = build_signature_summary(
template_bytes=template_bytes,
dataset_nodes=dataset_analysis.nodes,
)
acroform_fields = read_acroform_fields(pdf_bytes)
reconciliation = build_reconciliation_candidates(
dataset_analysis=dataset_analysis,
acroform_fields=acroform_fields,
)
packet_checksums = {item.name: item.checksum for item in packet_result.packets}
capability = {
'parser_identity': XFA_PARSER_IDENTITY,
'contract_version': XFA_CONTRACT_VERSION,
'document_kind': document_kind,
'structure_analysis_ready': True,
'xfa_dataset_ready': True,
'has_table_structure': False,
'has_page_coordinates': False,
'has_cell_coordinates': False,
'deterministic_cell_evidence_ready': False,
'template_packet_checksum': signatures.get('template_packet_checksum'),
'dataset_structure_fingerprint': signatures.get('dataset_structure_fingerprint'),
'dataset_root_path': dataset_analysis.dataset_root_path,
'packet_checksums': packet_checksums,
'stats': dict(dataset_analysis.stats),
'header_candidate_count': len(dataset_analysis.header_candidates),
'collection_candidate_count': len(dataset_analysis.collection_candidates),
'acroform_field_count': len(acroform_fields),
'reconciliation_candidate_count': len(reconciliation),
'issues': [],
}
issues.append('xfa_document_kind_detected')
issues.append('xfa_structure_analysis_ready')
snapshot = {
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
'provider': 'xfa',
'provider_version': XFA_PARSER_IDENTITY,
'backend': 'xfa_hardened_parser',
'status': 'ready',
'document_kind': document_kind,
'tables': [],
'text_blocks': [],
'xfa_capability': capability,
'capability': capability,
'issues': sorted(set(issues)),
}
return XfaAnalysisOutcome(
snapshot=snapshot,
packet_result=packet_result,
dataset_analysis=dataset_analysis,
issues=snapshot['issues'],
)
def persist_xfa_structure_analysis(
*,
document_id: int,
layout_version_id: int | None,
source_content_hash: str,
outcome: XfaAnalysisOutcome,
) -> ShippingXfaStructureAnalysis:
"""
将 XFA 结构分析摘要持久化到数据库。
Args:
document_id: ShippingOrderDocument 主键。
layout_version_id: 关联布局版本 ID(可空)。
source_content_hash: 文档内容哈希。
outcome: analyze_xfa_pdf 的结果。
Returns:
新建或更新的 ShippingXfaStructureAnalysis 记录。
"""
packet_result = outcome.packet_result
dataset_analysis = outcome.dataset_analysis
capability = (
outcome.snapshot.get('xfa_capability')
if isinstance(outcome.snapshot.get('xfa_capability'), dict)
else {}
)
packet_checksums = capability.get('packet_checksums') if isinstance(capability.get('packet_checksums'), dict) else {}
stats = capability.get('stats') if isinstance(capability.get('stats'), dict) else {}
security_summary = {
'parser_identity': XFA_PARSER_IDENTITY,
'resolve_entities': False,
'load_dtd': False,
'no_network': True,
'huge_tree': False,
'scripts_executed': False,
'preflight_rejected': outcome.error_code == 'XFA_UNSAFE_XML',
}
tree_summary: dict[str, Any] = {}
if dataset_analysis is not None:
tree_summary = {
'dataset_root_path_hash': hash_data_path(dataset_analysis.dataset_root_path),
'header_candidates': list(dataset_analysis.header_candidates),
'collection_candidates': [
{
'collection_path_hash': hash_data_path(item.collection_path),
'path_id': item.path_id,
'row_count': item.row_count,
'local_name': item.collection_path.rstrip('/').rsplit('/', 1)[-1],
'path_label': ' / '.join(item.collection_path.strip('/').split('/')[-3:]),
'sibling_collection_path_hashes': [
hash_data_path(path) for path in item.sibling_collection_paths
],
}
for item in dataset_analysis.collection_candidates
],
'known_path_ids': sorted(dataset_analysis.known_path_ids),
}
status = 'ready' if outcome.snapshot.get('status') == 'ready' else 'failed'
if outcome.error_code == 'XFA_UNSAFE_XML':
status = 'rejected'
record = ShippingXfaStructureAnalysis(
document_id=int(document_id),
layout_version_id=int(layout_version_id) if layout_version_id else None,
source_content_hash=str(source_content_hash or '').lower()[:64],
document_kind=str(
(packet_result.document_kind if packet_result else None)
or outcome.snapshot.get('document_kind')
or 'unsupported',
),
analysis_status=status,
template_packet_checksum=capability.get('template_packet_checksum'),
datasets_packet_checksum=packet_checksums.get('datasets'),
dataset_structure_fingerprint=capability.get('dataset_structure_fingerprint'),
packet_checksums_json=dict(packet_checksums),
stats_json=dict(stats),
security_summary_json=security_summary,
tree_summary_json=sanitize_xfa_dto(tree_summary),
error_code=outcome.error_code,
route_reason=outcome.route_reason,
encrypted_snapshot_ref=None,
parser_identity=XFA_PARSER_IDENTITY,
contract_version=XFA_CONTRACT_VERSION,
finished_at=datetime.utcnow(),
)
db.session.add(record)
db.session.flush()
if status == 'ready':
outcome.snapshot.setdefault('xfa_capability', {})['structure_analysis_id'] = int(record.id)
if isinstance(outcome.snapshot.get('capability'), dict):
outcome.snapshot['capability']['structure_analysis_id'] = int(record.id)
outcome.analysis_record = record
return record
def _failed_snapshot(
*,
document_kind: str,
error_code: str,
route_reason: str,
issues: list[str],
packet_result: XfaPacketReadResult | None = None,
) -> dict[str, Any]:
"""构造 failed 状态的 XFA 布局快照。"""
capability = {
'parser_identity': XFA_PARSER_IDENTITY,
'contract_version': XFA_CONTRACT_VERSION,
'document_kind': document_kind,
'structure_analysis_ready': False,
'xfa_dataset_ready': False,
'has_table_structure': False,
'error_code': error_code,
'route_reason': route_reason,
}
if packet_result is not None:
capability['packet_checksums'] = {item.name: item.checksum for item in packet_result.packets}
return {
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
'provider': 'xfa',
'provider_version': XFA_PARSER_IDENTITY,
'backend': 'xfa_hardened_parser',
'status': 'failed',
'document_kind': document_kind,
'tables': [],
'text_blocks': [],
'xfa_capability': capability,
'capability': capability,
'issues': sorted(set(issues)),
}
def _unsupported_snapshot(packet_result: XfaPacketReadResult) -> dict[str, Any]:
"""构造 unsupported 状态的 XFA 布局快照。"""
return {
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
'provider': 'xfa',
'provider_version': XFA_PARSER_IDENTITY,
'backend': 'xfa_hardened_parser',
'status': 'unsupported',
'document_kind': packet_result.document_kind,
'tables': [],
'text_blocks': [],
'xfa_capability': {
'parser_identity': XFA_PARSER_IDENTITY,
'document_kind': packet_result.document_kind,
'structure_analysis_ready': False,
'packet_checksums': {item.name: item.checksum for item in packet_result.packets},
},
'capability': {
'document_kind': packet_result.document_kind,
'structure_analysis_ready': False,
'has_table_structure': False,
},
'issues': sorted({'xfa_unsupported_document'}),
}
def project_field_tree(analysis: ShippingXfaStructureAnalysis, *, include_values: bool = False) -> dict[str, Any]:
"""
从持久化分析记录投影字段树 DTO(不含 XML 明文路径)。
Args:
analysis: 结构分析记录。
include_values: 是否包含脱敏样本值。
Returns:
安全字段树摘要。
"""
# tree_summary 存的是候选摘要;完整树在 analyze 时重建需 layout job 再解析或存结构 JSON。
# 阶段 1:从 tree_summary_json 返回已脱敏的节点摘要。
summary = analysis.tree_summary_json if isinstance(analysis.tree_summary_json, dict) else {}
return sanitize_xfa_dto({
'analysis_id': analysis.id,
'document_kind': analysis.document_kind,
'dataset_root_path_hash': analysis.dataset_structure_fingerprint,
'header_candidates': summary.get('header_candidates') or [],
'known_path_ids': summary.get('known_path_ids') or [],
'stats': analysis.stats_json or {},
})
def get_latest_analysis_for_document(document_id: int) -> ShippingXfaStructureAnalysis | None:
"""
读取文档最近一次成功的 XFA 结构分析。
Args:
document_id: ShippingOrderDocument 主键。
Returns:
分析记录或 None。
"""
return (
ShippingXfaStructureAnalysis.query.filter_by(document_id=int(document_id))
.order_by(ShippingXfaStructureAnalysis.id.desc())
.first()
)
def rebuild_tree_dto_from_analysis(
analysis: ShippingXfaStructureAnalysis,
pdf_bytes: bytes,
*,
include_values: bool = False,
) -> dict[str, Any]:
"""
按需从 PDF 重建字段树 DTO(管理员 API 用,不持久化 XML)。
Args:
analysis: 已有结构分析记录。
pdf_bytes: 原始 PDF 字节。
include_values: 是否包含脱敏值。
Returns:
字段树 DTO。
"""
outcome = analyze_xfa_pdf(pdf_bytes)
if outcome.dataset_analysis is None:
return project_field_tree(analysis, include_values=include_values)
root = outcome.dataset_analysis.nodes[0] if outcome.dataset_analysis.nodes else None
tree = serialize_tree_node(root, include_values=include_values) if root else {}
return sanitize_xfa_dto({
'analysis_id': analysis.id,
'document_kind': analysis.document_kind,
'dataset_structure_fingerprint': analysis.dataset_structure_fingerprint,
'tree': tree,
'header_candidates': outcome.dataset_analysis.header_candidates,
'stats': outcome.dataset_analysis.stats,
})
@@ -0,0 +1,733 @@
"""
services/shipping_notice/document_layout/xfa_contract.py
用途:冻结 XFA 数据路径 Profile 的阶段 0 契约——template_mode、受控路径语法、
结构指纹算法、资源上限、支持/拒绝矩阵、鉴别联合 definition、evidence 与安全投影。
依赖:Pydantic 2、标准库 hashlib/json/re/unicodedata;被 order_extraction_route_contract、
error_explainability_contract、Profile 校验与后续 xfa_*.py 解析器引用。
逻辑:本模块只定义契约与纯函数校验,不读 PDF/XML、不执行脚本、不接正式流量;
coordinate 行为保持不变,xfa_dataset 定义不得混入坐标 region。
"""
from __future__ import annotations
import hashlib
import json
import re
import unicodedata
from typing import Any, Final, Literal
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
# ---------------------------------------------------------------------------
# 契约版本与模式
# ---------------------------------------------------------------------------
XFA_CONTRACT_VERSION: Final[str] = 'shipping-xfa-dataset-contract.v1'
XFA_PARSER_IDENTITY: Final[str] = 'shipping-xfa-hardened-parser.v1'
XFA_STRUCTURE_FINGERPRINT_VERSION: Final[str] = 'xfa-dataset-structure-fingerprint.v1'
XFA_STRUCTURE_SIGNATURE_ID: Final[str] = 'xfa-structure-signature.v1'
# 盲测/正式提取共用的文档级 table_id 占位;XFA 无物理表格。
XFA_DOCUMENT_TABLE_ID: Final[str] = 'xfa-authoritative-lines'
OrderProfileTemplateMode = Literal['coordinate', 'xfa_dataset']
ORDER_PROFILE_TEMPLATE_MODES: Final[frozenset[str]] = frozenset({
'coordinate',
'xfa_dataset',
})
XfaDocumentKind = Literal[
'plain_pdf',
'acroform',
'xfa_hybrid',
'pure_xfa',
'unsupported',
]
XFA_DOCUMENT_KINDS: Final[frozenset[str]] = frozenset({
'plain_pdf',
'acroform',
'xfa_hybrid',
'pure_xfa',
'unsupported',
})
# 第一版正式支持:datasets 已含最终业务值的混合型 XFA。
XFA_SUPPORTED_DOCUMENT_KINDS: Final[frozenset[str]] = frozenset({
'xfa_hybrid',
})
XFA_REJECTED_CAPABILITIES: Final[frozenset[str]] = frozenset({
'execute_javascript',
'execute_formcalc',
'external_data_connection',
'network_fetch',
'fuzzy_template_match',
'auto_merge_line_collections',
'ocr_fallback',
'vlm_fallback',
'blank_page_coordinate_evidence',
'flatten_legal_equivalent_pdf',
})
XfaEvidenceSource = Literal['xfa_dataset']
XFA_EVIDENCE_SOURCES: Final[frozenset[str]] = frozenset({'xfa_dataset'})
XfaCrossCheckStatus = Literal[
'matched',
'partial',
'mismatched',
'skipped',
'unavailable',
'failed',
]
XFA_CROSS_CHECK_STATUSES: Final[frozenset[str]] = frozenset({
'matched',
'partial',
'mismatched',
'skipped',
'unavailable',
'failed',
})
# 自动建单 CQ 仅接受可证明完整性的对账状态(不含 partial/unavailable)。
XFA_CROSS_CHECK_AUTO_CREATE_OK_STATUSES: Final[frozenset[str]] = frozenset({
'matched',
'passed',
'skipped',
})
XfaMirrorCollectionPolicy = Literal['must_match_when_present', 'ignore']
XFA_MIRROR_COLLECTION_POLICIES: Final[frozenset[str]] = frozenset({
'must_match_when_present',
'ignore',
})
XfaLineAmountFormula = Literal['quantity_times_unit_price', 'disabled']
XfaTotalAmountPolicy = Literal['must_equal_line_sum', 'disabled']
# ---------------------------------------------------------------------------
# 资源上限(与验收/实施方案一致;后续可由 settings 覆盖,但契约默认值冻结)
# ---------------------------------------------------------------------------
XFA_DEFAULT_MAX_PDF_BYTES: Final[int] = 20 * 1024 * 1024
XFA_DEFAULT_MAX_PACKET_BYTES: Final[int] = 10 * 1024 * 1024
XFA_DEFAULT_MAX_XML_DEPTH: Final[int] = 64
XFA_DEFAULT_MAX_XML_NODES: Final[int] = 100_000
XFA_DEFAULT_MAX_LINE_ROWS: Final[int] = 2_000
XFA_DEFAULT_PARSE_TIMEOUT_SECONDS: Final[int] = 30
XFA_DEFAULT_MAX_RETRIES: Final[int] = 2
# ---------------------------------------------------------------------------
# 稳定错误码 / 路由原因码(阶段 0 冻结;后续只追加不改语义)
# ---------------------------------------------------------------------------
XFA_ERROR_CODES: Final[frozenset[str]] = frozenset({
'XFA_DATASET_MISSING',
'XFA_UNSAFE_XML',
'XFA_PACKET_TOO_LARGE',
'XFA_XML_DEPTH_EXCEEDED',
'XFA_XML_NODE_LIMIT_EXCEEDED',
'XFA_LINE_ROW_LIMIT_EXCEEDED',
'XFA_PARSE_TIMEOUT',
'XFA_UNSUPPORTED_DOCUMENT',
'XFA_PROFILE_NOT_MATCHED',
'XFA_PROFILE_AMBIGUOUS',
'XFA_REQUIRED_FIELD_MISSING',
'XFA_MIRROR_COLLECTION_MISMATCH',
'XFA_ACROFORM_MISMATCH',
'XFA_BUSINESS_VALIDATION_FAILED',
'XFA_AUTHORITATIVE_COLLECTION_MISSING',
'XFA_PATH_INVALID',
'XFA_PATH_UNKNOWN',
'XFA_DEFINITION_INVALID',
'XFA_SPLIT_RULE_INVALID',
'XFA_SPLIT_FIELD_CONFLICT',
'XFA_SPLIT_MIRROR_MISMATCH',
})
XFA_ROUTE_REASON_CODES: Final[frozenset[str]] = frozenset({
'xfa_dataset_missing',
'xfa_unsafe_xml',
'xfa_packet_too_large',
'xfa_xml_depth_exceeded',
'xfa_xml_node_limit_exceeded',
'xfa_line_row_limit_exceeded',
'xfa_parse_timeout',
'xfa_unsupported_document',
'xfa_profile_not_matched',
'xfa_profile_ambiguous',
'xfa_required_field_missing',
'xfa_mirror_collection_mismatch',
'xfa_acroform_mismatch',
'xfa_business_validation_failed',
'xfa_authoritative_collection_missing',
'xfa_path_invalid',
'xfa_path_unknown',
'xfa_definition_invalid',
'xfa_structure_identity_changed',
'xfa_split_rule_invalid',
'xfa_split_field_conflict',
'xfa_split_mirror_mismatch',
})
XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
'xfa_sample_uploaded',
'xfa_parse_started',
'xfa_parse_completed',
'xfa_parse_failed',
'xfa_parse_rejected_unsafe',
'xfa_document_kind_detected',
'xfa_packet_parsed',
'xfa_structure_analysis_ready',
'xfa_field_tree_accessed',
'xfa_collections_accessed',
'xfa_sensitive_sample_value_read',
'xfa_draft_created',
'xfa_mapping_saved',
'xfa_authoritative_collection_selected',
'xfa_normalizer_changed',
'xfa_profile_matched',
'xfa_profile_not_matched',
'xfa_profile_ambiguous',
'xfa_extraction_completed',
'xfa_extraction_failed',
'xfa_cross_check_completed',
'xfa_structure_signature_frozen',
'xfa_audit_snapshot_viewed',
# 字段拆分映射审计(阶段 3/7)
'xfa_split_rule_suggested',
'xfa_split_rule_previewed',
'xfa_split_rule_validated',
'xfa_split_segment_created',
'xfa_split_segment_updated',
'xfa_split_segment_deleted',
'xfa_segment_mapping_updated',
'xfa_profile_draft_saved',
'xfa_profile_validation_executed',
'blind_test_executed',
'blind_test_approved',
'xfa_profile_published',
'xfa_profile_formal_extracted',
'xfa_profile_needs_review',
})
# Profile / Run / 分析 DTO 禁止键(大小写不敏感);完整 XML / PDF bytes / 存储地址不得外泄。
XFA_DTO_FORBIDDEN_KEYS: Final[frozenset[str]] = frozenset({
'xml',
'raw_xml',
'xfa_xml',
'datasets_xml',
'packet_bytes',
'pdf_bytes',
'file_bytes',
'object_key',
'object_url',
'minio',
'storage_url',
'presigned_url',
'api_key',
'secret',
'password',
'authorization',
'credential',
'audit_snapshot_key',
'raw_value', # 普通 DTO 仅允许脱敏预览或 encrypted ref
'full_xml_path', # 普通用户 DTO 不返回明文路径;管理员敏感读另走受控 API
})
# ---------------------------------------------------------------------------
# 受控数据路径语法
# ---------------------------------------------------------------------------
# 路径形态:/localName[/localName...];禁止通配、函数、父级逃逸、属性谓词与脚本。
_XFA_PATH_SEGMENT_RE = re.compile(r'^[A-Za-z_][A-Za-z0-9_.-]*$')
_XFA_FORBIDDEN_PATH_SUBSTRINGS = (
'*',
'//',
'..',
'(',
')',
'[',
']',
'@',
'=',
'|',
'::',
)
_XFA_FORBIDDEN_PATH_SEGMENTS = frozenset({
'script',
'javascript',
'formcalc',
})
class XfaContractModel(BaseModel):
"""XFA 契约模型基类:禁止额外字段,赋值时再次校验。"""
model_config = ConfigDict(extra='forbid', validate_assignment=True)
class XfaSourceContract(XfaContractModel):
"""冻结 XFA 模板结构身份:packet checksum + 结构指纹 + 权威集合路径。"""
template_packet_checksum: str = Field(min_length=16, max_length=128)
dataset_structure_fingerprint: str = Field(min_length=16, max_length=128)
dataset_root_path: str = Field(min_length=1, max_length=512)
authoritative_line_collection_path: str = Field(min_length=1, max_length=512)
mirror_collection_paths: list[str] = Field(default_factory=list)
@field_validator(
'dataset_root_path',
'authoritative_line_collection_path',
mode='before',
)
@classmethod
def validate_required_paths(cls, value: Any) -> str:
"""校验必填受控路径语法。"""
return validate_controlled_data_path(value)
@field_validator('mirror_collection_paths', mode='before')
@classmethod
def validate_mirror_paths(cls, value: Any) -> list[str]:
"""校验镜像集合路径列表;允许空列表。"""
items = list(value or [])
return [validate_controlled_data_path(item) for item in items]
class XfaHeaderMapping(XfaContractModel):
"""Header 字段:Schema field ↔ 受控 datasets 路径。"""
mapping_id: str = Field(min_length=1, max_length=64)
field_id: str = Field(min_length=1, max_length=64)
field_code: str = Field(min_length=1, max_length=128)
data_path: str = Field(min_length=1, max_length=512)
path_id: str = Field(min_length=1, max_length=128)
value_type: str = Field(min_length=1, max_length=64)
normalizer_key: str | None = Field(default=None, max_length=64)
validator_key: str | None = Field(default=None, max_length=64)
@field_validator('data_path', mode='before')
@classmethod
def validate_data_path(cls, value: Any) -> str:
"""Header 映射路径必须通过受控语法。"""
return validate_controlled_data_path(value)
class XfaLineFieldMapping(XfaContractModel):
"""明细行字段映射。"""
mapping_id: str = Field(min_length=1, max_length=64)
field_id: str = Field(min_length=1, max_length=64)
field_code: str = Field(min_length=1, max_length=128)
data_path: str = Field(min_length=1, max_length=512)
path_id: str = Field(min_length=1, max_length=128)
value_type: str = Field(min_length=1, max_length=64)
normalizer_key: str | None = Field(default=None, max_length=64)
validator_key: str | None = Field(default=None, max_length=64)
@field_validator('data_path', mode='before')
@classmethod
def validate_data_path(cls, value: Any) -> str:
"""明细映射路径必须通过受控语法。"""
return validate_controlled_data_path(value)
class XfaLineMapping(XfaContractModel):
"""权威明细集合路径及行内字段映射。"""
row_path: str = Field(min_length=1, max_length=512)
fields: list[XfaLineFieldMapping] = Field(default_factory=list)
@field_validator('row_path', mode='before')
@classmethod
def validate_row_path(cls, value: Any) -> str:
"""行集合路径必须通过受控语法。"""
return validate_controlled_data_path(value)
class XfaCrossChecks(XfaContractModel):
"""对账与业务恒等式策略。"""
acroform_enabled: bool = True
mirror_collection_policy: XfaMirrorCollectionPolicy = 'must_match_when_present'
line_amount_formula: XfaLineAmountFormula = 'quantity_times_unit_price'
total_amount_policy: XfaTotalAmountPolicy = 'must_equal_line_sum'
class OrderXfaDatasetProfile(XfaContractModel):
"""
xfa_dataset 模式的鉴别联合 definition。
核心逻辑:仅允许 XFA 映射字段;显式拒绝 coordinate 的 table_regions /
order_field_layouts 等键混入;可选 split_rules 声明式多行拆分。
"""
template_mode: Literal['xfa_dataset'] = 'xfa_dataset'
source_contract: XfaSourceContract
header_mappings: list[XfaHeaderMapping] = Field(default_factory=list)
line_mapping: XfaLineMapping
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。"""
if not isinstance(data, dict):
return data
forbidden = {
'table_regions',
'order_field_layouts',
'draft_unbound_order_field_layouts',
'document_match',
'structure_fingerprint',
'column_rules',
'row_structure',
'coordinate_reconstruction',
}
present = sorted(key for key in forbidden if key in data)
if present:
raise ValueError(
f'xfa_dataset definition must not mix coordinate keys: {", ".join(present)}',
)
mode = str(data.get('template_mode') or 'xfa_dataset').strip()
if mode != 'xfa_dataset':
raise ValueError('OrderXfaDatasetProfile requires template_mode=xfa_dataset')
return data
@model_validator(mode='after')
def validate_unique_bindings(self) -> 'OrderXfaDatasetProfile':
"""同一 Schema 字段与同一 mapping_id 不得重复绑定;校验 split_rules 契约。"""
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
parse_split_rule_sets,
)
field_ids: list[str] = []
mapping_ids: list[str] = []
for item in self.header_mappings:
field_ids.append(item.field_id)
mapping_ids.append(item.mapping_id)
for item in self.line_mapping.fields:
field_ids.append(item.field_id)
mapping_ids.append(item.mapping_id)
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)
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',
[item.model_dump(mode='json') for item in rule_sets],
)
return self
class XfaFieldEvidenceRef(XfaContractModel):
"""字段证据引用:普通 DTO 仅含哈希与标准化值,不含明文路径与原始 XML。"""
source: XfaEvidenceSource = 'xfa_dataset'
document_id: int = Field(ge=1)
packet_checksum: str = Field(min_length=16, max_length=128)
data_path_hash: str = Field(min_length=16, max_length=128)
mapping_id: str = Field(min_length=1, max_length=64)
raw_value_snapshot_ref: str | None = Field(default=None, max_length=256)
normalized_value: str | None = None
normalizer_key: str | None = Field(default=None, max_length=64)
cross_check_status: XfaCrossCheckStatus = 'unavailable'
class XfaStructureNodeSpec(XfaContractModel):
"""结构指纹输入节点:只含名称/层级/基数/命名空间,不含业务值。"""
local_name: str = Field(min_length=1, max_length=256)
namespace_uri: str = ''
depth: int = Field(ge=0, le=XFA_DEFAULT_MAX_XML_DEPTH)
cardinality: Literal['one', 'many'] = 'one'
children: list['XfaStructureNodeSpec'] = Field(default_factory=list)
XfaStructureNodeSpec.model_rebuild()
def normalize_template_mode(value: Any) -> OrderProfileTemplateMode:
"""
将输入规范化为合法 template_mode。
Args:
value: 原始模式字符串。
Returns:
coordinate | xfa_dataset。
Raises:
ValueError: 非法或不支持的模式。
"""
mode = str(value or '').strip()
if mode not in ORDER_PROFILE_TEMPLATE_MODES:
raise ValueError(
f'template_mode must be one of {sorted(ORDER_PROFILE_TEMPLATE_MODES)}; got {mode!r}',
)
return mode # type: ignore[return-value]
def validate_controlled_data_path(value: Any) -> str:
"""
校验受控数据路径语法。
核心逻辑:仅允许以 `/` 分段的 localName 路径;拒绝通配符、函数调用、
父级逃逸、属性谓词、命名空间轴与脚本关键字。
Args:
value: 候选路径字符串。
Returns:
规范化后的绝对路径(保留段名大小写)。
Raises:
ValueError: 路径语法非法。
"""
path = str(value or '').strip()
if not path:
raise ValueError('data path is required')
lowered = path.lower()
for token in _XFA_FORBIDDEN_PATH_SUBSTRINGS:
if token in path or token in lowered:
raise ValueError(f'data path contains forbidden token: {token}')
if not path.startswith('/'):
raise ValueError('data path must be absolute and start with /')
if path != '/' and path.endswith('/'):
raise ValueError('data path must not end with /')
segments = [part for part in path.split('/') if part != '']
if not segments:
raise ValueError('data path must contain at least one segment')
for segment in segments:
if segment.lower() in _XFA_FORBIDDEN_PATH_SEGMENTS:
raise ValueError(f'data path contains forbidden segment: {segment}')
if not _XFA_PATH_SEGMENT_RE.fullmatch(segment):
raise ValueError(f'invalid data path segment: {segment!r}')
return '/' + '/'.join(segments)
def assert_path_id_known(path_id: str, known_path_ids: set[str] | frozenset[str]) -> str:
"""
断言 path_id 属于当前结构分析记录中的已知集合。
Args:
path_id: 映射保存的路径身份。
known_path_ids: 分析记录产生的合法 path ID 集合。
Returns:
原 path_id。
Raises:
ValueError: path_id 未知。
"""
normalized = str(path_id or '').strip()
if not normalized:
raise ValueError('path_id is required')
if normalized not in known_path_ids:
raise ValueError(f'unknown path_id: {normalized}')
return normalized
def hash_data_path(path: str) -> str:
"""
对受控路径计算稳定 SHA-256(带 sha256: 前缀),供 evidence 与审计脱敏使用。
Args:
path: 已通过语法校验的数据路径。
Returns:
`sha256:<hex>` 字符串。
"""
validated = validate_controlled_data_path(path)
digest = hashlib.sha256(validated.encode('utf-8')).hexdigest()
return f'sha256:{digest}'
def canonical_structure_payload(nodes: list[XfaStructureNodeSpec] | list[dict[str, Any]]) -> dict[str, Any]:
"""
生成结构指纹的 canonical 载荷。
核心逻辑:仅序列化 local_name / namespace_uri / depth / cardinality / children;
不包含订单值、文件名或明细行数量。
Args:
nodes: 结构树根列表(模型或 dict)。
Returns:
可稳定哈希的字典。
"""
validated = [
item if isinstance(item, XfaStructureNodeSpec) else XfaStructureNodeSpec.model_validate(item)
for item in nodes
]
def _dump(node: XfaStructureNodeSpec) -> dict[str, Any]:
return {
'local_name': node.local_name,
'namespace_uri': node.namespace_uri or '',
'depth': node.depth,
'cardinality': node.cardinality,
'children': [_dump(child) for child in node.children],
}
return {
'fingerprint_version': XFA_STRUCTURE_FINGERPRINT_VERSION,
'roots': [_dump(node) for node in validated],
}
def compute_dataset_structure_fingerprint(
nodes: list[XfaStructureNodeSpec] | list[dict[str, Any]],
) -> str:
"""
计算 dataset 结构指纹。
Args:
nodes: 不含业务值的结构树。
Returns:
`sha256:<hex>` 指纹。
"""
payload = canonical_structure_payload(nodes)
raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
return f'sha256:{hashlib.sha256(raw.encode("utf-8")).hexdigest()}'
def validate_xfa_dataset_definition(payload: dict[str, Any] | OrderXfaDatasetProfile) -> OrderXfaDatasetProfile:
"""
将字典校验为 OrderXfaDatasetProfile。
Args:
payload: 原始 definition 或已构造模型。
Returns:
通过鉴别联合与路径语法校验的模型。
Raises:
pydantic.ValidationError / ValueError: 契约不合法。
"""
if isinstance(payload, OrderXfaDatasetProfile):
return OrderXfaDatasetProfile.model_validate(payload.model_dump(mode='json'))
return OrderXfaDatasetProfile.model_validate(payload)
def sanitize_xfa_dto(payload: dict[str, Any] | None) -> dict[str, Any]:
"""
递归剥离 Profile/Run/分析 DTO 中的禁止键。
核心逻辑:键名大小写不敏感匹配 XFA_DTO_FORBIDDEN_KEYS;用于阶段 0 契约测试
与后续 API 投影共用。
Args:
payload: 候选字典。
Returns:
脱敏后的浅拷贝字典。
"""
if not isinstance(payload, dict):
return {}
forbidden = {key.lower() for key in XFA_DTO_FORBIDDEN_KEYS}
def _walk(value: Any) -> Any:
if isinstance(value, dict):
cleaned: dict[str, Any] = {}
for key, item in value.items():
if str(key).lower() in forbidden:
continue
cleaned[str(key)] = _walk(item)
return cleaned
if isinstance(value, list):
return [_walk(item) for item in value]
return value
return _walk(payload)
_XFA_FULL_DISPLAY_FIELD_NAMES: Final[frozenset[str]] = frozenset({
'AMOUNT', 'BEDAT', 'COUNTRY', 'EBELP', 'EINDT', 'INCO1', 'INCO2',
'MEINS', 'MENGE', 'NETPR', 'PEINH', 'POST_CODE1', 'TOTAL_AMOUNT',
'WAERS', 'WERKS', 'ZTERM',
})
_XFA_RESTRICTED_FIELD_TOKENS: Final[tuple[str, ...]] = (
'ADDRESS', 'CITY', 'FAX', 'HOUSE', 'INSTRUCTION', 'INSPECTION', 'NAME',
'PHONE', 'REMARK', 'SPECIFICATION', 'STRAS', 'STREET', 'TEL', 'VENDOR',
)
def mask_sample_value(value: Any, *, keep_head: int = 4, keep_tail: int = 3) -> str:
"""
对样本原值做默认脱敏展示。
Args:
value: 原始业务值。
keep_head: 保留前缀字符数。
keep_tail: 保留后缀字符数。
Returns:
脱敏字符串;短值整体替换为 `***`。
"""
text = unicodedata.normalize('NFKC', str(value or '')).strip()
if not text:
return ''
if len(text) <= keep_head + keep_tail:
return '***'
return f'{text[:keep_head]}{"•" * 3}{text[-keep_tail:]}'
def xfa_mapping_sample_display(field_name: str, value: Any) -> dict[str, Any]:
"""
为 XFA 映射工作台生成可辨识且分级受控的样本展示。
核心逻辑:业务代码、日期、数量、金额与单位完整展示;订单/物料等标识符保留
足够前后缀;名称、地址、电话和自由文本默认限制展示并允许授权后临时展开。
Args:
field_name: XML 叶子节点 localName。
value: datasets 原始业务值。
Returns:
display_value、display_policy 与 can_reveal 组成的安全展示字典。
"""
text = unicodedata.normalize('NFKC', str(value or '')).strip()
name = unicodedata.normalize('NFKC', str(field_name or '')).strip().upper()
if not text:
return {'display_value': '', 'display_policy': 'empty', 'can_reveal': False}
if name in _XFA_FULL_DISPLAY_FIELD_NAMES:
return {'display_value': text, 'display_policy': 'full', 'can_reveal': False}
if any(token in name for token in _XFA_RESTRICTED_FIELD_TOKENS):
if len(text) <= 4:
display = f'{text[:1]}•••'
else:
display = f'{text[: min(8, max(2, len(text) // 3))]}•••'
return {'display_value': display, 'display_policy': 'restricted', 'can_reveal': True}
# 标识符需要足以区分字段和值;短标识不再整体压成无法判断语义的 ***。
if len(text) <= 4:
display = text
elif len(text) <= 8:
display = f'{text[:2]}••{text[-2:]}'
else:
head = min(16, max(4, len(text) // 2))
display = f'{text[:head]}…{text[-3:]}'
return {'display_value': display, 'display_policy': 'partial', 'can_reveal': True}
def default_xfa_resource_limits() -> dict[str, int]:
"""返回阶段 0 冻结的默认资源上限字典。"""
return {
'max_pdf_bytes': XFA_DEFAULT_MAX_PDF_BYTES,
'max_packet_bytes': XFA_DEFAULT_MAX_PACKET_BYTES,
'max_xml_depth': XFA_DEFAULT_MAX_XML_DEPTH,
'max_xml_nodes': XFA_DEFAULT_MAX_XML_NODES,
'max_line_rows': XFA_DEFAULT_MAX_LINE_ROWS,
'parse_timeout_seconds': XFA_DEFAULT_PARSE_TIMEOUT_SECONDS,
'max_retries': XFA_DEFAULT_MAX_RETRIES,
}
@@ -0,0 +1,605 @@
"""
backend/app/services/shipping_notice/document_layout/xfa_dataset.py
用途: hardened 解析 XFA datasets XML,构建受控路径树并识别 Header/集合候选;
提供单叶子与权威集合行读取供正式提取使用;叶子保留 raw/normalized/lines
三层中间表示,供字段拆分规则引擎消费。
依赖:lxml、xfa_contract(路径语法/指纹/脱敏)、xfa_packets.preflight_xml_bytes。
逻辑:由 xfa_analysis、xfa_profile_extraction 与 admin XFA API 调用;
只读内存 XML,不联网、不执行脚本;raw_value/lines 仅存内存树,不进入普通 DTO。
"""
from __future__ import annotations
import hashlib
import re
from dataclasses import dataclass, field
from typing import Any, Literal
from lxml import etree
from app.services.shipping_notice.document_layout.xfa_contract import (
XFA_DEFAULT_MAX_LINE_ROWS,
XFA_DEFAULT_MAX_XML_DEPTH,
XFA_DEFAULT_MAX_XML_NODES,
hash_data_path,
mask_sample_value,
xfa_mapping_sample_display,
validate_controlled_data_path,
)
from app.services.shipping_notice.document_layout.xfa_packets import XfaPacketError, preflight_xml_bytes
_CARDINALITY = Literal['one', 'many']
@dataclass
class XfaLeafValue:
"""
叶子业务值的三层中间表示(阶段 1:字段拆分前置)。
raw_value:保留原始换行(统一为 \\n);
normalized_value:空白折叠,供搜索/比较;
lines:按换行切分后的行列表(含空行,规则引擎再按 normalization 过滤)。
"""
raw_value: str
normalized_value: str
lines: list[str]
@dataclass
class XfaDatasetNode:
"""受控路径树节点。"""
path_id: str
local_name: str
namespace_uri: str
data_path: str
depth: int
cardinality: _CARDINALITY
is_leaf: bool
is_header_candidate: bool = False
is_collection_candidate: bool = False
sample_value_masked: str | None = None
sample_value_display: str | None = None
display_policy: str = 'empty'
can_reveal: bool = False
# 仅内存内部使用;serialize_tree_node / 普通 DTO 不得外泄原文。
raw_value: str | None = None
normalized_value: str | None = None
lines: list[str] = field(default_factory=list)
children: list['XfaDatasetNode'] = field(default_factory=list)
@dataclass
class XfaCollectionCandidate:
"""重复明细集合候选。"""
collection_path: str
path_id: str
row_count: int
sibling_collection_paths: list[str] = field(default_factory=list)
@dataclass
class XfaDatasetAnalysis:
"""datasets 结构分析结果。"""
dataset_root_path: str
nodes: list[XfaDatasetNode]
header_candidates: list[dict[str, Any]]
collection_candidates: list[XfaCollectionCandidate]
stats: dict[str, Any]
leaf_values_by_path: dict[str, str]
known_path_ids: set[str]
class XfaDatasetParseError(XfaPacketError):
"""datasets 解析失败。"""
def _local_name(tag: str) -> str:
"""提取 XML localName,忽略命名空间前缀。"""
return str(tag or '').rsplit('}', 1)[-1]
def _namespace_uri(tag: str) -> str:
"""提取命名空间 URI。"""
text = str(tag or '')
if text.startswith('{') and '}' in text:
return text[1:text.index('}')]
return ''
def _normalize_leaf_text(value: str) -> str:
"""
将叶子文本折叠为单行规范化串(搜索/比较用)。
注意:不得用于正式拆分输入;拆分必须使用保留换行的 raw_value / lines。
"""
return re.sub(r'\s+', ' ', str(value or '')).strip()
def build_xfa_leaf_value(text: str) -> XfaLeafValue:
"""
从 XML 叶子原文构建三层中间表示。
核心逻辑:统一 \\r\\n/\\r 为 \\n 且保留行结构;去掉整段首尾换行(pretty-print);
normalized 折叠空白;lines 按 \\n 切分(含空行,供 position matcher 使用)。
Args:
text: element.itertext() 拼接后的原文。
Returns:
XfaLeafValue。
"""
raw = str(text or '').replace('\r\n', '\n').replace('\r', '\n').strip('\n')
lines = raw.split('\n') if raw != '' else []
return XfaLeafValue(
raw_value=raw,
normalized_value=_normalize_leaf_text(raw),
lines=lines,
)
def _path_id_for(data_path: str) -> str:
"""为受控路径生成稳定 path_id。"""
digest = hashlib.sha256(data_path.encode('utf-8')).hexdigest()[:16]
return f'path-{digest}'
def _hardened_parser() -> etree.XMLParser:
"""构造禁用外部实体与 DTD 的 lxml 解析器。"""
return etree.XMLParser(
resolve_entities=False,
load_dtd=False,
no_network=True,
huge_tree=False,
)
def _iter_element_nodes(root: etree._Element) -> list[tuple[etree._Element, int]]:
"""
深度优先遍历元素节点并附带深度。
Args:
root: XML 根元素。
Returns:
(element, depth) 列表;depth 从 1 开始。
"""
result: list[tuple[etree._Element, int]] = []
def _walk(node: etree._Element, depth: int) -> None:
result.append((node, depth))
for child in node:
if isinstance(child.tag, str):
_walk(child, depth + 1)
_walk(root, 1)
return result
def _detect_cardinality(element: etree._Element) -> _CARDINALITY:
"""
根据同级重复 localName 判断基数。
核心逻辑:DATA 行容器在结构层始终视为 many,使明细行数量变化不影响指纹。
"""
local = _local_name(element.tag)
if local.upper() == 'DATA':
return 'many'
if element.getparent() is None:
return 'one'
siblings = [
_local_name(item.tag)
for item in element.getparent()
if isinstance(item.tag, str)
]
return 'many' if siblings.count(local) > 1 else 'one'
def _build_tree(
element: etree._Element,
*,
parent_path: str,
depth: int,
limits: dict[str, int],
counters: dict[str, int],
leaf_values: dict[str, str],
) -> XfaDatasetNode:
"""
递归构建受控路径树。
Args:
element: 当前 XML 元素。
parent_path: 父级受控路径。
depth: 当前深度。
limits: 资源上限。
counters: 可变计数器(node_count、max_depth、line_rows)。
leaf_values: 输出叶子原值映射(仅内部使用,不外泄)。
Returns:
XfaDatasetNode 子树。
Raises:
XfaDatasetParseError: 深度/节点/行数超限。
"""
local = _local_name(element.tag)
data_path = validate_controlled_data_path(f'{parent_path}/{local}' if parent_path else f'/{local}')
counters['node_count'] = int(counters.get('node_count', 0)) + 1
counters['max_depth'] = max(int(counters.get('max_depth', 0)), depth)
if counters['node_count'] > limits['max_xml_nodes']:
raise XfaDatasetParseError(
error_code='XFA_XML_NODE_LIMIT_EXCEEDED',
route_reason='xfa_xml_node_limit_exceeded',
)
if depth > limits['max_xml_depth']:
raise XfaDatasetParseError(
error_code='XFA_XML_DEPTH_EXCEEDED',
route_reason='xfa_xml_depth_exceeded',
)
element_children = [child for child in element if isinstance(child.tag, str)]
is_leaf = not element_children
cardinality = _detect_cardinality(element)
masked_value: str | None = None
raw_value: str | None = None
normalized_value: str | None = None
lines: list[str] = []
if is_leaf:
leaf = build_xfa_leaf_value(''.join(element.itertext()))
leaf_values[data_path] = leaf.raw_value
raw_value = leaf.raw_value
normalized_value = leaf.normalized_value
lines = list(leaf.lines)
masked_value = mask_sample_value(leaf.normalized_value) if leaf.normalized_value else ''
display = xfa_mapping_sample_display(local, leaf.normalized_value)
else:
display = {'display_value': '', 'display_policy': 'empty', 'can_reveal': False}
child_nodes: list[XfaDatasetNode] = []
for child in element_children:
child_nodes.append(
_build_tree(
child,
parent_path=data_path,
depth=depth + 1,
limits=limits,
counters=counters,
leaf_values=leaf_values,
),
)
return XfaDatasetNode(
path_id=_path_id_for(data_path),
local_name=local,
namespace_uri=_namespace_uri(element.tag),
data_path=data_path,
depth=depth,
cardinality=cardinality,
is_leaf=is_leaf,
sample_value_masked=masked_value,
sample_value_display=str(display['display_value']),
display_policy=str(display['display_policy']),
can_reveal=bool(display['can_reveal']),
raw_value=raw_value,
normalized_value=normalized_value,
lines=lines,
children=child_nodes,
)
def _mark_header_candidates(root: XfaDatasetNode) -> list[dict[str, Any]]:
"""
识别 Header 候选:位于 HEADER 子树下的叶子节点。
Args:
root: 数据集根节点。
Returns:
Header 候选摘要列表。
"""
candidates: list[dict[str, Any]] = []
def _walk(node: XfaDatasetNode, under_header: bool) -> None:
in_header = under_header or node.local_name.upper() == 'HEADER'
if in_header and node.is_leaf:
node.is_header_candidate = True
candidates.append({
'path_id': node.path_id,
'data_path_hash': hash_data_path(node.data_path),
'local_name': node.local_name,
'value_type': 'string',
'sample_value_masked': node.sample_value_masked or '',
})
for child in node.children:
_walk(child, in_header)
_walk(root, False)
return candidates
def _is_line_row_container(node: XfaDatasetNode) -> bool:
"""判断 DATA 节点是否表现为明细行容器(子节点均为叶子字段)。"""
if node.local_name.upper() != 'DATA':
return False
if not node.children:
return node.is_leaf
return all(child.is_leaf for child in node.children)
def _mark_collection_candidates(
root: XfaDatasetNode,
*,
limits: dict[str, int],
) -> list[XfaCollectionCandidate]:
"""
识别独立重复集合候选,例如 ITEMS/DATA 与 ITEMS1/DATA。
核心逻辑:在每个父节点下查找 DATA 行容器;同一父下多行 DATA 只登记一次候选,
row_count 为行数;ITEMS 与 ITEMS1 视为互不合并的独立集合。
Args:
root: 数据集根节点。
limits: 资源上限(用于行数统计)。
Returns:
集合候选列表。
Raises:
XfaDatasetParseError: 明细行数超过上限。
"""
candidates: list[XfaCollectionCandidate] = []
total_line_rows = 0
def _walk(node: XfaDatasetNode) -> None:
nonlocal total_line_rows
data_children = [child for child in node.children if _is_line_row_container(child)]
if data_children:
sibling_paths = [item.data_path for item in data_children]
total_line_rows += len(data_children)
if total_line_rows > limits['max_line_rows']:
raise XfaDatasetParseError(
error_code='XFA_LINE_ROW_LIMIT_EXCEEDED',
route_reason='xfa_line_row_limit_exceeded',
)
# 同一父节点下多行 DATA 共享同一集合路径;候选只登记一次,row_count=行数。
for data_node in data_children:
data_node.is_collection_candidate = True
first = data_children[0]
candidates.append(XfaCollectionCandidate(
collection_path=first.data_path,
path_id=first.path_id,
row_count=len(data_children),
sibling_collection_paths=sibling_paths,
))
for child in node.children:
_walk(child)
_walk(root)
return candidates
def _collect_known_path_ids(node: XfaDatasetNode) -> set[str]:
"""递归收集全部 path_id。"""
ids = {node.path_id}
for child in node.children:
ids.update(_collect_known_path_ids(child))
return ids
def parse_xfa_datasets(
xml_bytes: bytes,
*,
limits: dict[str, int] | None = None,
) -> XfaDatasetAnalysis:
"""
安全解析 XFA datasets XML 并生成结构分析。
Args:
xml_bytes: datasets packet 原始字节。
limits: 可选 max_xml_depth/max_xml_nodes/max_line_rows 覆盖。
Returns:
XfaDatasetAnalysis:含路径树、Header/集合候选与统计。
Raises:
XfaDatasetParseError: 不安全 XML 或资源超限。
"""
resolved = {
'max_xml_depth': XFA_DEFAULT_MAX_XML_DEPTH,
'max_xml_nodes': XFA_DEFAULT_MAX_XML_NODES,
'max_line_rows': XFA_DEFAULT_MAX_LINE_ROWS,
}
if isinstance(limits, dict):
resolved.update({key: int(limits[key]) for key in resolved if key in limits})
try:
preflight_xml_bytes(xml_bytes)
except XfaPacketError as exc:
raise XfaDatasetParseError(
error_code=exc.error_code,
route_reason=exc.route_reason,
message=str(exc),
) from exc
parser = _hardened_parser()
try:
root_element = etree.fromstring(xml_bytes, parser=parser)
except etree.XMLSyntaxError as exc:
raise XfaDatasetParseError(
error_code='XFA_UNSAFE_XML',
route_reason='xfa_unsafe_xml',
message='xml syntax error',
) from exc
counters: dict[str, int] = {'node_count': 0, 'max_depth': 0}
leaf_values: dict[str, str] = {}
dataset_root_path = validate_controlled_data_path(f"/{_local_name(root_element.tag)}")
root_node = _build_tree(
root_element,
parent_path='',
depth=1,
limits=resolved,
counters=counters,
leaf_values=leaf_values,
)
header_candidates = _mark_header_candidates(root_node)
collection_candidates = _mark_collection_candidates(root_node, limits=resolved)
known_path_ids = _collect_known_path_ids(root_node)
stats = {
'node_count': counters['node_count'],
'max_depth': counters['max_depth'],
'leaf_count': len(leaf_values),
'header_candidate_count': len(header_candidates),
'collection_candidate_count': len(collection_candidates),
'line_row_count': sum(item.row_count for item in collection_candidates),
}
return XfaDatasetAnalysis(
dataset_root_path=dataset_root_path,
nodes=[root_node],
header_candidates=header_candidates,
collection_candidates=collection_candidates,
stats=stats,
leaf_values_by_path=leaf_values,
known_path_ids=known_path_ids,
)
def read_dataset_value(analysis: XfaDatasetAnalysis, data_path: str) -> str | None:
"""
按受控路径读取 datasets 叶子原值(保留换行)。
Args:
analysis: 已完成的 datasets 分析。
data_path: 绝对受控路径。
Returns:
叶子 raw_value 或 None(路径不存在/非叶子)。
Raises:
XfaDatasetParseError: 路径语法非法。
"""
leaf = read_dataset_leaf_value(analysis, data_path)
return None if leaf is None else leaf.raw_value
def read_dataset_leaf_value(analysis: XfaDatasetAnalysis, data_path: str) -> XfaLeafValue | None:
"""
按受控路径读取叶子三层中间表示。
核心逻辑:优先从内存树节点取 raw/normalized/lines;若仅有 leaf map 则重建。
Args:
analysis: 已完成的 datasets 分析。
data_path: 绝对受控路径。
Returns:
XfaLeafValue;路径不存在时 None。
Raises:
XfaDatasetParseError: 路径语法非法。
"""
normalized = validate_controlled_data_path(data_path)
for root in analysis.nodes or []:
for node in _iter_nodes(root):
if node.data_path == normalized and node.is_leaf:
return XfaLeafValue(
raw_value=str(node.raw_value or ''),
normalized_value=str(node.normalized_value or ''),
lines=list(node.lines or []),
)
raw = analysis.leaf_values_by_path.get(normalized)
if raw is None:
return None
return build_xfa_leaf_value(raw)
def _iter_nodes(node: XfaDatasetNode) -> list[XfaDatasetNode]:
"""深度优先展开路径树节点。"""
result = [node]
for child in node.children:
result.extend(_iter_nodes(child))
return result
def read_collection_rows(
analysis: XfaDatasetAnalysis,
collection_path: str,
) -> list[dict[str, str]]:
"""
按权威/镜像集合路径读取每一行叶子字段原值。
核心逻辑:查找 data_path 等于集合路径的全部 DATA 行容器;每行以
子叶子的绝对受控路径为键返回原值。同路径多行互不覆盖(与 leaf_values_by_path 不同)。
Args:
analysis: 已完成的 datasets 分析。
collection_path: 权威或镜像集合绝对路径(如 /data/ITEMS/DATA)。
Returns:
行字典列表;集合不存在时返回空列表。
Raises:
XfaDatasetParseError: 路径语法非法。
"""
normalized = validate_controlled_data_path(collection_path)
rows: list[dict[str, str]] = []
roots = list(analysis.nodes or [])
for root in roots:
for node in _iter_nodes(root):
if node.data_path != normalized or not _is_line_row_container(node):
continue
row: dict[str, str] = {}
for child in node.children:
if child.is_leaf:
row[child.data_path] = str(child.raw_value or '')
rows.append(row)
return rows
def serialize_tree_node(node: XfaDatasetNode, *, include_values: bool = False) -> dict[str, Any]:
"""
序列化单个树节点供 API 返回。
Args:
node: 数据集树节点。
include_values: 是否包含脱敏样本值。
Returns:
安全 DTO 字典。
"""
payload: dict[str, Any] = {
'path_id': node.path_id,
'local_name': node.local_name,
'namespace_uri': node.namespace_uri,
'data_path_hash': hash_data_path(node.data_path),
'depth': node.depth,
'cardinality': node.cardinality,
'is_leaf': node.is_leaf,
'is_header_candidate': node.is_header_candidate,
'is_collection_candidate': node.is_collection_candidate,
'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['line_count'] = len(node.lines or [])
return payload
def mask_value_for_dto(value: Any) -> str:
"""
将业务原值转为 DTO 允许返回的脱敏字符串。
Args:
value: 任意原值。
Returns:
脱敏字符串。
"""
return mask_sample_value(value)
@@ -0,0 +1,367 @@
"""
backend/app/services/shipping_notice/document_layout/xfa_packets.py
用途:从 PDF 读取 AcroForm/XFA packet,识别文档类型并返回受控 packet 摘要。
依赖:pypdf、xfa_contract 资源上限与文档类型枚举。
逻辑:由 runtime 与 layout Job 在 MinerU 前调用;只读 packet 字节,不执行脚本、不联网。
"""
from __future__ import annotations
import hashlib
import re
from dataclasses import dataclass, field
from io import BytesIO
from typing import Any, Literal
from pypdf import PdfReader
from pypdf.errors import PdfReadError
from pypdf.generic import ArrayObject, IndirectObject, StreamObject
from app.services.shipping_notice.document_layout.xfa_contract import (
XFA_DEFAULT_MAX_PACKET_BYTES,
XFA_DEFAULT_MAX_PDF_BYTES,
XFA_SUPPORTED_DOCUMENT_KINDS,
XfaDocumentKind,
default_xfa_resource_limits,
)
XFA_PACKET_NAMES = frozenset({
'template',
'datasets',
'config',
'templateCache',
'xfdf',
'xslt',
'pdf',
'form',
})
_UNSAFE_XML_MARKERS = re.compile(
r'<!DOCTYPE|<!ENTITY|&[A-Za-z_][A-Za-z0-9_-]*;|<!ELEMENT|<!ATTLIST',
re.IGNORECASE,
)
@dataclass(frozen=True)
class XfaPacket:
"""单个 XFA packet 的受控摘要;不含持久化所需的完整 XML 外泄面。"""
name: str
byte_length: int
checksum: str
@dataclass
class XfaPacketReadResult:
"""XFA packet 读取结果。"""
document_kind: XfaDocumentKind
packets: list[XfaPacket] = field(default_factory=list)
packet_bytes_by_name: dict[str, bytes] = field(default_factory=dict)
has_acroform: bool = False
has_acroform_fields: bool = False
has_xfa: bool = False
page_count: int = 0
error_code: str | None = None
route_reason: str | None = None
supported: bool = False
class XfaPacketError(Exception):
"""XFA packet 读取阶段的确定性业务失败。"""
def __init__(self, *, error_code: str, route_reason: str, message: str = '') -> None:
super().__init__(message or error_code)
self.error_code = error_code
self.route_reason = route_reason
def compute_packet_checksum(packet_bytes: bytes) -> str:
"""
计算 packet 稳定 SHA-256 校验和。
Args:
packet_bytes: 原始 packet 字节。
Returns:
带 `sha256:` 前缀的十六进制摘要。
"""
return f'sha256:{hashlib.sha256(packet_bytes).hexdigest()}'
def _resolve_limits(limits: dict[str, int] | None) -> dict[str, int]:
"""合并调用方 limits 与契约默认值。"""
merged = default_xfa_resource_limits()
if isinstance(limits, dict):
merged.update({key: int(value) for key, value in limits.items() if key in merged})
return merged
def _stream_bytes(value: Any) -> bytes:
"""从 pypdf StreamObject 或原始 bytes/str 提取 packet 字节。"""
if isinstance(value, bytes):
return value
if isinstance(value, str):
return value.encode('utf-8', errors='ignore')
if isinstance(value, StreamObject):
raw = value.get_data()
return raw if isinstance(raw, bytes) else bytes(raw or b'')
if isinstance(value, IndirectObject):
resolved = value.get_object()
return _stream_bytes(resolved)
return bytes(value or b'')
def _collect_xfa_packets_from_reader(
reader: PdfReader,
*,
max_packet_bytes: int,
) -> tuple[dict[str, bytes], list[XfaPacket], str | None]:
"""
从 PdfReader 提取命名 XFA packet。
核心逻辑:兼容 pypdf 的 reader.xfa 字典与 AcroForm `/XFA` 数组/单流两种容器形态。
Args:
reader: 已打开的 PDF 阅读器。
max_packet_bytes: 单 packet 字节上限。
Returns:
(packet_bytes_by_name, packet_summaries, error_code)。
"""
packet_bytes: dict[str, bytes] = {}
summaries: list[XfaPacket] = []
def _register(name: str, payload: bytes) -> str | None:
normalized_name = str(name or '').strip()
if not normalized_name:
return None
if len(payload) > max_packet_bytes:
return 'XFA_PACKET_TOO_LARGE'
checksum = compute_packet_checksum(payload)
packet_bytes[normalized_name] = payload
summaries.append(XfaPacket(name=normalized_name, byte_length=len(payload), checksum=checksum))
return None
xfa_obj = getattr(reader, 'xfa', None)
xfa_map = xfa_obj if isinstance(xfa_obj, dict) else getattr(xfa_obj, 'xfa', None)
if isinstance(xfa_map, dict) and xfa_map:
for name, payload in xfa_map.items():
error_code = _register(str(name), _stream_bytes(payload))
if error_code:
return packet_bytes, summaries, error_code
try:
root = reader.trailer.get('/Root') or reader.trailer['/Root']
acroform = root.get('/AcroForm') if hasattr(root, 'get') else None
if acroform is not None and hasattr(acroform, 'get_object'):
acroform = acroform.get_object()
xfa_ref = acroform.get('/XFA') if isinstance(acroform, dict) or hasattr(acroform, 'get') else None
if xfa_ref is not None and hasattr(xfa_ref, 'get_object'):
xfa_ref = xfa_ref.get_object()
except Exception:
xfa_ref = None
if isinstance(xfa_ref, ArrayObject):
index = 0
while index < len(xfa_ref):
name_obj = xfa_ref[index]
index += 1
if index >= len(xfa_ref):
break
payload_obj = xfa_ref[index]
index += 1
name = str(getattr(name_obj, 'name', name_obj) or name_obj or '').strip().lstrip('/')
error_code = _register(name, _stream_bytes(payload_obj))
if error_code:
return packet_bytes, summaries, error_code
elif xfa_ref is not None and not packet_bytes:
error_code = _register('xfa', _stream_bytes(xfa_ref))
if error_code:
return packet_bytes, summaries, error_code
return packet_bytes, summaries, None
def _has_acroform_fields(reader: PdfReader) -> bool:
"""判断 AcroForm 是否包含可读取字段。"""
try:
fields = reader.get_fields() or {}
return bool(fields)
except Exception:
return False
def _detect_document_kind(
*,
has_acroform: bool,
has_xfa: bool,
has_datasets: bool,
page_count: int,
has_acroform_fields: bool,
) -> XfaDocumentKind:
"""
根据 PDF 结构探测 document_kind。
Args:
has_acroform: 是否存在 AcroForm 字典。
has_xfa: 是否检测到 XFA packet 容器。
has_datasets: 是否包含 datasets packet。
page_count: 页面数。
has_acroform_fields: 是否存在 AcroForm 字段。
Returns:
plain_pdf | acroform | xfa_hybrid | pure_xfa | unsupported。
"""
if not has_xfa:
if has_acroform and has_acroform_fields:
return 'acroform'
return 'plain_pdf'
if not has_datasets:
return 'unsupported'
if page_count > 0 or has_acroform_fields:
return 'xfa_hybrid'
return 'pure_xfa'
def read_xfa_packets(
pdf_bytes: bytes,
*,
limits: dict[str, int] | None = None,
) -> XfaPacketReadResult:
"""
读取 PDF 中的 XFA packet 并识别文档类型。
核心逻辑:先校验 PDF 总大小,再用 pypdf 只读 AcroForm/XFA;不执行 JavaScript/FormCalc,
不触发任何网络访问。
Args:
pdf_bytes: 原始 PDF 字节。
limits: 可选资源上限覆盖项。
Returns:
XfaPacketReadResult:含 packet 摘要、document_kind 与支持标记。
Raises:
XfaPacketError: PDF 损坏或 packet 超限等确定性失败。
"""
resolved = _resolve_limits(limits)
if len(pdf_bytes) > resolved['max_pdf_bytes']:
raise XfaPacketError(
error_code='XFA_PACKET_TOO_LARGE',
route_reason='xfa_packet_too_large',
message='pdf exceeds max_pdf_bytes',
)
if not pdf_bytes:
raise XfaPacketError(
error_code='XFA_UNSUPPORTED_DOCUMENT',
route_reason='xfa_unsupported_document',
message='empty pdf',
)
try:
reader = PdfReader(BytesIO(pdf_bytes), strict=False)
except PdfReadError as exc:
raise XfaPacketError(
error_code='XFA_UNSUPPORTED_DOCUMENT',
route_reason='xfa_unsupported_document',
message='pdf unreadable',
) from exc
page_count = len(reader.pages)
has_acroform = False
try:
root = reader.trailer.get('/Root') or reader.trailer['/Root']
acroform = root.get('/AcroForm') if hasattr(root, 'get') else None
has_acroform = acroform is not None
except Exception:
has_acroform = False
packet_bytes, summaries, packet_error = _collect_xfa_packets_from_reader(
reader,
max_packet_bytes=int(resolved['max_packet_bytes']),
)
if packet_error:
route = 'xfa_packet_too_large' if packet_error == 'XFA_PACKET_TOO_LARGE' else 'xfa_unsupported_document'
raise XfaPacketError(error_code=packet_error, route_reason=route)
has_xfa = bool(packet_bytes)
has_datasets = 'datasets' in packet_bytes
has_acroform_fields = _has_acroform_fields(reader) if has_acroform else False
document_kind = _detect_document_kind(
has_acroform=has_acroform,
has_xfa=has_xfa,
has_datasets=has_datasets,
page_count=page_count,
has_acroform_fields=has_acroform_fields,
)
supported = document_kind in XFA_SUPPORTED_DOCUMENT_KINDS
error_code: str | None = None
route_reason: str | None = None
if has_xfa and not has_datasets:
error_code = 'XFA_DATASET_MISSING'
route_reason = 'xfa_dataset_missing'
elif document_kind == 'pure_xfa':
error_code = 'XFA_UNSUPPORTED_DOCUMENT'
route_reason = 'xfa_unsupported_document'
elif document_kind == 'unsupported':
error_code = 'XFA_UNSUPPORTED_DOCUMENT'
route_reason = 'xfa_unsupported_document'
return XfaPacketReadResult(
document_kind=document_kind,
packets=summaries,
packet_bytes_by_name=packet_bytes,
has_acroform=has_acroform,
has_acroform_fields=has_acroform_fields,
has_xfa=has_xfa,
page_count=page_count,
error_code=error_code,
route_reason=route_reason,
supported=supported,
)
def preflight_xml_bytes(xml_bytes: bytes) -> None:
"""
在 lxml 解析前拒绝 DOCTYPE/ENTITY 等不安全标记。
Args:
xml_bytes: 待解析 XML 字节。
Raises:
XfaPacketError: 检测到不安全 XML 结构。
"""
sample = xml_bytes[:65536].decode('utf-8', errors='ignore')
if _UNSAFE_XML_MARKERS.search(sample):
raise XfaPacketError(
error_code='XFA_UNSAFE_XML',
route_reason='xfa_unsafe_xml',
message='unsafe xml marker detected',
)
def is_deterministic_xfa_error(error_code: str | None) -> bool:
"""
判断 XFA 错误码是否属于确定性业务失败(不应重试)。
Args:
error_code: XFA_ERROR_CODES 中的稳定错误码。
Returns:
True 表示 Worker 不应重试。
"""
deterministic = {
'XFA_DATASET_MISSING',
'XFA_UNSAFE_XML',
'XFA_PACKET_TOO_LARGE',
'XFA_XML_DEPTH_EXCEEDED',
'XFA_XML_NODE_LIMIT_EXCEEDED',
'XFA_LINE_ROW_LIMIT_EXCEEDED',
'XFA_UNSUPPORTED_DOCUMENT',
'XFA_PATH_INVALID',
'XFA_PATH_UNKNOWN',
'XFA_DEFINITION_INVALID',
}
return str(error_code or '') in deterministic
@@ -0,0 +1,761 @@
"""
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 字段)。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import date, datetime
from decimal import Decimal
from typing import Any
from app.core.errors import ValidationError
from app.services.shipping_notice.document_layout.order_profile_extractors import (
parse_unit_price_with_price_unit,
)
from app.services.shipping_notice.document_layout.xfa_contract import (
OrderXfaDatasetProfile,
XfaFieldEvidenceRef,
XFA_PARSER_IDENTITY,
hash_data_path,
sanitize_xfa_dto,
)
from app.services.shipping_notice.document_layout.xfa_dataset import (
XfaDatasetAnalysis,
read_collection_rows,
read_dataset_value,
)
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
XfaSplitRuleSet,
parse_split_rule_sets,
)
from app.services.shipping_notice.document_layout.xfa_split_rule_engine import (
execute_split_rule_set,
)
from app.services.shipping_notice.order_schema.field_rules import (
normalize_order_field_value,
validate_order_field_value,
)
@dataclass
class XfaExtractedField:
"""单字段提取结果(含内部原始值,对外投影时剥离)。"""
field_id: str
field_code: str
mapping_id: str
data_path: str
raw_value: str | None
normalized_value: Any
quote: str
normalizer_key: str | None
evidence: dict[str, Any]
issues: list[str] = field(default_factory=list)
@dataclass
class XfaExtractionResult:
"""XFA 正式提取结果;rows 形状对齐坐标路径以便复用订单组装。"""
status: str
reason_codes: list[str] = field(default_factory=list)
header_fields: list[XfaExtractedField] = field(default_factory=list)
rows: list[dict[str, Any]] = field(default_factory=list)
packet_checksum: str | None = None
dataset_structure_fingerprint: str | None = None
parser_identity: str = XFA_PARSER_IDENTITY
profile_checksum: str | None = None
evidence_summary: dict[str, Any] = field(default_factory=dict)
def _schema_field_config(
*,
schema_fields: dict[str, dict[str, Any]],
field_id: str,
field_code: str,
value_type: str,
normalizer_key: str | None,
validator_key: str | None,
) -> dict[str, Any]:
"""合并 Schema 字段配置与映射上的类型/normalizer。"""
config = dict(schema_fields.get(field_id) or {})
if not config:
config = {
'field_id': field_id,
'field_code': field_code,
'value_type': value_type or 'string',
'normalizer_key': normalizer_key or 'trim',
'validator_keys': [validator_key] if validator_key else [],
}
else:
config = dict(config)
config.setdefault('field_id', field_id)
config.setdefault('field_code', field_code)
if value_type:
config['value_type'] = value_type
if normalizer_key:
config['normalizer_key'] = normalizer_key
if validator_key:
keys = list(config.get('validator_keys') or [])
if validator_key not in keys:
keys.append(validator_key)
config['validator_keys'] = keys
return config
def _normalize_display_value(value: Any) -> Any:
"""
将 Decimal/date 收敛为 JSON 可序列化的业务可读形式。
核心逻辑:整数型 Decimal → int(30.000 → 30);非整数 Decimal → 去尾零字符串;
date → ISO 字符串。与订单组装 json.dumps 共识逻辑兼容。
"""
if isinstance(value, Decimal):
normalized = value.normalize()
if normalized == normalized.to_integral_value():
return int(normalized)
text = format(normalized, 'f')
if '.' in text:
text = text.rstrip('0').rstrip('.')
return text
if isinstance(value, datetime):
return value.date().isoformat()
if isinstance(value, date):
return value.isoformat()
return value
def _build_evidence_ref(
*,
document_id: int,
packet_checksum: str,
data_path: str,
mapping_id: str,
normalized_value: Any,
normalizer_key: str | None,
cross_check_status: str = 'unavailable',
) -> dict[str, Any]:
"""构建普通 DTO 允许的字段 evidence(无明文路径/XML)。"""
display = normalized_value
if isinstance(display, Decimal):
display = format(display, 'f')
elif display is not None and not isinstance(display, (str, int, float, bool)):
display = str(display)
ref = XfaFieldEvidenceRef(
source='xfa_dataset',
document_id=max(int(document_id or 1), 1),
packet_checksum=packet_checksum,
data_path_hash=hash_data_path(data_path),
mapping_id=mapping_id,
raw_value_snapshot_ref=None,
normalized_value=None if display is None else str(display),
normalizer_key=normalizer_key,
cross_check_status=cross_check_status, # type: ignore[arg-type]
)
return sanitize_xfa_dto(ref.model_dump(mode='json'))
def _extract_one_field(
*,
raw_value: str | None,
mapping_id: str,
field_id: str,
field_code: str,
data_path: str,
value_type: str,
normalizer_key: str | None,
validator_key: str | None,
schema_fields: dict[str, dict[str, Any]],
document_id: int,
packet_checksum: str,
) -> XfaExtractedField:
"""标准化并校验单个映射字段。"""
config = _schema_field_config(
schema_fields=schema_fields,
field_id=field_id,
field_code=field_code,
value_type=value_type,
normalizer_key=normalizer_key,
validator_key=validator_key,
)
issues: list[str] = []
normalized: Any = None
if raw_value in (None, ''):
issues.append(f'order_profile_field_invalid:{field_code}')
else:
try:
typed = normalize_order_field_value(raw_value, config)
except (TypeError, ValueError, ValidationError):
typed = None
issues.append(f'order_profile_field_invalid:{field_code}')
if typed is not None and not validate_order_field_value(typed, config):
issues.append(f'order_profile_field_invalid:{field_code}')
typed = None
if typed is not None:
normalized = _normalize_display_value(typed)
evidence = _build_evidence_ref(
document_id=document_id,
packet_checksum=packet_checksum,
data_path=data_path,
mapping_id=mapping_id,
normalized_value=normalized,
normalizer_key=str(config.get('normalizer_key') or normalizer_key or '') or None,
)
return XfaExtractedField(
field_id=str(config.get('field_id') or field_id),
field_code=str(config.get('field_code') or field_code),
mapping_id=mapping_id,
data_path=data_path,
raw_value=raw_value,
normalized_value=normalized,
quote=str(raw_value or '')[:1000],
normalizer_key=str(config.get('normalizer_key') or '') or None,
evidence=evidence,
issues=issues,
)
def _is_formal_ready_split_rule_set(rule_set: XfaSplitRuleSet) -> bool:
"""
判断拆分规则集是否可用于正式提取。
核心逻辑:须 confirmed/published、非 requires_confirmation、非 system_suggestion。
"""
if rule_set.requires_confirmation:
return False
if rule_set.status not in ('confirmed', 'published'):
return False
if rule_set.source == 'system_suggestion':
return False
return True
def _build_path_id_to_data_path(profile: OrderXfaDatasetProfile) -> dict[str, str]:
"""从 Header/Line 映射构建 path_id → data_path 索引。"""
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)
return mapping
def _resolve_split_source_data_path(
rule_set: XfaSplitRuleSet,
*,
line_fields: list[Any],
path_id_to_data_path: dict[str, str],
) -> str | None:
"""
解析拆分规则集源字段 data_path。
核心逻辑:优先使用服务端冻结的 source_data_path,其次按 source_path_id 命中映射;
旧定义最后按 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):
return data_path or None
return None
def _apply_split_rules_for_header(
*,
dataset_analysis: XfaDatasetAnalysis,
rule_sets: list[XfaSplitRuleSet],
path_id_to_data_path: dict[str, str],
schema_fields: dict[str, dict[str, Any]],
schema_by_code: dict[str, dict[str, Any]],
document_id: int,
packet_checksum: str,
) -> tuple[list[XfaExtractedField], list[dict[str, Any]], list[str], bool]:
"""
对文档级源字段执行拆分规则一次。
Returns:
(header_fields, split_evidence, issues, required_missing)
"""
fields: list[XfaExtractedField] = []
evidence: list[dict[str, Any]] = []
issues: list[str] = []
required_missing = False
for rule_set in rule_sets:
data_path = _resolve_split_source_data_path(
rule_set,
line_fields=[],
path_id_to_data_path=path_id_to_data_path,
)
if not data_path:
issues.append('xfa_split_rule_unconfirmed')
continue
raw_value = read_dataset_value(dataset_analysis, data_path)
split_result = execute_split_rule_set(raw_value=raw_value or '', rule_set=rule_set)
if split_result.status != 'parsed':
issues.append('xfa_split_rule_needs_review')
issues.extend(
f'xfa_split:{item.code}' for item in split_result.diagnostics if item.code
)
for segment in split_result.evidence_only_segments:
evidence.append({
'segment_id': segment.segment_id,
'segment_code': segment.segment_code,
'display_name': segment.display_name,
'line_no': segment.line_no,
'line_end_no': segment.line_end_no,
'raw_text': segment.raw_text,
'normalized_text': segment.normalized_text,
'rule_id': segment.rule_id,
'source_path_id': rule_set.source_path_id,
})
for field_code, mapped_raw in split_result.mapped_fields.items():
cfg = schema_by_code.get(field_code) or {}
extracted = _extract_one_field(
raw_value=mapped_raw,
mapping_id=f'split-{rule_set.rule_id}-{field_code}'[:64],
field_id=str(cfg.get('field_id') or field_code),
field_code=field_code,
data_path=data_path,
value_type=str(cfg.get('value_type') or 'string'),
normalizer_key=str(cfg.get('normalizer_key') or 'trim') or None,
validator_key=(cfg.get('validator_keys') or [None])[0],
schema_fields=schema_fields,
document_id=document_id,
packet_checksum=packet_checksum,
)
fields.append(extracted)
issues.extend(extracted.issues)
if extracted.normalized_value is None:
required_missing = True
return fields, evidence, issues, required_missing
def _schema_by_field_code(schema_fields: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]:
"""field_code → Schema 配置。"""
indexed: dict[str, dict[str, Any]] = {}
for item in schema_fields.values():
code = str(item.get('field_code') or '').strip()
if code:
indexed[code] = item
return indexed
def _apply_split_rules_for_row(
*,
row_values: dict[str, str],
rule_sets: list[XfaSplitRuleSet],
line_fields: list[Any],
path_id_to_data_path: dict[str, str],
schema_fields: dict[str, dict[str, Any]],
schema_by_code: dict[str, dict[str, Any]],
document_id: int,
packet_checksum: str,
row_index: int,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], set[str], list[str], bool]:
"""
对单行执行已确认拆分规则并产出 Schema 字段值与 evidence_only 段。
Returns:
(values, split_evidence, produced_field_codes, issues, required_missing)
"""
values: list[dict[str, Any]] = []
split_evidence: list[dict[str, Any]] = []
produced_codes: set[str] = set()
issues: list[str] = []
required_missing = False
for rule_set in rule_sets:
data_path = _resolve_split_source_data_path(
rule_set,
line_fields=line_fields,
path_id_to_data_path=path_id_to_data_path,
)
if not data_path:
issues.append('xfa_split_rule_unconfirmed')
continue
raw_value = row_values.get(data_path)
split_result = execute_split_rule_set(raw_value=raw_value or '', rule_set=rule_set)
if split_result.status != 'parsed':
issues.append('xfa_split_rule_needs_review')
for diagnostic in split_result.diagnostics:
if diagnostic.code:
issues.append(f'xfa_split:{diagnostic.code}')
for segment in split_result.evidence_only_segments:
split_evidence.append({
'segment_id': segment.segment_id,
'segment_code': segment.segment_code,
'display_name': segment.display_name,
'line_no': segment.line_no,
'line_end_no': segment.line_end_no,
'raw_text': segment.raw_text,
'normalized_text': segment.normalized_text,
'rule_id': segment.rule_id,
'source_path_id': rule_set.source_path_id,
'row_index': row_index,
})
for field_code, mapped_raw in split_result.mapped_fields.items():
cfg = schema_by_code.get(field_code) or {}
field_id = str(cfg.get('field_id') or field_code)
extracted = _extract_one_field(
raw_value=mapped_raw,
mapping_id=f'split-{rule_set.rule_id}-{field_code}'[:64],
field_id=field_id,
field_code=field_code,
data_path=data_path,
value_type=str(cfg.get('value_type') or 'string'),
normalizer_key=str(cfg.get('normalizer_key') or 'trim') or None,
validator_key=(cfg.get('validator_keys') or [None])[0],
schema_fields=schema_fields,
document_id=document_id,
packet_checksum=packet_checksum,
)
if extracted.issues:
issues.extend(extracted.issues)
if extracted.normalized_value is None:
required_missing = True
continue
produced_codes.add(field_code)
values.append({
'field_id': extracted.field_id,
'field_code': extracted.field_code,
'value': extracted.normalized_value,
'quote': extracted.quote,
'source': 'xfa_dataset',
'evidence_ref': extracted.evidence,
'highlight_source': 'xfa_split',
'row_index': row_index,
'split_rule_id': rule_set.rule_id,
})
return values, split_evidence, produced_codes, issues, required_missing
def extract_xfa_profile(
*,
raw_profile: dict[str, Any],
dataset_analysis: XfaDatasetAnalysis,
schema_definition: dict[str, Any],
document_id: int,
packet_checksum: str,
dataset_structure_fingerprint: str | None = None,
) -> XfaExtractionResult:
"""
按冻结 XFA Profile 提取 Header 与权威明细行。
核心逻辑:校验 definition → 读 Header 叶子 → 读权威集合行 → Schema 标准化;
权威集合缺失时 fail-closed(reason=xfa_authoritative_collection_missing)。
Args:
raw_profile: 冻结 Profile 快照(含 definition / checksum)。
dataset_analysis: 当前文档 datasets 分析。
schema_definition: Run 冻结 Schema definition_json。
document_id: 当前文档 ID(写入 evidence)。
packet_checksum: datasets packet checksum。
dataset_structure_fingerprint: 结构指纹(写入摘要)。
Returns:
XfaExtractionResult:含 rows(对齐坐标路径)与安全 evidence_summary。
"""
definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {}
try:
profile = OrderXfaDatasetProfile.model_validate(definition)
except (TypeError, ValueError):
return XfaExtractionResult(
status='failed',
reason_codes=['xfa_definition_invalid'],
packet_checksum=packet_checksum,
dataset_structure_fingerprint=dataset_structure_fingerprint,
profile_checksum=str(raw_profile.get('checksum') or '') or None,
)
schema_fields = {
str(item.get('field_id') or ''): item
for item in (schema_definition.get('fields') or [])
if isinstance(item, dict) and item.get('enabled', True) and item.get('field_id')
}
# [STEP 1] Header 映射
header_fields: list[XfaExtractedField] = []
header_issues: list[str] = []
for mapping in profile.header_mappings:
raw_value = read_dataset_value(dataset_analysis, mapping.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,
schema_fields=schema_fields,
document_id=document_id,
packet_checksum=packet_checksum,
)
header_fields.append(extracted)
header_issues.extend(extracted.issues)
# [STEP 2] 权威集合行
auth_path = profile.source_contract.authoritative_line_collection_path
line_rows = read_collection_rows(dataset_analysis, auth_path)
if not line_rows:
return XfaExtractionResult(
status='failed',
reason_codes=['xfa_authoritative_collection_missing'],
header_fields=header_fields,
packet_checksum=packet_checksum,
dataset_structure_fingerprint=dataset_structure_fingerprint,
profile_checksum=str(raw_profile.get('checksum') or '') or None,
evidence_summary={
'header_field_count': len(header_fields),
'line_row_count': 0,
'parser_identity': XFA_PARSER_IDENTITY,
},
)
rows: list[dict[str, Any]] = []
required_missing = False
all_split_rule_sets = parse_split_rule_sets(profile.split_rules or [])
# [STEP] 任意规则集未确认 → 彻底 fail-closed:不执行任何拆分产出 mapped 字段。
has_unconfirmed_split_rules = bool(all_split_rule_sets) and any(
not _is_formal_ready_split_rule_set(item) for item in all_split_rule_sets
)
formal_split_rule_sets = (
[]
if has_unconfirmed_split_rules
else [item for item in all_split_rule_sets if _is_formal_ready_split_rule_set(item)]
)
path_id_to_data_path = _build_path_id_to_data_path(profile)
schema_by_code = _schema_by_field_code(schema_fields)
split_global_issues: list[str] = []
normalized_auth_path = auth_path.rstrip('/')
header_split_rule_sets = [
item for item in formal_split_rule_sets
if item.source_data_path and not str(item.source_data_path).startswith(f'{normalized_auth_path}/')
]
line_split_rule_sets = [item for item in formal_split_rule_sets if item not in header_split_rule_sets]
header_split_evidence: list[dict[str, Any]] = []
if header_split_rule_sets:
split_headers, header_split_evidence, split_header_issues, split_header_missing = (
_apply_split_rules_for_header(
dataset_analysis=dataset_analysis,
rule_sets=header_split_rule_sets,
path_id_to_data_path=path_id_to_data_path,
schema_fields=schema_fields,
schema_by_code=schema_by_code,
document_id=document_id,
packet_checksum=packet_checksum,
)
)
header_fields.extend(split_headers)
header_issues.extend(split_header_issues)
required_missing = required_missing or split_header_missing
split_source_path_ids = {str(item.source_path_id) for item in line_split_rule_sets}
if has_unconfirmed_split_rules:
split_global_issues.append('xfa_split_rule_unconfirmed')
for index, row_values in enumerate(line_rows, start=1):
values: list[dict[str, Any]] = []
issues = list(header_issues) + list(split_global_issues)
split_evidence: list[dict[str, Any]] = []
split_produced_codes: set[str] = set()
# [STEP 2a] 已确认拆分规则:mapped 字段 + evidence_only 段。
if line_split_rule_sets:
split_values, split_evidence, split_produced_codes, split_issues, split_required_missing = (
_apply_split_rules_for_row(
row_values=row_values,
rule_sets=line_split_rule_sets,
line_fields=list(profile.line_mapping.fields),
path_id_to_data_path=path_id_to_data_path,
schema_fields=schema_fields,
schema_by_code=schema_by_code,
document_id=document_id,
packet_checksum=packet_checksum,
row_index=index,
)
)
values.extend(split_values)
issues.extend(split_issues)
if split_required_missing:
required_missing = True
# Header 字段挂到每行,供 _build_approved_profile_order_result 聚合。
for header in header_fields:
if header.normalized_value is None:
required_missing = True
continue
values.append({
'field_id': header.field_id,
'field_code': header.field_code,
'value': header.normalized_value,
'quote': header.quote,
'source': 'xfa_dataset',
'evidence_ref': header.evidence,
'highlight_source': 'xfa_dataset',
})
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:
continue
if str(mapping.path_id or '') in split_source_path_ids:
continue
raw_value = row_values.get(mapping.data_path)
extract_raw = raw_value
# [STEP] NETPR 复合值:拆出单价;价格单位若无独立映射则稍后补齐。
if str(mapping.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
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,
schema_fields=schema_fields,
document_id=document_id,
packet_checksum=packet_checksum,
)
# 保留原文 quote(含 ``898.72 / 1``)便于审计对账。
if (
str(mapping.field_code or '') == 'unit_price'
and raw_value not in (None, '')
and extract_raw != raw_value
):
extracted = XfaExtractedField(
field_id=extracted.field_id,
field_code=extracted.field_code,
mapping_id=extracted.mapping_id,
data_path=extracted.data_path,
raw_value=str(raw_value),
normalized_value=extracted.normalized_value,
quote=str(raw_value)[:1000],
normalizer_key=extracted.normalizer_key,
evidence=extracted.evidence,
issues=extracted.issues,
)
if extracted.issues:
issues.extend(extracted.issues)
if extracted.normalized_value is None:
required_missing = True
continue
values.append({
'field_id': extracted.field_id,
'field_code': extracted.field_code,
'value': extracted.normalized_value,
'quote': extracted.quote,
'source': 'xfa_dataset',
'evidence_ref': extracted.evidence,
'highlight_source': 'xfa_dataset',
'row_index': index,
})
# 仅映射 NETPR 复合值、未单独映射 PEINH 时,补齐 price_unit。
present_codes = {
str(item.get('field_code') or '')
for item in values
if isinstance(item, dict)
}
if pending_price_unit_raw and 'price_unit' not in present_codes:
pu_schema = next(
(
item for item in schema_fields.values()
if str(item.get('field_code') or '') == 'price_unit'
),
None,
)
pu_field_id = str((pu_schema or {}).get('field_id') or 'price_unit')
pu_extracted = _extract_one_field(
raw_value=pending_price_unit_raw,
mapping_id='derived-unit-price-price-unit',
field_id=pu_field_id,
field_code='price_unit',
data_path=str(pending_price_unit_path or '/data'),
value_type=str((pu_schema or {}).get('value_type') or 'integer'),
normalizer_key=str((pu_schema or {}).get('normalizer_key') or 'trim') or None,
validator_key=None,
schema_fields=schema_fields,
document_id=document_id,
packet_checksum=packet_checksum,
)
if pu_extracted.issues:
issues.extend(pu_extracted.issues)
if pu_extracted.normalized_value is None:
required_missing = True
else:
values.append({
'field_id': pu_extracted.field_id,
'field_code': 'price_unit',
'value': pu_extracted.normalized_value,
'quote': pu_extracted.quote,
'source': 'xfa_dataset',
'evidence_ref': pu_extracted.evidence,
'highlight_source': 'xfa_dataset',
'row_index': index,
'derived_from': 'unit_price_price_unit',
})
rows.append({
'row_index': index,
'status': 'parsed' if not issues else 'needs_review',
'fields': values,
'issues': sorted(set(issues)),
'split_evidence': split_evidence,
})
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):
reason_codes.append('xfa_required_field_missing')
evidence_summary = sanitize_xfa_dto({
'header_field_count': len(header_fields),
'line_row_count': len(rows),
'packet_checksum': packet_checksum,
'dataset_structure_fingerprint': dataset_structure_fingerprint,
'parser_identity': XFA_PARSER_IDENTITY,
'profile_checksum': str(raw_profile.get('checksum') or '') or None,
'header_split_evidence': header_split_evidence,
'field_evidence_refs': [
item.evidence for item in header_fields
] + [
field.get('evidence_ref')
for row in rows
for field in row.get('fields') or []
if isinstance(field, dict) and field.get('evidence_ref')
and str(field.get('field_code') or '') not in {h.field_code for h in header_fields}
],
})
return XfaExtractionResult(
status='parsed' if not reason_codes else 'needs_review',
reason_codes=reason_codes,
header_fields=header_fields,
rows=rows,
packet_checksum=packet_checksum,
dataset_structure_fingerprint=dataset_structure_fingerprint,
profile_checksum=str(raw_profile.get('checksum') or '') or None,
evidence_summary=evidence_summary,
)
@@ -0,0 +1,191 @@
"""
backend/app/services/shipping_notice/document_layout/xfa_profile_matcher.py
用途:对冻结 published XFA Profile 做精确结构身份匹配(禁止模糊/OCR/VLM)。
依赖:xfa_contract(OrderXfaDatasetProfile / sanitize)、ProfileMatchResult 形状对齐。
逻辑:由 order_extraction_workflow XFA 分支调用;仅比较
template_packet_checksum + dataset_structure_fingerprint;草稿/retired 不在快照内。
"""
from __future__ import annotations
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
from app.services.shipping_notice.document_layout.xfa_contract import (
OrderXfaDatasetProfile,
sanitize_xfa_dto,
)
class XfaProfileMatchCandidate(BaseModel):
"""单个冻结 XFA Profile 的精确身份匹配摘要(无业务值)。"""
model_config = ConfigDict(extra='forbid')
profile_code: str
version: int = Field(ge=1)
checksum: str | None = None
hard_match: bool = False
reason_codes: list[str] = Field(default_factory=list)
template_packet_checksum: str | None = None
dataset_structure_fingerprint: str | None = None
class XfaProfileMatchResult(BaseModel):
"""文档级 XFA Profile 精确匹配结果;仅 unique_match 可启动正式提取。"""
model_config = ConfigDict(extra='forbid')
status: Literal[
'unique_match',
'no_match',
'ambiguous',
'evidence_insufficient',
'structure_identity_changed',
]
profile_code: str | None = None
version: int | None = None
checksum: str | None = None
profile_id: int | None = None
template_packet_checksum: str | None = None
dataset_structure_fingerprint: str | None = None
candidates: list[XfaProfileMatchCandidate] = Field(default_factory=list)
reason_codes: list[str] = Field(default_factory=list)
def model_dump_safe(self) -> dict[str, Any]:
"""返回经 sanitize 的可持久化字典。"""
return sanitize_xfa_dto(self.model_dump(mode='json'))
def _is_xfa_definition(definition: dict[str, Any] | None) -> bool:
"""判断 definition 是否为 xfa_dataset 模式。"""
if not isinstance(definition, dict):
return False
return str(definition.get('template_mode') or '').strip() == 'xfa_dataset'
def match_frozen_xfa_profiles(
*,
profiles: list[dict[str, Any]],
template_packet_checksum: str | None,
dataset_structure_fingerprint: str | None,
) -> XfaProfileMatchResult:
"""
对同一文档的冻结 published XFA Profile 做精确结构身份匹配。
核心逻辑:仅当 template_packet_checksum 与 dataset_structure_fingerprint
同时相等时计为 hard_match;0 命中 → no_match,1 → unique_match,≥2 → ambiguous。
禁止模糊相似度、客户 ID 单独命中或字段名猜测。
Args:
profiles: Run 冻结的 order_document_profiles(应已排除 draft/retired)。
template_packet_checksum: 当前文档 live template packet checksum。
dataset_structure_fingerprint: 当前文档 live dataset 结构指纹。
Returns:
XfaProfileMatchResult:含候选摘要与稳定 reason_codes。
"""
live_template = str(template_packet_checksum or '').strip() or None
live_fingerprint = str(dataset_structure_fingerprint or '').strip() or None
if not live_template or not live_fingerprint:
return XfaProfileMatchResult(
status='evidence_insufficient',
reason_codes=['xfa_structure_identity_changed'],
template_packet_checksum=live_template,
dataset_structure_fingerprint=live_fingerprint,
)
candidates: list[XfaProfileMatchCandidate] = []
hard_matches: list[tuple[dict[str, Any], XfaProfileMatchCandidate]] = []
for raw in profiles:
if not isinstance(raw, dict):
continue
definition = raw.get('definition') if isinstance(raw.get('definition'), dict) else {}
if not _is_xfa_definition(definition):
continue
# 防御:即使快照误含非 published,也不参与新 Run 匹配。
status = str(raw.get('status') or 'published').strip()
if status in {'draft', 'retired'}:
continue
reason_codes: list[str] = []
try:
profile = OrderXfaDatasetProfile.model_validate(definition)
except (TypeError, ValueError):
reason_codes.append('xfa_definition_invalid')
candidates.append(XfaProfileMatchCandidate(
profile_code=str(raw.get('profile_code') or ''),
version=max(int(raw.get('version') or 1), 1),
checksum=str(raw.get('checksum') or '') or None,
hard_match=False,
reason_codes=reason_codes,
))
continue
source = profile.source_contract
profile_template = str(source.template_packet_checksum or '').strip()
profile_fingerprint = str(source.dataset_structure_fingerprint or '').strip()
hard = (
bool(profile_template)
and bool(profile_fingerprint)
and profile_template == live_template
and profile_fingerprint == live_fingerprint
and bool(str(raw.get('checksum') or '').strip())
)
if not hard:
if profile_template != live_template or profile_fingerprint != live_fingerprint:
reason_codes.append('xfa_structure_identity_changed')
else:
reason_codes.append('xfa_profile_not_matched')
candidate = XfaProfileMatchCandidate(
profile_code=str(raw.get('profile_code') or ''),
version=max(int(raw.get('version') or 1), 1),
checksum=str(raw.get('checksum') or '') or None,
hard_match=hard,
reason_codes=reason_codes,
template_packet_checksum=profile_template or None,
dataset_structure_fingerprint=profile_fingerprint or None,
)
candidates.append(candidate)
if hard:
hard_matches.append((raw, candidate))
if not candidates:
return XfaProfileMatchResult(
status='no_match',
reason_codes=['xfa_profile_not_matched'],
template_packet_checksum=live_template,
dataset_structure_fingerprint=live_fingerprint,
candidates=candidates,
)
if len(hard_matches) == 0:
return XfaProfileMatchResult(
status='no_match',
reason_codes=['xfa_profile_not_matched'],
template_packet_checksum=live_template,
dataset_structure_fingerprint=live_fingerprint,
candidates=candidates,
)
if len(hard_matches) > 1:
return XfaProfileMatchResult(
status='ambiguous',
reason_codes=['xfa_profile_ambiguous'],
template_packet_checksum=live_template,
dataset_structure_fingerprint=live_fingerprint,
candidates=candidates,
)
raw, winner = hard_matches[0]
return XfaProfileMatchResult(
status='unique_match',
profile_code=winner.profile_code,
version=winner.version,
checksum=winner.checksum,
profile_id=int(raw.get('profile_id') or raw.get('id') or 0) or None,
template_packet_checksum=live_template,
dataset_structure_fingerprint=live_fingerprint,
candidates=candidates,
reason_codes=[],
)
@@ -0,0 +1,147 @@
"""
backend/app/services/shipping_notice/document_layout/xfa_signature.py
用途:计算 XFA template packet checksum、datasets 结构指纹与治理用 structure signature。
依赖:xfa_contract、xfa_dataset.XfaDatasetNode、标准库 hashlib/json。
逻辑:由 xfa_analysis / 验证服务调用;指纹忽略业务值与行数;structure signature
冻结 analysis 与 packet 身份供发布门禁引用。
"""
from __future__ import annotations
import hashlib
import json
from typing import Any
from app.services.shipping_notice.document_layout.xfa_contract import (
XFA_STRUCTURE_SIGNATURE_ID,
XfaStructureNodeSpec,
compute_dataset_structure_fingerprint,
)
from app.services.shipping_notice.document_layout.xfa_dataset import XfaDatasetNode
from app.services.shipping_notice.document_layout.xfa_packets import compute_packet_checksum
def compute_template_packet_checksum(template_bytes: bytes | None) -> str | None:
"""
计算 template packet 的稳定 checksum。
Args:
template_bytes: template packet 原始字节;缺失时返回 None。
Returns:
`sha256:<hex>` 或 None。
"""
if not template_bytes:
return None
return compute_packet_checksum(template_bytes)
def dataset_nodes_to_structure_specs(nodes: list[XfaDatasetNode]) -> list[XfaStructureNodeSpec]:
"""
将受控路径树转换为结构指纹输入节点。
核心逻辑:只保留 local_name/namespace/depth/cardinality/children;不包含样本值与行计数。
Args:
nodes: datasets 路径树根列表。
Returns:
XfaStructureNodeSpec 列表。
"""
def _convert(node: XfaDatasetNode) -> XfaStructureNodeSpec:
return XfaStructureNodeSpec(
local_name=node.local_name,
namespace_uri=node.namespace_uri,
depth=node.depth,
cardinality=node.cardinality,
children=[_convert(child) for child in node.children],
)
return [_convert(item) for item in nodes]
def compute_dataset_structure_fingerprint_from_nodes(nodes: list[XfaDatasetNode]) -> str:
"""
基于路径树计算 dataset 结构指纹。
Args:
nodes: datasets 路径树根列表。
Returns:
`sha256:<hex>` 结构指纹。
"""
specs = dataset_nodes_to_structure_specs(nodes)
return compute_dataset_structure_fingerprint(specs)
def build_signature_summary(
*,
template_bytes: bytes | None,
dataset_nodes: list[XfaDatasetNode],
) -> dict[str, Any]:
"""
汇总 template checksum 与 datasets 结构指纹。
Args:
template_bytes: template packet 字节。
dataset_nodes: 已解析 datasets 路径树。
Returns:
含 template_packet_checksum 与 dataset_structure_fingerprint 的字典。
"""
return {
'template_packet_checksum': compute_template_packet_checksum(template_bytes),
'dataset_structure_fingerprint': compute_dataset_structure_fingerprint_from_nodes(dataset_nodes),
}
def build_xfa_structure_signature(
*,
template_packet_checksum: str | None,
dataset_structure_fingerprint: str | None,
datasets_packet_checksum: str | None,
definition_checksum: str,
analysis_ids: list[int],
parser_identity: str,
) -> dict[str, Any]:
"""
生成 XFA 结构签名快照(替代 coordinate layout_signature)。
核心逻辑:对 analysis/packet/structure/definition/parser 身份做稳定哈希;
不含订单值、文件名或明细行数。
Args:
template_packet_checksum: template packet 身份。
dataset_structure_fingerprint: datasets 结构指纹。
datasets_packet_checksum: datasets packet 内容 checksum(可与 template 不同)。
definition_checksum: 当前草稿 definition checksum。
analysis_ids: 冻结的结构分析记录 ID 列表。
parser_identity: 解析器身份常量。
Returns:
含 signature_version / signature_checksum / evidence 的安全快照。
"""
payload = {
'signature_version': XFA_STRUCTURE_SIGNATURE_ID,
'template_packet_checksum': str(template_packet_checksum or ''),
'dataset_structure_fingerprint': str(dataset_structure_fingerprint or ''),
'datasets_packet_checksum': str(datasets_packet_checksum or ''),
'definition_checksum': str(definition_checksum or ''),
'analysis_ids': sorted(int(item) for item in analysis_ids),
'parser_identity': str(parser_identity or ''),
}
encoded = json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
checksum = hashlib.sha256(encoded).hexdigest()
return {
'signature_version': XFA_STRUCTURE_SIGNATURE_ID,
'signature_checksum': checksum,
'signature': payload,
'evidence_quality': {
'source_sample_count': len(analysis_ids),
'analysis_count': len(analysis_ids),
'has_template_checksum': bool(template_packet_checksum),
'has_structure_fingerprint': bool(dataset_structure_fingerprint),
},
}
@@ -0,0 +1,434 @@
"""
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 与正式提取路径引用。
逻辑:仅声明式校验,不执行规则、不读 PDF、不接网络;非法契约以 ValidationError
或 ValueError 拒绝;不提供系统推荐;若残留 source=system_suggestion 必须 draft。
"""
from __future__ import annotations
import re
import uuid
from typing import Any, Final, Literal
from pydantic import Field, field_validator, model_validator
from app.services.shipping_notice.document_layout.xfa_contract import (
XfaContractModel,
validate_controlled_data_path,
)
# ---------------------------------------------------------------------------
# 资源上限(防止灾难性回溯与规则爆炸)
# ---------------------------------------------------------------------------
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_REGEX_TIMEOUT_MS: Final[int] = 50
XfaSplitHandling = Literal['mapped', 'evidence_only']
XfaSplitStageType = Literal[
'split_lines',
'select_line',
'select_line_range',
'extract_prefix',
'regex_capture',
'replace',
'substring',
'normalize',
]
XfaSplitStrategy = Literal['pipeline']
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'\([^)]*[+*][^)]*\)\{'),
)
class XfaSplitSegment(XfaContractModel):
"""自定义拆分段:与 Schema 字段分离;mapped 时绑定冻结 Schema。"""
segment_id: str = Field(min_length=8, max_length=64)
segment_code: str = Field(min_length=2, max_length=XFA_SPLIT_MAX_SEGMENT_CODE_LENGTH)
display_name: str = Field(min_length=1, max_length=XFA_SPLIT_MAX_DISPLAY_NAME_LENGTH)
handling: XfaSplitHandling
target_field_id: str | None = Field(default=None, max_length=64)
target_field_code: str | None = Field(default=None, max_length=128)
note: str | None = Field(default=None, max_length=256)
@field_validator('segment_code', mode='before')
@classmethod
def validate_segment_code(cls, value: Any) -> str:
"""segment_code 必须为小写蛇形,Profile 内唯一由上层校验。"""
code = str(value or '').strip()
if not _SEGMENT_CODE_RE.fullmatch(code):
raise ValueError(
'segment_code must be lowercase snake_case starting with a letter',
)
return code
@model_validator(mode='after')
def validate_handling_targets(self) -> 'XfaSplitSegment':
"""mapped 必须绑定目标字段;evidence_only 禁止目标字段。"""
if self.handling == 'mapped':
if not self.target_field_id or not self.target_field_code:
raise ValueError('mapped segment requires target_field_id and target_field_code')
else:
if self.target_field_id or self.target_field_code:
raise ValueError('evidence_only segment must not set target fields')
return self
class XfaSplitStage(XfaContractModel):
"""
单阶段处理步骤(声明式流水线节点)。
状态机:split_lines 产出行列表;select_line/select_line_range 产出标量并记录行号范围;
其余阶段在标量文本上变换。
"""
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
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
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':
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':
label = str(self.value or '').strip()
if not label:
raise ValueError('extract_prefix requires non-empty value')
seps = [str(item) for item in (self.separators or []) if str(item)]
if not seps:
raise ValueError('extract_prefix requires at least one separator')
object.__setattr__(self, 'separators', seps)
object.__setattr__(self, 'value', label)
elif self.type == 'regex_capture':
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 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
return self
class XfaSplitRule(XfaContractModel):
"""单条输出流水线:显式 order + stages[] + segment。"""
rule_id: str = Field(min_length=1, max_length=64)
order: int = Field(ge=1, le=10_000)
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: bool = True
remove_empty_lines: bool = True
line_breaks: list[str] = Field(default_factory=lambda: ['\r\n', '\r', '\n'])
@model_validator(mode='after')
def validate_breaks(self) -> 'XfaSplitNormalization':
"""line_breaks 不可为空。"""
breaks = [str(item) for item in (self.line_breaks or []) if str(item)]
if not breaks:
raise ValueError('normalization.line_breaks requires at least one value')
object.__setattr__(self, 'line_breaks', breaks)
return self
class XfaSplitRuleSet(XfaContractModel):
"""
针对单一源字段的拆分规则集,存于 Profile definition_json.split_rules。
规则由管理员手工配置(source=user/imported)。若出现历史 source=system_suggestion,
必须保持 draft + requires_confirmation,且不得进入正式提取/发布。
"""
rule_id: str = Field(min_length=1, max_length=128)
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_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'
duplicate_match_policy: XfaSplitDuplicatePolicy = 'needs_review'
same_field_multiple_segment_policy: XfaSplitDuplicatePolicy = 'needs_review'
source: XfaSplitRuleSource = 'user'
status: XfaSplitRuleStatus = 'draft'
requires_confirmation: bool = False
@field_validator('source_data_path', mode='before')
@classmethod
def validate_source_data_path(cls, value: Any) -> str | None:
"""校验由服务端写入的拆分源路径;旧定义允许为空以兼容读取。"""
if value in (None, ''):
return None
return validate_controlled_data_path(value)
@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}')
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')
segment_codes = [item.segment.segment_code for item in self.rules]
if len(segment_codes) != len(set(segment_codes)):
raise ValueError('duplicate segment_code within split rule set')
if self.source == 'system_suggestion':
if self.status != 'draft' or not self.requires_confirmation:
raise ValueError(
'system_suggestion must be draft with requires_confirmation=true',
)
return self
def new_segment_id() -> str:
"""
生成不可变 segment_id。
Returns:
形如 seg-<uuid4hex> 的稳定标识。
"""
return f'seg-{uuid.uuid4().hex}'
def new_rule_id(prefix: str = 'rule') -> str:
"""
生成规则条目 ID。
Args:
prefix: ID 前缀。
Returns:
形如 ``{prefix}-<hex>`` 的标识。
"""
safe = re.sub(r'[^a-z0-9_]+', '_', str(prefix or 'rule').strip().lower()) or 'rule'
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。
Args:
rule_set: 模型或 dict。
Returns:
稳定 JSON 字符串指纹素材(调用方可再 hash)。
"""
import json
if isinstance(rule_set, XfaSplitRuleSet):
payload = rule_set.model_dump(mode='json')
else:
payload = dict(rule_set or {})
payload.pop('status', None)
payload.pop('requires_confirmation', None)
payload.pop('rule_version', None)
return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
def validate_split_rules_against_schema(
rule_sets: list[XfaSplitRuleSet],
*,
known_schema_fields: dict[str, dict[str, Any]],
known_path_ids: set[str] | None = None,
source_scopes: dict[str, str] | None = None,
) -> list[XfaSplitRuleSet]:
"""
相对冻结 Schema 与已知 path_id 校验拆分规则集。
核心逻辑:目标字段必须存在、启用且与拆分源节点 scope 一致;
source_path_id 必须已知(若提供集合)。
Args:
rule_sets: 待校验规则集。
known_schema_fields: field_code → Schema 字段配置(仅 enabled)。
known_path_ids: 分析记录合法 path_id;None 时跳过路径存在性检查。
source_scopes: source_path_id → header/line;未提供时仅校验字段存在性。
Returns:
校验通过的同一列表。
Raises:
ValueError: 契约或 Schema 引用非法。
"""
if len(rule_sets) > XFA_SPLIT_MAX_RULE_SETS:
raise ValueError(f'split_rules exceed max {XFA_SPLIT_MAX_RULE_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}')
for rule in rule_set.rules:
all_codes.append(rule.segment.segment_code)
all_segment_ids.append(rule.segment.segment_id)
if rule.segment.handling != 'mapped':
continue
code = str(rule.segment.target_field_code or '')
field = known_schema_fields.get(code)
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"}',
)
expected_id = str(field.get('field_id') or '')
if expected_id and rule.segment.target_field_id != expected_id:
raise ValueError(
f'target_field_id mismatch for {code}: '
f'expected {expected_id}, got {rule.segment.target_field_id}',
)
if len(all_codes) != len(set(all_codes)):
raise ValueError('segment_code must be unique across Profile split_rules')
if len(all_segment_ids) != len(set(all_segment_ids)):
raise ValueError('segment_id must be unique across Profile split_rules')
return rule_sets
def parse_split_rule_sets(raw: Any) -> list[XfaSplitRuleSet]:
"""
将 definition_json.split_rules 解析为模型列表。
Args:
raw: JSON 列表或 None。
Returns:
XfaSplitRuleSet 列表;空输入返回 []。
Raises:
ValueError: 形状或契约非法。
"""
if raw is None:
return []
if not isinstance(raw, list):
raise ValueError('split_rules must be a list')
return [XfaSplitRuleSet.model_validate(item) for item in raw]
@@ -0,0 +1,512 @@
"""
services/shipping_notice/document_layout/xfa_split_rule_engine.py
用途:声明式执行 XFA 多阶段拆分流水线,产出 mapped Schema 值与 evidence_only 段。
依赖:xfa_split_rule_contract、concurrent.futures(正则超时)。
逻辑:由预览 API 与正式提取调用;无网络、无脚本、无 LLM;
每条 rule 按 stages[] 顺序独立变换;显式 order 决定冲突判定次序;
同一行被多条流水线 select_line/select_line_range 认领 → needs_review;正式字段冲突 → needs_review。
"""
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_split_rule_contract import (
XFA_SPLIT_REGEX_TIMEOUT_MS,
XfaSplitRule,
XfaSplitRuleSet,
XfaSplitStage,
)
@dataclass
class XfaSplitSegmentResult:
"""单段执行结果(含起止行号与证据文本)。"""
segment_id: str
segment_code: str
display_name: str
line_no: int | None
line_end_no: int | None
raw_text: str
normalized_text: str
handling: str
target_field_id: str | None
target_field_code: str | None
rule_id: str
status: str
matcher_type: str # 兼容预览字段名:末级 stage type 或 unmatched
@dataclass
class XfaSplitDiagnostic:
"""规则执行诊断。"""
code: str
message: str
line_no: int | None = None
field_code: str | None = None
rule_ids: list[str] = field(default_factory=list)
@dataclass
class XfaSplitEngineResult:
"""规则引擎输出。"""
status: str
segments: list[XfaSplitSegmentResult] = field(default_factory=list)
mapped_fields: dict[str, str] = field(default_factory=dict)
evidence_only_segments: list[XfaSplitSegmentResult] = field(default_factory=list)
diagnostics: list[XfaSplitDiagnostic] = field(default_factory=list)
rule_id: str | None = None
rule_version: int | None = None
def _split_text_by_breaks(text: str, line_breaks: list[str]) -> list[str]:
"""
按声明的 line_breaks 切分文本(长分隔符优先)。
Args:
text: 原始文本。
line_breaks: 换行符列表。
Returns:
切分后的行列表(尚未 trim / 去空行)。
"""
if not text:
return []
pattern = '|'.join(re.escape(item) for item in sorted(line_breaks, key=len, reverse=True))
if not pattern:
return [text]
return re.split(pattern, text)
def _apply_line_normalization(
lines: list[str],
*,
trim: bool,
remove_empty_lines: bool,
) -> list[str]:
"""对行列表应用 trim / 去空行。"""
out = list(lines)
if trim:
out = [item.strip() for item in out]
if remove_empty_lines:
out = [item for item in out if item]
return out
def _inventory_lines(raw_value: str, rule_set: XfaSplitRuleSet) -> list[str]:
"""
用规则集级 normalization 生成未匹配行盘点用的行清单。
核心逻辑:尊重 normalization.line_breaks(不再忽略配置)。
"""
norm = rule_set.normalization
lines = _split_text_by_breaks(raw_value or '', list(norm.line_breaks))
return _apply_line_normalization(
lines,
trim=bool(norm.trim),
remove_empty_lines=bool(norm.remove_empty_lines),
)
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()
if not hay.startswith(needle):
return None
rest = text[len(label):]
for sep in stage.separators:
if rest.startswith(sep):
return rest[len(sep):].strip()
stripped = rest.lstrip()
if stripped.startswith(sep):
return stripped[len(sep):].strip()
return None
def _regex_search(text: str, pattern: str, *, case_sensitive: bool) -> re.Match[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。
"""
try:
matched = _regex_search(
text,
str(stage.pattern or ''),
case_sensitive=bool(stage.case_sensitive),
)
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
try:
if group is None:
if matched.lastindex:
return str(matched.group(1) or '').strip(), None
return str(matched.group(0) or '').strip(), None
return str(matched.group(group) or '').strip(), None
except IndexError:
return None, 'regex_failed'
def _run_pipeline(
*,
raw_value: str,
rule: XfaSplitRule,
) -> tuple[str | None, set[int], str, str | None]:
"""
执行单条规则的 stages 流水线。
Returns:
(output_text, claimed_line_numbers, last_stage_type, error_code)
error_code 非空表示流水线失败。
"""
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
def execute_split_rule_set(
*,
raw_value: str,
rule_set: XfaSplitRuleSet,
lines: list[str] | None = None,
) -> XfaSplitEngineResult:
"""
对单个源字段原值执行多阶段拆分规则集。
核心逻辑:
1. 按 order 升序执行每条输出流水线;
2. select_line/select_line_range 认领行号;范围重叠 → duplicate_line_match;
3. 未认领行按 unmatched_line_policy;
4. 同一正式字段多段命中 → needs_review;
5. evidence_only 全部保留。
Args:
raw_value: 保留换行的原始叶子值。
rule_set: 已校验规则集。
lines: 可选预切分行(仅覆盖未匹配盘点;流水线仍从 raw 起步)。
Returns:
XfaSplitEngineResult。
"""
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]] = {}
ordered_rules = sorted(rule_set.rules, key=lambda item: (item.order, item.rule_id))
# [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],
))
continue
assert text is not None
for claimed_line in claimed_lines:
line_claims.setdefault(claimed_line, []).append(rule.rule_id)
status = 'parsed'
if not str(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,
field_code=seg.target_field_code,
rule_ids=[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(),
handling=seg.handling,
target_field_id=seg.target_field_id,
target_field_code=seg.target_field_code,
rule_id=rule.rule_id,
status=status,
matcher_type=last_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] 未匹配行。
for line_index, line in enumerate(inventory, start=1):
if line_index in claimed_lines:
continue
status = 'needs_review' if rule_set.unmatched_line_policy == 'needs_review' else 'parsed'
if status == 'needs_review':
diagnostics.append(XfaSplitDiagnostic(
code='unmatched_line',
message='Unmatched line requires review',
line_no=line_index,
))
segments.append(XfaSplitSegmentResult(
segment_id=f'unmatched-{line_index}',
segment_code=f'unmatched_line_{line_index}',
display_name=f'其他编码/{line_index}',
line_no=line_index,
line_end_no=line_index,
raw_text=line,
normalized_text=line.strip(),
handling='evidence_only',
target_field_id=None,
target_field_code=None,
rule_id='unmatched',
status=status,
matcher_type='unmatched',
))
# [STEP 4] 聚合正式字段。
mapped_fields: dict[str, str] = {}
field_sources: dict[str, list[str]] = {}
overall = 'parsed'
for item in segments:
if item.status == 'needs_review':
overall = 'needs_review'
if item.handling != 'mapped' or not item.target_field_code:
continue
code = item.target_field_code
field_sources.setdefault(code, []).append(item.rule_id)
if code in mapped_fields:
overall = 'needs_review'
diagnostics.append(XfaSplitDiagnostic(
code='same_field_multiple_segment',
message=f'Schema field {code} hit by multiple segments',
field_code=code,
rule_ids=list(field_sources[code]),
))
else:
mapped_fields[code] = item.normalized_text
for _code, sources in field_sources.items():
if len(sources) > 1 and rule_set.same_field_multiple_segment_policy == 'needs_review':
overall = 'needs_review'
if any(d.code == 'duplicate_line_match' for d in diagnostics):
if rule_set.duplicate_match_policy == 'needs_review':
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',
} for d in diagnostics):
overall = 'needs_review'
evidence_only = [item for item in segments if item.handling == 'evidence_only']
return XfaSplitEngineResult(
status=overall,
segments=segments,
mapped_fields=mapped_fields,
evidence_only_segments=evidence_only,
diagnostics=diagnostics,
rule_id=rule_set.rule_id,
rule_version=rule_set.rule_version,
)
def execute_split_on_leaf(
*,
leaf: XfaLeafValue,
rule_set: XfaSplitRuleSet,
) -> XfaSplitEngineResult:
"""
对 XfaLeafValue 执行拆分。
Args:
leaf: 三层中间表示。
rule_set: 规则集。
Returns:
XfaSplitEngineResult。
"""
return execute_split_rule_set(raw_value=leaf.raw_value, rule_set=rule_set)
def project_split_result_safe(
result: XfaSplitEngineResult,
*,
include_full_values: bool = False,
) -> dict[str, Any]:
"""
将引擎结果投影为普通 DTO。
核心逻辑:默认脱敏 mapped/segment 文本;仅当调用方已通过敏感读权限且
include_full_values=True 时返回 raw_text / 完整 mapped 值。
evidence_only_segments 仅作兼容字段;完整列表以 segments 为准。
Args:
result: 引擎输出。
include_full_values: 是否返回完整业务值(需上游权限门禁)。
Returns:
JSON 可序列化 dict。
"""
from app.services.shipping_notice.document_layout.xfa_dataset import mask_value_for_dto
def _text(value: str) -> str:
return str(value) if include_full_values else mask_value_for_dto(value)
mapped = {
code: _text(value)
for code, value in result.mapped_fields.items()
}
return {
'status': result.status,
'rule_id': result.rule_id,
'rule_version': result.rule_version,
'full_values_revealed': bool(include_full_values),
'mapped_fields': mapped,
'segments': [
{
'segment_id': item.segment_id,
'segment_code': item.segment_code,
'display_name': item.display_name,
'line_no': item.line_no,
'line_end_no': item.line_end_no,
'raw_text': _text(item.raw_text),
'normalized_text': _text(item.normalized_text),
'handling': item.handling,
'target_field_id': item.target_field_id,
'target_field_code': item.target_field_code,
'rule_id': item.rule_id,
'status': item.status,
'matcher_type': item.matcher_type,
}
for item in result.segments
],
'evidence_only_segments': [], # 避免与 segments 重复展示;兼容字段置空
'diagnostics': [
{
'code': item.code,
'message': item.message,
'line_no': item.line_no,
'field_code': item.field_code,
'rule_ids': list(item.rule_ids),
}
for item in result.diagnostics
],
}
@@ -0,0 +1,500 @@
"""
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”。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import date, datetime
from decimal import Decimal, InvalidOperation
from typing import Any
from app.services.shipping_notice.document_layout.xfa_acroform import (
XfaAcroformField,
group_acroform_values_by_short_name,
read_acroform_fields,
)
from app.services.shipping_notice.document_layout.xfa_contract import (
OrderXfaDatasetProfile,
sanitize_xfa_dto,
)
from app.services.shipping_notice.document_layout.xfa_dataset import (
XfaDatasetAnalysis,
read_collection_rows,
)
from app.services.shipping_notice.document_layout.xfa_profile_extraction import (
XfaExtractionResult,
_is_formal_ready_split_rule_set,
_resolve_split_source_data_path,
)
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
XfaSplitRuleSet,
parse_split_rule_sets,
)
from app.services.shipping_notice.document_layout.xfa_split_rule_engine import (
execute_split_rule_set,
)
@dataclass
class XfaValidationResult:
"""业务校验汇总;passed=False 时 reason_codes 非空。"""
passed: bool
reason_codes: list[str] = field(default_factory=list)
cross_check_summary: dict[str, Any] = field(default_factory=dict)
def _to_decimal(value: Any) -> Decimal | None:
"""将标准化值转为 Decimal;失败返回 None。"""
if value is None or value == '':
return None
if isinstance(value, Decimal):
return value
if isinstance(value, (int, float)):
return Decimal(str(value))
text = str(value).replace(',', '').strip()
if not text:
return None
try:
return Decimal(text)
except (InvalidOperation, ValueError):
return None
def _normalize_comparable(value: Any, *, value_type: str | None = None) -> str | None:
"""
将 datasets / AcroForm 展示值收敛为可比较的标准化字符串。
核心逻辑:金额去千分位;日期接受 ISO 与 DD/MM/YYYY;数量去尾随零。
"""
if value is None:
return None
text = str(value).strip()
if not text:
return None
lowered_type = str(value_type or '').strip().lower()
# 日期优先:避免把 14/07/2026 误判为数值。
date_patterns = ('%Y-%m-%d', '%Y/%m/%d', '%d/%m/%Y', '%m/%d/%Y', '%d-%m-%Y', '%Y%m%d')
if lowered_type in {'date', 'datetime'} or any(sep in text for sep in ('/', '-')) and text.count('/') + text.count('-') >= 2:
for pattern in date_patterns:
try:
return datetime.strptime(text, pattern).date().isoformat()
except ValueError:
continue
if isinstance(value, date) and not isinstance(value, datetime):
return value.isoformat()
# 数值:覆盖 30 vs 30.000、26,961.6 vs 26961.60。
if lowered_type in {'decimal', 'integer', 'amount', 'quantity', 'unit_price', ''} or any(
ch.isdigit() for ch in text
):
numeric = _to_decimal(text)
if numeric is not None and any(ch.isdigit() for ch in text):
slash_parts = text.replace('.', '/').replace('-', '/').split('/')
if not (len(slash_parts) == 3 and all(part.isdigit() for part in slash_parts if part)):
normalized = numeric.normalize()
if normalized == normalized.to_integral_value():
return str(int(normalized))
rendered = format(normalized, 'f')
if '.' in rendered:
rendered = rendered.rstrip('0').rstrip('.')
return rendered
for pattern in date_patterns:
try:
return datetime.strptime(text, pattern).date().isoformat()
except ValueError:
continue
return text.casefold()
def _field_map_from_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""从提取行中收集 field_code → value 映射(按行)。"""
result: list[dict[str, Any]] = []
for row in rows:
mapping: dict[str, Any] = {}
for item in row.get('fields') or []:
if not isinstance(item, dict):
continue
code = str(item.get('field_code') or '').strip()
if code:
mapping[code] = item.get('value')
result.append(mapping)
return result
def _validate_line_amount_formula(line_maps: list[dict[str, Any]]) -> bool:
"""校验 quantity × unit_price / price_unit == amount。"""
for mapping in line_maps:
quantity = _to_decimal(mapping.get('quantity'))
unit_price = _to_decimal(mapping.get('unit_price'))
amount = _to_decimal(mapping.get('amount'))
if quantity is None or unit_price is None or amount is None:
return False
price_unit = _to_decimal(mapping.get('price_unit')) or Decimal('1')
if price_unit == 0:
return False
expected = (quantity * unit_price) / price_unit
if expected.quantize(Decimal('0.01')) != amount.quantize(Decimal('0.01')):
# 允许未量化的精确相等。
if expected != amount:
return False
return True
def _validate_total_equals_line_sum(
*,
header_fields: list[Any],
line_maps: list[dict[str, Any]],
) -> bool:
"""校验 Header total_amount 与明细 amount 合计一致。"""
total: Decimal | None = None
for item in header_fields:
code = str(getattr(item, 'field_code', '') or '')
if code in {'total_amount', 'order_amount', 'amount'}:
total = _to_decimal(getattr(item, 'normalized_value', None))
break
if total is None:
# Header 未映射总金额时不因缺失阻断(由 required 字段门禁负责)。
return True
line_sum = Decimal('0')
for mapping in line_maps:
amount = _to_decimal(mapping.get('amount'))
if amount is None:
return False
line_sum += amount
return total.quantize(Decimal('0.01')) == line_sum.quantize(Decimal('0.01')) or total == line_sum
def _split_mirror_compare_plan(
profile: OrderXfaDatasetProfile,
) -> tuple[list[XfaSplitRuleSet], set[str], set[str], dict[str, str]]:
"""
构建镜像对账用的拆分规则计划。
Returns:
(formal_rule_sets, split_source_paths, split_field_codes, path_id_to_data_path)
"""
authoritative_path = profile.source_contract.authoritative_line_collection_path.rstrip('/')
rule_sets = [
item for item in parse_split_rule_sets(profile.split_rules or [])
if _is_formal_ready_split_rule_set(item)
and (
item.source_data_path is None
or str(item.source_data_path).startswith(f'{authoritative_path}/')
)
]
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
}
split_source_paths: set[str] = set()
split_field_codes: set[str] = set()
line_fields = list(profile.line_mapping.fields)
for rule_set in rule_sets:
data_path = _resolve_split_source_data_path(
rule_set,
line_fields=line_fields,
path_id_to_data_path=path_id_to_data_path,
)
if data_path:
split_source_paths.add(data_path)
for rule in rule_set.rules:
if rule.segment.handling == 'mapped' and rule.segment.target_field_code:
split_field_codes.add(str(rule.segment.target_field_code))
return rule_sets, split_source_paths, split_field_codes, path_id_to_data_path
def _validate_mirror_collections(
*,
profile: OrderXfaDatasetProfile,
dataset_analysis: XfaDatasetAnalysis,
line_field_paths: dict[str, str],
) -> tuple[bool, str]:
"""
镜像集合存在时,按字段标准化结果逐行对比权威集合。
核心逻辑:有 split_rules 时,对拆分覆盖字段比较引擎 mapped 值而非整段 raw;
evidence_only 段不参与镜像不一致判定。
Args:
profile: 已校验 XFA definition。
dataset_analysis: datasets 分析。
line_field_paths: field_code → data_path(权威集合路径形态)。
Returns:
(hard_ok, status):status 为 matched|mismatched|skipped|unavailable。
hard_ok=False 仅当存在镜像且内容不一致。
"""
if profile.cross_checks.mirror_collection_policy != 'must_match_when_present':
return True, 'skipped'
mirrors = list(profile.source_contract.mirror_collection_paths or [])
if not mirrors:
return True, 'skipped'
auth_rows = read_collection_rows(
dataset_analysis,
profile.source_contract.authoritative_line_collection_path,
)
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)
present_count = 0
for mirror_path in mirrors:
mirror_rows = read_collection_rows(dataset_analysis, mirror_path)
if not mirror_rows:
# 镜像集合不存在:must_match_when_present 可接受,但不得记 matched。
continue
present_count += 1
if len(mirror_rows) != len(auth_rows):
return False, 'mismatched'
for auth_row, mirror_row in zip(auth_rows, mirror_rows):
for field_code, auth_path in line_field_paths.items():
if field_code in split_field_codes or auth_path in split_source_paths:
continue
suffix = auth_path[len(profile.source_contract.authoritative_line_collection_path):]
mirror_field_path = f'{mirror_path}{suffix}'
left = _normalize_comparable(auth_row.get(auth_path))
right = _normalize_comparable(mirror_row.get(mirror_field_path))
if left != right:
return False, 'mismatched'
for rule_set in formal_rule_sets:
auth_source_path = _resolve_split_source_data_path(
rule_set,
line_fields=line_fields,
path_id_to_data_path=path_id_to_data_path,
)
if not auth_source_path:
continue
suffix = auth_source_path[len(profile.source_contract.authoritative_line_collection_path):]
mirror_source_path = f'{mirror_path}{suffix}'
auth_result = execute_split_rule_set(
raw_value=auth_row.get(auth_source_path) or '',
rule_set=rule_set,
)
mirror_result = execute_split_rule_set(
raw_value=mirror_row.get(mirror_source_path) or '',
rule_set=rule_set,
)
for field_code in auth_result.mapped_fields:
left = _normalize_comparable(auth_result.mapped_fields.get(field_code))
right = _normalize_comparable(mirror_result.mapped_fields.get(field_code))
if left != right:
return False, 'mismatched'
if present_count == 0:
return True, 'unavailable'
return True, 'matched'
def _acroform_values_by_local_name(fields: list[XfaAcroformField]) -> dict[str, list[str]]:
"""按短名建立 AcroForm 多实例值列表(委托 xfa_acroform)。"""
return group_acroform_values_by_short_name(fields)
def _dataset_line_values_by_mapping(
*,
extraction: XfaExtractionResult,
mapping_field_code: str,
) -> list[Any]:
"""按提取行顺序收集某一 line mapping 的标准化值列表。"""
values: list[Any] = []
for row in extraction.rows:
row_value = None
for item in row.get('fields') or []:
if isinstance(item, dict) and str(item.get('field_code') or '') == mapping_field_code:
row_value = item.get('value')
break
values.append(row_value)
return values
def _validate_acroform(
*,
profile: OrderXfaDatasetProfile,
extraction: XfaExtractionResult,
pdf_bytes: bytes | None,
) -> tuple[bool, str]:
"""
对账 datasets 标准化值与 AcroForm 展示值(表头单值 + 明细按行对齐)。
核心逻辑:
- 允许展示格式不同,标准化后必须相同;
- 明细按 AcroForm 同名多实例下标与提取行一一对应,禁止“全行扫到首个 field_code”;
- 无 Fields / 无重叠字段 → unavailable;仅部分字段可对 → partial;冲突 → mismatched。
Returns:
(hard_ok, status):hard_ok=False 仅 mismatched;其余状态不阻断正式提取硬失败,
由 CQ 决定是否允许自动建单。
"""
if not profile.cross_checks.acroform_enabled:
return True, 'skipped'
if not pdf_bytes:
return True, 'unavailable'
acro_fields = read_acroform_fields(pdf_bytes)
if not acro_fields:
return True, 'unavailable'
by_name = _acroform_values_by_local_name(acro_fields)
compared = 0
mismatched = 0
missing_counterpart = 0
# [STEP 1] Header:每个映射对应短名的首个 AcroForm 实例。
for mapping in profile.header_mappings:
local = mapping.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:
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)
if left is None or right is None:
missing_counterpart += 1
continue
compared += 1
if left != right:
mismatched += 1
# [STEP 2] Line:按行索引对齐同名多实例 Widget。
for mapping in profile.line_mapping.fields:
local = mapping.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,
)
if not dataset_values:
continue
if not acro_values:
missing_counterpart += len(dataset_values)
continue
for row_index, dataset_value in enumerate(dataset_values):
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)
if left is None or right is None:
missing_counterpart += 1
continue
compared += 1
if left != right:
mismatched += 1
if mismatched > 0:
return False, 'mismatched'
if compared == 0:
return True, 'unavailable'
if missing_counterpart > 0:
return True, 'partial'
return True, 'matched'
def validate_xfa_extraction(
*,
raw_profile: dict[str, Any],
dataset_analysis: XfaDatasetAnalysis,
extraction: XfaExtractionResult,
pdf_bytes: bytes | None = None,
) -> XfaValidationResult:
"""
执行 XFA 提取后的确定性业务校验。
核心逻辑(任一失败即 fail-closed):
1. 镜像集合标准化一致性;
2. AcroForm 关键字段标准化一致性;
3. 明细金额公式 quantity×unit_price;
4. Header 总金额与明细合计。
Args:
raw_profile: 冻结 Profile 快照。
dataset_analysis: datasets 分析。
extraction: 提取结果。
pdf_bytes: 可选原始 PDF,用于 AcroForm 对账。
Returns:
XfaValidationResult。
"""
definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {}
try:
profile = OrderXfaDatasetProfile.model_validate(definition)
except (TypeError, ValueError):
return XfaValidationResult(
passed=False,
reason_codes=['xfa_definition_invalid'],
cross_check_summary={'status': 'failed'},
)
reason_codes: list[str] = []
line_field_paths = {
item.field_code: item.data_path for item in profile.line_mapping.fields
}
summary: dict[str, Any] = {
'mirror_collection_policy': profile.cross_checks.mirror_collection_policy,
'acroform_enabled': profile.cross_checks.acroform_enabled,
'line_amount_formula': profile.cross_checks.line_amount_formula,
'total_amount_policy': profile.cross_checks.total_amount_policy,
}
# [STEP 1] 镜像集合
mirror_ok, mirror_status = _validate_mirror_collections(
profile=profile,
dataset_analysis=dataset_analysis,
line_field_paths=line_field_paths,
)
if not mirror_ok:
reason_codes.append('xfa_mirror_collection_mismatch')
summary['mirror_status'] = mirror_status
# [STEP 2] AcroForm(按行对齐;状态含 matched/partial/unavailable)
acro_ok, acro_status = _validate_acroform(
profile=profile,
extraction=extraction,
pdf_bytes=pdf_bytes,
)
if not acro_ok:
reason_codes.append('xfa_acroform_mismatch')
summary['acroform_status'] = acro_status
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):
reason_codes.append('xfa_business_validation_failed')
summary['line_amount_status'] = 'failed'
else:
summary['line_amount_status'] = 'passed'
else:
summary['line_amount_status'] = 'skipped'
# [STEP 4] Header 总计
if profile.cross_checks.total_amount_policy == 'must_equal_line_sum':
if not _validate_total_equals_line_sum(
header_fields=extraction.header_fields,
line_maps=line_maps,
):
if 'xfa_business_validation_failed' not in reason_codes:
reason_codes.append('xfa_business_validation_failed')
summary['total_amount_status'] = 'failed'
else:
summary['total_amount_status'] = 'passed'
else:
summary['total_amount_status'] = 'skipped'
return XfaValidationResult(
passed=not reason_codes,
reason_codes=reason_codes,
cross_check_summary=sanitize_xfa_dto(summary),
)