feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程
清理废弃的shipping xfa ocr automark相关代码和job配置 新增收料报表管理的前端页面、路由和侧边栏入口 新增后端收料报表配置接口、数据库模型和RPA脚本 优化发货通知流程的重试策略,将shipping相关job默认不自动重试 移除废弃的库存源确认相关逻辑,更新流程门禁规则 重构订单模板的值适配器模块,新增坐标OCR值适配器 清理前端shipping菜单和action的废弃选项 更新相关文档和测试用例,调整.gitignore忽略规则
This commit is contained in:
1 parent
260465b72d
commit
1b6483a4ea
466 files changed
+32115
-33796
No files matched your search
@@ -54,10 +54,11 @@ ON_DEMAND_COORDINATE_COMPACTION_ISSUES = frozenset({
|
||||
|
||||
|
||||
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'
|
||||
"""判断布局快照是否可直接使用,或可由原 PDF 在订单识别时按需恢复。
|
||||
|
||||
所有 PDF 一律以共同坐标证据判断;没有视觉 Layout 的历史快照会安全重解析,
|
||||
不能因其曾携带某个值源 capability 而被当成可复用的业务路径。
|
||||
"""
|
||||
if Path(str(document.filename or '')).suffix.lower() != '.pdf':
|
||||
return True
|
||||
evidence = payload.get('coordinate_evidence') if isinstance(payload.get('coordinate_evidence'), dict) else {}
|
||||
@@ -209,6 +210,99 @@ def current_layout_snapshot(document: ShippingOrderDocument) -> dict[str, Any] |
|
||||
return dict(version.payload_json)
|
||||
|
||||
|
||||
def _bind_inline_xfa_structure_analysis(
|
||||
*,
|
||||
document: ShippingOrderDocument,
|
||||
version: ShippingDocumentLayoutVersion,
|
||||
) -> None:
|
||||
"""本地化派生 Layout 的 XFA Analysis,禁止新快照引用旧 Layout 的分析主键。
|
||||
|
||||
坐标/OCR 补证会从现有 Layout 派生一个新版本。XFA Analysis 是
|
||||
``document_id + layout_version_id`` 共同冻结的正式值源证据,不能把旧版本的
|
||||
``structure_analysis_id`` 原样带到新版本;否则样本重新冻结时会因身份不一致
|
||||
fail-closed。首次写入(Analysis 尚未绑定 Layout)只回填本身,派生写入则
|
||||
克隆安全摘要并将新 ID 写回该 Layout。
|
||||
"""
|
||||
payload = version.payload_json if isinstance(version.payload_json, dict) else {}
|
||||
capability = payload.get('xfa_capability') if isinstance(payload.get('xfa_capability'), dict) else {}
|
||||
raw_analysis_id = capability.get('structure_analysis_id')
|
||||
if raw_analysis_id in (None, ''):
|
||||
return
|
||||
try:
|
||||
analysis = db.session.get(ShippingXfaStructureAnalysis, int(raw_analysis_id))
|
||||
except (TypeError, ValueError):
|
||||
return
|
||||
if analysis is None or int(analysis.document_id) != int(document.id):
|
||||
return
|
||||
if str(analysis.analysis_status or '') != 'ready':
|
||||
return
|
||||
if str(analysis.source_content_hash or '').lower() != str(document.content_hash or '').lower():
|
||||
return
|
||||
if analysis.layout_version_id in (None, ''):
|
||||
analysis.layout_version_id = int(version.id)
|
||||
return
|
||||
if int(analysis.layout_version_id) == int(version.id):
|
||||
return
|
||||
|
||||
# [STEP 1] 派生 Layout 不能窃取旧 Analysis 的 Layout 身份;复制的仅是脱敏结构摘要。
|
||||
localized = ShippingXfaStructureAnalysis(
|
||||
document_id=int(document.id),
|
||||
layout_version_id=int(version.id),
|
||||
source_content_hash=str(document.content_hash or '').lower(),
|
||||
document_kind=analysis.document_kind,
|
||||
analysis_status='ready',
|
||||
template_packet_checksum=analysis.template_packet_checksum,
|
||||
datasets_packet_checksum=analysis.datasets_packet_checksum,
|
||||
dataset_structure_fingerprint=analysis.dataset_structure_fingerprint,
|
||||
packet_checksums_json=dict(analysis.packet_checksums_json or {}),
|
||||
stats_json=dict(analysis.stats_json or {}),
|
||||
security_summary_json=dict(analysis.security_summary_json or {}),
|
||||
tree_summary_json=dict(analysis.tree_summary_json or {}),
|
||||
error_code=None,
|
||||
route_reason=analysis.route_reason,
|
||||
encrypted_snapshot_ref=None,
|
||||
parser_identity=analysis.parser_identity,
|
||||
contract_version=analysis.contract_version,
|
||||
finished_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(localized)
|
||||
db.session.flush()
|
||||
|
||||
# [STEP 2] 重算 checksum,保证 Layout 载荷和结构分析 ID 仍是同一不可变身份。
|
||||
localized_capability = dict(capability)
|
||||
localized_capability['structure_analysis_id'] = int(localized.id)
|
||||
localized_payload = dict(payload)
|
||||
localized_payload['xfa_capability'] = localized_capability
|
||||
if isinstance(localized_payload.get('capability'), dict):
|
||||
localized_payload['capability'] = {
|
||||
**dict(localized_payload['capability']),
|
||||
'structure_analysis_id': int(localized.id),
|
||||
}
|
||||
checksum, payload_size = canonical_layout_payload(localized_payload)
|
||||
version.payload_json = localized_payload
|
||||
version.payload_checksum = checksum
|
||||
version.payload_size_bytes = payload_size
|
||||
version.quality_json = (
|
||||
dict(localized_payload['capability'])
|
||||
if isinstance(localized_payload.get('capability'), dict) else version.quality_json
|
||||
)
|
||||
|
||||
|
||||
def ensure_inline_xfa_structure_analysis_identity(
|
||||
*,
|
||||
document: ShippingOrderDocument,
|
||||
version: ShippingDocumentLayoutVersion,
|
||||
) -> ShippingDocumentLayoutVersion:
|
||||
"""确保当前 inline Layout 的 XFA Analysis 与其自身版本号一致。
|
||||
|
||||
Profile 冻结会直接读取当前 ready Layout;历史坐标补证版本即使已存在,也必须
|
||||
在该正式冻结边界完成 analysis identity 本地化,不能依赖再次生成同一快照。
|
||||
"""
|
||||
if str(version.status or '') in CURRENT_LAYOUT_STATUSES:
|
||||
_bind_inline_xfa_structure_analysis(document=document, version=version)
|
||||
return version
|
||||
|
||||
|
||||
def record_inline_layout_snapshot(
|
||||
document: ShippingOrderDocument,
|
||||
snapshot: dict[str, Any],
|
||||
@@ -248,6 +342,9 @@ def record_inline_layout_snapshot(
|
||||
)
|
||||
if existing is not None:
|
||||
if existing.status in CURRENT_LAYOUT_STATUSES:
|
||||
# 历史坐标补证快照可能在 XFA Analysis 身份本地化修复前已经落库;
|
||||
# 复用时补齐同一 Layout 的 Analysis,避免冻结样本永久卡在旧 identity。
|
||||
ensure_inline_xfa_structure_analysis_identity(document=document, version=existing)
|
||||
document.current_layout_version_id = existing.id
|
||||
return existing
|
||||
|
||||
@@ -289,6 +386,8 @@ def record_inline_layout_snapshot(
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
if status in CURRENT_LAYOUT_STATUSES:
|
||||
ensure_inline_xfa_structure_analysis_identity(document=document, version=version)
|
||||
if status in CURRENT_LAYOUT_STATUSES:
|
||||
document.current_layout_version_id = version.id
|
||||
return version
|
||||
@@ -411,7 +510,11 @@ def _clone_reusable_layout_for_document(
|
||||
target_analysis: ShippingXfaStructureAnalysis | None = None
|
||||
source_analysis: ShippingXfaStructureAnalysis | None = None
|
||||
reject_reason: str | None = None
|
||||
if str(copied_payload.get('provider') or '') == 'xfa':
|
||||
# XFA structure analysis is document-scoped evidence. Both the retired
|
||||
# XFA-only snapshot format and the current shared visual Layout carry it in
|
||||
# xfa_capability, so reuse must localize it by capability rather than by
|
||||
# the layout provider.
|
||||
if isinstance(copied_payload.get('xfa_capability'), dict):
|
||||
capability = (
|
||||
copied_payload.get('xfa_capability')
|
||||
if isinstance(copied_payload.get('xfa_capability'), dict)
|
||||
|
||||
@@ -38,7 +38,7 @@ class OrderFieldExtraction(BaseModel):
|
||||
scope: Literal['header']
|
||||
value: Any = None
|
||||
status: Literal['confirmed', 'needs_review', 'unavailable']
|
||||
source: Literal['pdf_coordinate', 'ocr_coordinate'] | None = None
|
||||
source: Literal['pdf_coordinate', 'ocr_coordinate', 'acroform_widget'] | None = None
|
||||
page_no: int | None = Field(default=None, ge=1)
|
||||
anchor_bbox: LayoutBBox | None = None
|
||||
value_bbox: LayoutBBox | None = None
|
||||
@@ -48,7 +48,7 @@ class OrderFieldExtraction(BaseModel):
|
||||
|
||||
def extract_order_fields(
|
||||
*, profile: OrderCoordinateProfile, schema_fields: dict[str, dict[str, Any]],
|
||||
coordinate_evidence: dict[str, Any],
|
||||
coordinate_evidence: dict[str, Any], allow_ocr_preview_fallback: bool = False,
|
||||
) -> list[OrderFieldExtraction]:
|
||||
"""
|
||||
用唯一文字锚点和相对值区读取订单字段,缺少页级证据时严格失败关闭。
|
||||
@@ -57,18 +57,26 @@ def extract_order_fields(
|
||||
profile: Run 冻结的坐标模板,不得包含待重新绑定字段。
|
||||
schema_fields: 以 stable field_id 为键的冻结启用 Schema 字段。
|
||||
coordinate_evidence: 冻结页尺寸、page_glyphs 与来源;不接受表格内 glyph 兜底。
|
||||
allow_ocr_preview_fallback: 仅管理端视觉样本值预览可启用。它允许已确认的
|
||||
PDF 坐标字段临时读取 OCR 候选,但结果仍固定为 needs_review,不能用于正式运行时取值。
|
||||
|
||||
Returns:
|
||||
每个已绑定布局对应一个候选,按模板声明顺序返回。
|
||||
"""
|
||||
return [
|
||||
_extract_layout(layout=layout, schema_fields=schema_fields, coordinate_evidence=coordinate_evidence)
|
||||
_extract_layout(
|
||||
layout=layout,
|
||||
schema_fields=schema_fields,
|
||||
coordinate_evidence=coordinate_evidence,
|
||||
allow_ocr_preview_fallback=allow_ocr_preview_fallback,
|
||||
)
|
||||
for layout in profile.order_field_layouts
|
||||
]
|
||||
|
||||
|
||||
def _extract_layout(
|
||||
*, layout: OrderFieldLayout, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any],
|
||||
allow_ocr_preview_fallback: bool = False,
|
||||
) -> OrderFieldExtraction:
|
||||
"""处理一个订单字段布局,并把任何不确定性保留为 Review/Unavailable 而非猜测。"""
|
||||
config = schema_fields.get(layout.field_id)
|
||||
@@ -104,7 +112,12 @@ def _extract_layout(
|
||||
|
||||
results: list[OrderFieldExtraction] = []
|
||||
for page_no, glyphs, width, height, source in candidates:
|
||||
if not _source_allowed(layout, config=config, source=source):
|
||||
if not _source_allowed(
|
||||
layout,
|
||||
config=config,
|
||||
source=source,
|
||||
allow_ocr_preview_fallback=allow_ocr_preview_fallback,
|
||||
):
|
||||
results.append(_unavailable(layout, 'order_field_coordinate_source_not_allowed', page_no=page_no, source=source))
|
||||
continue
|
||||
if layout.anchor is None:
|
||||
@@ -441,8 +454,16 @@ def _layout_applies_to_page(layout: OrderFieldLayout, page_no: int) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _source_allowed(layout: OrderFieldLayout, *, config: dict[str, Any], source: str) -> bool:
|
||||
"""同时满足布局和 Schema 的坐标来源授权,OCR 永远不提升为 confirmed。"""
|
||||
def _source_allowed(
|
||||
layout: OrderFieldLayout,
|
||||
*,
|
||||
config: dict[str, Any],
|
||||
source: str,
|
||||
allow_ocr_preview_fallback: bool = False,
|
||||
) -> bool:
|
||||
"""同时满足布局和 Schema 的坐标来源授权;仅样本预览可临时展示 OCR 候选。"""
|
||||
if source == 'ocr_coordinate' and allow_ocr_preview_fallback:
|
||||
return True
|
||||
allowed = set(config.get('allowed_sources') or [])
|
||||
if source not in allowed:
|
||||
return False
|
||||
|
||||
@@ -254,6 +254,11 @@ class TableRegionProfile(OrderProfileModel):
|
||||
line_start_field_code: str = Field(default='customer_po_line_no', pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
# 默认沿用既有固定物理子行;自适应模式仅在模板显式选择时允许字段跨视觉行匹配。
|
||||
row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns'] = 'fixed_subrows'
|
||||
# 人工确认本表区自动标注时采用的视觉几何来源;仅用于审计、盲测和冲突复核,
|
||||
# 不参与普通 PDF/XFA 的正式字段取值,更不能替代 XFA datasets。
|
||||
visual_evidence_source: Literal[
|
||||
'pdf_coordinate', 'ocr_coordinate', 'opencv_geometry', 'acroform_widget_geometry',
|
||||
] | None = None
|
||||
header_layouts: list[HeaderLayout] = Field(default_factory=list)
|
||||
line_layouts: list[LineLayout] = Field(default_factory=list)
|
||||
continuation_rule: ContinuationRule = Field(default_factory=ContinuationRule)
|
||||
|
||||
@@ -4,7 +4,8 @@ services/shipping_notice/document_layout/order_profile_extractors.py
|
||||
用途:执行订单坐标 Profile v2 的有限注册字段解析器。
|
||||
依赖:订单料号复合解析与数值解析。
|
||||
逻辑:坐标重建先取得管理员框选的原文,本模块再将其安全拆成固定业务字段;任何拆分失败均不返回部分字段。
|
||||
另提供 XFA/坐标共用的 ``unit_price / price_unit``(如 ``898.72 / 1``)确定性拆分。
|
||||
单价、价格单位等业务字段必须由管理员分别框选,或通过 XFA 显式拆分规则映射;
|
||||
本模块不按值形态隐式生成 Schema 字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,44 +20,9 @@ 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()
|
||||
@@ -92,8 +58,6 @@ 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 {}
|
||||
|
||||
|
||||
@@ -109,6 +73,4 @@ 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()
|
||||
@@ -672,24 +672,11 @@ def _observe_layout_features(
|
||||
if width > 0 and height > 0:
|
||||
aspect_ratio = width / height
|
||||
|
||||
primary_bbox = None
|
||||
if tables:
|
||||
bbox = tables[0].get('bbox') if isinstance(tables[0].get('bbox'), dict) else None
|
||||
if isinstance(bbox, dict):
|
||||
try:
|
||||
primary_bbox = [
|
||||
float(bbox.get('x0', 0)), float(bbox.get('y0', 0)),
|
||||
float(bbox.get('x1', 1)), float(bbox.get('y1', 1)),
|
||||
]
|
||||
if max(primary_bbox) > 1 and isinstance(first_page, dict):
|
||||
page_width, page_height = float(first_page.get('width') or 0), float(first_page.get('height') or 0)
|
||||
if page_width > 0 and page_height > 0:
|
||||
primary_bbox = [
|
||||
primary_bbox[0] / page_width, primary_bbox[1] / page_height,
|
||||
primary_bbox[2] / page_width, primary_bbox[3] / page_height,
|
||||
]
|
||||
except (TypeError, ValueError):
|
||||
primary_bbox = None
|
||||
# [STEP 1] 与签名生成一致,按签名表区选择实际业务表;MinerU 的 tables[0]
|
||||
# 可能是抬头/元数据表,不能作为运行时默认主表。
|
||||
primary_bbox = _select_signature_primary_table_bbox(
|
||||
tables=tables, pages=pages, signature=signature,
|
||||
)
|
||||
|
||||
header_tokens, column_centers, column_width_ratios = _observe_primary_table_header(
|
||||
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
|
||||
@@ -712,6 +699,60 @@ def _observe_layout_features(
|
||||
}
|
||||
|
||||
|
||||
def _select_signature_primary_table_bbox(
|
||||
*, tables: list[dict[str, Any]], pages: dict[str, Any], signature: dict[str, Any] | None,
|
||||
) -> list[float] | None:
|
||||
"""按签名表区选取重叠最大的实际表;无可用签名时才保持首表兼容行为。"""
|
||||
normalized_tables: list[list[float]] = []
|
||||
for table in tables:
|
||||
page = pages.get(str(table.get('page_no') or 1)) or pages.get(table.get('page_no') or 1)
|
||||
bbox = table.get('bbox') if isinstance(table.get('bbox'), dict) else None
|
||||
if not isinstance(page, dict) or not isinstance(bbox, dict):
|
||||
continue
|
||||
try:
|
||||
raw = [float(bbox[key]) for key in ('x0', 'y0', 'x1', 'y1')]
|
||||
width, height = float(page.get('width') or 0), float(page.get('height') or 0)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if raw[2] <= raw[0] or raw[3] <= raw[1] or width <= 0 or height <= 0:
|
||||
continue
|
||||
normalized_tables.append(raw if max(raw) <= 1 else [
|
||||
raw[0] / width, raw[1] / height, raw[2] / width, raw[3] / height,
|
||||
])
|
||||
if not normalized_tables:
|
||||
return None
|
||||
patterns = [
|
||||
item for item in ((signature or {}).get('table_patterns') or [])
|
||||
if isinstance(item, dict)
|
||||
and isinstance(item.get('bbox'), dict)
|
||||
and isinstance(item['bbox'].get('median'), list)
|
||||
and len(item['bbox']['median']) == 4
|
||||
]
|
||||
if not patterns:
|
||||
return normalized_tables[0]
|
||||
best_bbox = normalized_tables[0]
|
||||
best_overlap = -1.0
|
||||
for candidate in normalized_tables:
|
||||
for pattern in patterns:
|
||||
try:
|
||||
expected = [float(value) for value in pattern['bbox']['median']]
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
overlap = _bbox_overlap(expected, candidate)
|
||||
if overlap > best_overlap:
|
||||
best_overlap, best_bbox = overlap, candidate
|
||||
return best_bbox
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
_HEADER_TOKEN_SPLIT = re.compile(r'[\s|/]+')
|
||||
|
||||
|
||||
|
||||
@@ -43,53 +43,6 @@ 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
|
||||
@@ -124,16 +77,6 @@ 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:
|
||||
_record_xfa_page_count(xfa_snapshot, diagnostics=diagnostics)
|
||||
return xfa_snapshot
|
||||
native_pages: list[Any] | None = None
|
||||
if extension == '.pdf' and document_id and content_hash:
|
||||
try:
|
||||
@@ -408,32 +351,6 @@ def _diagnostics_from_maps(
|
||||
)
|
||||
|
||||
|
||||
def _record_xfa_page_count(
|
||||
snapshot: dict[str, Any],
|
||||
*,
|
||||
diagnostics: LayoutJobDiagnostics | None,
|
||||
) -> None:
|
||||
"""
|
||||
XFA 早退路径仅回填可安全取得的 page_count,不引入 OCR/OpenCV 逻辑。
|
||||
|
||||
Args:
|
||||
snapshot: XFA layout 快照。
|
||||
diagnostics: 可选诊断上下文。
|
||||
"""
|
||||
if diagnostics is None:
|
||||
return
|
||||
capability = snapshot.get('xfa_capability') if isinstance(snapshot.get('xfa_capability'), dict) else {}
|
||||
page_count = capability.get('page_count')
|
||||
if page_count is None:
|
||||
pages = snapshot.get('pages')
|
||||
if isinstance(pages, list):
|
||||
page_count = len(pages)
|
||||
try:
|
||||
diagnostics.counts['page_count'] = int(page_count or 0)
|
||||
except (TypeError, ValueError):
|
||||
diagnostics.counts['page_count'] = 0
|
||||
|
||||
|
||||
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,
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/shipping_notice/document_layout/xfa_acroform.py
|
||||
|
||||
用途:读取 AcroForm 字段值/Widget 几何,并生成与 datasets 叶子节点的对账与路径候选。
|
||||
依赖:pypdf、xfa_dataset.XfaDatasetAnalysis、xfa_contract.hash_data_path。
|
||||
逻辑:由 xfa_analysis、xfa_visual_binding、xfa_validation 调用;按短名聚合多实例值
|
||||
逻辑:由 xfa_analysis、datasets 末端映射和 xfa_validation 调用;按短名聚合多实例值
|
||||
供行对齐对账;Widget 摘要含页码与归一化 bbox,供统一视觉绑定评分。
|
||||
"""
|
||||
|
||||
|
||||
@@ -307,6 +307,23 @@ def persist_xfa_structure_analysis(
|
||||
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)
|
||||
# [STEP 2] Layout 与 datasets identity 必须落在同一冻结快照;仅更新 outcome
|
||||
# 会导致后续 Profile/盲测按 Layout 重放时找不到本次 structure analysis。
|
||||
if layout_version_id:
|
||||
layout_version = db.session.get(ShippingDocumentLayoutVersion, int(layout_version_id))
|
||||
if layout_version is not None:
|
||||
payload = dict(layout_version.payload_json or {})
|
||||
capability_payload = payload.get('xfa_capability')
|
||||
if not isinstance(capability_payload, dict):
|
||||
capability_payload = dict(payload.get('capability') or {})
|
||||
capability_payload['structure_analysis_id'] = int(record.id)
|
||||
payload['xfa_capability'] = capability_payload
|
||||
if isinstance(payload.get('capability'), dict):
|
||||
payload['capability'] = {
|
||||
**dict(payload['capability']),
|
||||
'structure_analysis_id': int(record.id),
|
||||
}
|
||||
layout_version.payload_json = payload
|
||||
outcome.analysis_record = record
|
||||
return record
|
||||
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
services/shipping_notice/document_layout/xfa_contract.py
|
||||
|
||||
用途:冻结 XFA 数据路径 Profile 契约——template_mode、受控路径语法、结构指纹、
|
||||
统一字段 binding(value_binding + visual_binding)、鉴别联合 definition、
|
||||
统一字段 binding(共同视觉 field_layout_id + value_binding)、鉴别联合 definition、
|
||||
evidence 与安全投影、合成预览审计事件与错误码注册。
|
||||
依赖:Pydantic 2、标准库 hashlib/json/re/unicodedata;被 order_extraction_route_contract、
|
||||
Profile 校验、拆分契约、xfa_preview_* 与后续 xfa_*.py 解析器引用。
|
||||
逻辑:本模块只定义契约与纯函数校验,不读 PDF/XML、不执行脚本、不接正式流量;
|
||||
禁止混入 coordinate 表区键,但允许 visual_binding 归一化框作为视觉证据。
|
||||
共同视觉布局与末端 datasets 映射分层,历史 visual_binding 仅兼容读取。
|
||||
header_mappings / line_mapping.fields 仅作**迁移输入**解析(order_profile_unified_migration);
|
||||
正式 validate/save/extract 须 bindings-only,legacy-only 或 dual-source 均 fail-closed。
|
||||
"""
|
||||
@@ -28,9 +28,9 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_valida
|
||||
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'
|
||||
# Historical ``xfa_structure_signature`` Run records remain readable through the
|
||||
# ORM enum/migration compatibility path. New code must use the common
|
||||
# ``layout_signature`` lifecycle and must not introduce a second XFA signature.
|
||||
|
||||
OrderProfileTemplateMode = Literal['coordinate', 'xfa_dataset']
|
||||
ORDER_PROFILE_TEMPLATE_MODES: Final[frozenset[str]] = frozenset({
|
||||
@@ -144,12 +144,6 @@ XFA_ERROR_CODES: Final[frozenset[str]] = frozenset({
|
||||
'XFA_SPLIT_RULE_INVALID',
|
||||
'XFA_SPLIT_FIELD_CONFLICT',
|
||||
'XFA_SPLIT_MIRROR_MISMATCH',
|
||||
# 合成预览(阶段 1 POC)
|
||||
'XFA_PREVIEW_STALE',
|
||||
'XFA_PREVIEW_FAILED',
|
||||
'XFA_PREVIEW_UNAVAILABLE',
|
||||
'XFA_PREVIEW_PAGE_INCONSISTENT',
|
||||
'XFA_PREVIEW_VALUE_MISMATCH',
|
||||
})
|
||||
|
||||
XFA_ROUTE_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
@@ -176,22 +170,13 @@ XFA_ROUTE_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_split_field_conflict',
|
||||
'xfa_split_mirror_mismatch',
|
||||
# 统一视觉绑定 / 发布门禁 / 运行时再验(阶段 5–6)
|
||||
'xfa_visual_bindings_required',
|
||||
'xfa_visual_binding_incomplete',
|
||||
'xfa_mapping_required',
|
||||
'xfa_visual_coverage_insufficient',
|
||||
'xfa_evidence_retention_insufficient',
|
||||
'xfa_mirror_consistency_insufficient',
|
||||
'xfa_profile_checksum_mismatch',
|
||||
'xfa_visual_not_publishable',
|
||||
'xfa_split_rule_unconfirmed',
|
||||
# 合成预览发布门禁(阶段 5)
|
||||
'xfa_synthetic_preview_not_ready',
|
||||
'xfa_preview_render_checksum_missing',
|
||||
'xfa_preview_pages_incomplete',
|
||||
'xfa_preview_page_box_invalid',
|
||||
'xfa_ocr_unresolved_mismatch',
|
||||
'xfa_preview_checksum_drift',
|
||||
'xfa_preview_renderer_version_mismatch',
|
||||
})
|
||||
|
||||
XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
@@ -221,11 +206,6 @@ XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_cross_check_completed',
|
||||
'xfa_structure_signature_frozen',
|
||||
'xfa_audit_snapshot_viewed',
|
||||
# 统一视觉绑定(阶段 2)
|
||||
'xfa_visual_binding_suggested',
|
||||
'xfa_visual_binding_confirmed',
|
||||
'xfa_visual_binding_rejected',
|
||||
'xfa_visual_binding_updated',
|
||||
# 字段拆分映射审计(阶段 3/7)
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_split_rule_previewed',
|
||||
@@ -235,26 +215,16 @@ XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'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_value_adapter_extracted',
|
||||
'profile_value_adapter_needs_review',
|
||||
# 统一 binding 一次性迁移(阶段 7)
|
||||
'order_profile_unified_migration_dry_run',
|
||||
'order_profile_unified_migration_executed',
|
||||
# 合成预览(阶段 1 POC)
|
||||
'xfa_preview_requested',
|
||||
'xfa_preview_generated',
|
||||
'xfa_preview_failed',
|
||||
'xfa_preview_viewed',
|
||||
'xfa_preview_stale',
|
||||
# OCR 自动标记建议(阶段 3)
|
||||
'xfa_ocr_started',
|
||||
'xfa_ocr_completed',
|
||||
'xfa_ocr_failed',
|
||||
})
|
||||
|
||||
# Profile / Run / 分析 DTO 禁止键(大小写不敏感);完整 XML / PDF bytes / 存储地址不得外泄。
|
||||
@@ -314,22 +284,29 @@ class XfaContractModel(BaseModel):
|
||||
|
||||
|
||||
class XfaSourceContract(XfaContractModel):
|
||||
"""冻结 XFA 模板结构身份:packet checksum + 结构指纹 + 权威集合路径。"""
|
||||
"""冻结 XFA 模板结构身份;权威集合在草稿的末端值映射阶段才配置。"""
|
||||
|
||||
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)
|
||||
authoritative_line_collection_path: str | None = Field(default=None, 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:
|
||||
"""校验必填受控路径语法。"""
|
||||
"""校验 datasets 根路径语法。"""
|
||||
return validate_controlled_data_path(value)
|
||||
|
||||
@field_validator('authoritative_line_collection_path', mode='before')
|
||||
@classmethod
|
||||
def validate_optional_authoritative_path(cls, value: Any) -> str | None:
|
||||
"""草稿允许未配置 datasets 行集合;发布前由统一门禁 fail-closed。"""
|
||||
if value in (None, ''):
|
||||
return None
|
||||
return validate_controlled_data_path(value)
|
||||
|
||||
@field_validator('mirror_collection_paths', mode='before')
|
||||
@@ -395,13 +372,15 @@ class XfaLineMapping(XfaContractModel):
|
||||
Execute 后须为空,正式值绑定仅经 bindings[]。
|
||||
"""
|
||||
|
||||
row_path: str = Field(min_length=1, max_length=512)
|
||||
row_path: str | None = Field(default=None, 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:
|
||||
"""行集合路径必须通过受控语法。"""
|
||||
def validate_row_path(cls, value: Any) -> str | None:
|
||||
"""草稿可暂未配置行集合,正式提取前必须由发布门禁补齐。"""
|
||||
if value in (None, ''):
|
||||
return None
|
||||
return validate_controlled_data_path(value)
|
||||
|
||||
|
||||
@@ -418,6 +397,9 @@ class XfaCrossChecks(XfaContractModel):
|
||||
# 统一字段绑定(value_binding + visual_binding)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# ``bindings[]`` 是所有 Profile 共用的末端取值 DTO;具体 adapter 的 Profile
|
||||
# 契约再收紧允许类型。这样坐标/OCR 与 datasets 共用编辑、审计和迁移结构,
|
||||
# 同时 XFA 不会把视觉证据误作正式值。
|
||||
XfaValueBindingType = Literal['xfa_dataset', 'pdf_coordinate', 'ocr_coordinate']
|
||||
XfaVisualBindingSource = Literal[
|
||||
'acroform_widget',
|
||||
@@ -456,7 +438,7 @@ class XfaNormalizedBBox(XfaContractModel):
|
||||
|
||||
|
||||
class XfaValueBinding(XfaContractModel):
|
||||
"""正式值绑定:XFA 仅允许 datasets 路径;普通 PDF 允许坐标/OCR。"""
|
||||
"""共同正式值绑定;XFA Profile 的上层契约仍只允许 datasets 路径。"""
|
||||
|
||||
type: XfaValueBindingType
|
||||
path_id: str | None = Field(default=None, max_length=128)
|
||||
@@ -485,7 +467,7 @@ class XfaValueBinding(XfaContractModel):
|
||||
|
||||
|
||||
class XfaVisualBinding(XfaContractModel):
|
||||
"""视觉绑定:页码 + 归一化框 + 确认状态;正式字段发布前须 confirmed。
|
||||
"""视觉绑定:页码 + 归一化框 + 确认状态;正式字段发布前须原生页 confirmed。
|
||||
|
||||
合成预览确认证据(阶段 4+):confirmed 时须携带 preview_render_checksum /
|
||||
render_mode=xfa_dataset_preview / confirmed_on=xfa_dataset_preview。
|
||||
@@ -516,21 +498,23 @@ class XfaUnifiedFieldBinding(XfaContractModel):
|
||||
"""
|
||||
统一字段绑定:同一 Schema 字段在同一作用域最多一个正式来源。
|
||||
|
||||
核心逻辑:value_binding 决定正式取值;visual_binding 决定页面证据;
|
||||
split_rule_ref 可选指向已确认拆分段。
|
||||
核心逻辑:value_binding 决定正式取值;field_layout_id 指向共同订单字段标签
|
||||
(order_field_layouts),不重复保存或确认一套 XFA 专属值框;split_rule_ref
|
||||
可选指向已确认拆分段。visual_binding 仅用于读取历史草稿,禁止新保存依赖它。
|
||||
"""
|
||||
|
||||
binding_id: str = Field(min_length=8, max_length=64)
|
||||
field_id: str = Field(min_length=1, max_length=64)
|
||||
field_code: str = Field(min_length=1, max_length=128)
|
||||
scope: XfaBindingScope
|
||||
field_layout_id: str | None = Field(default=None, min_length=1, max_length=128)
|
||||
value_binding: XfaValueBinding
|
||||
visual_binding: XfaVisualBinding
|
||||
visual_binding: XfaVisualBinding | None = None
|
||||
split_rule_ref: XfaSplitRuleRef | None = None
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_xfa_scope_value_type(self) -> 'XfaUnifiedFieldBinding':
|
||||
"""同模板允许字段级混合数据源;具体约束由 value_binding / 发布门禁执行。"""
|
||||
def validate_shared_scope_value_type(self) -> 'XfaUnifiedFieldBinding':
|
||||
"""统一 binding 本身不判模板类型;XFA Profile 上层单独拒绝坐标取值。"""
|
||||
return self
|
||||
|
||||
|
||||
@@ -539,9 +523,8 @@ def is_formal_binding_publishable(binding: XfaUnifiedFieldBinding) -> bool:
|
||||
判断统一绑定是否满足发布门禁(字段级混合数据源口径)。
|
||||
|
||||
核心逻辑:
|
||||
- xfa_dataset:正式 path 已配置即可发布(视觉框可选);
|
||||
- pdf_coordinate / ocr_coordinate:必须视觉 confirmed;
|
||||
- 旧合成预览确认(confirmed_on/render_mode=xfa_dataset_preview)视为未重确认。
|
||||
- xfa_dataset:正式 path 配置完毕;视觉存在性由共同 order_field_layouts 门禁处理;
|
||||
- 历史 visual_binding 不再作为新草稿的发布前提。
|
||||
|
||||
Args:
|
||||
binding: 统一字段绑定。
|
||||
@@ -550,17 +533,9 @@ def is_formal_binding_publishable(binding: XfaUnifiedFieldBinding) -> bool:
|
||||
满足对应类型发布条件时为 True。
|
||||
"""
|
||||
value_type = binding.value_binding.type
|
||||
visual = binding.visual_binding
|
||||
confirmed_on = str(visual.confirmed_on or '').strip()
|
||||
render_mode = str(visual.render_mode or '').strip()
|
||||
# 旧 flatten/synthetic 坐标系确认框须在原生 PDF 画布重确认。
|
||||
if visual.status == 'confirmed' and (
|
||||
confirmed_on == 'xfa_dataset_preview' or render_mode == 'xfa_dataset_preview'
|
||||
):
|
||||
return False
|
||||
if value_type == 'xfa_dataset':
|
||||
return bool(binding.value_binding.path_id and binding.value_binding.data_path)
|
||||
return visual.status == 'confirmed'
|
||||
return value_type in {'pdf_coordinate', 'ocr_coordinate'} and bool(binding.value_binding.region_id)
|
||||
|
||||
|
||||
def canonical_unified_bindings_payload(
|
||||
@@ -591,10 +566,20 @@ class OrderXfaDatasetProfile(XfaContractModel):
|
||||
xfa_dataset 模式的鉴别联合 definition。
|
||||
|
||||
核心逻辑:header_mappings / line_mapping.fields 仅迁移输入(须 bindings-only 正式运行);
|
||||
validate 拒绝 legacy-only 与 dual-source;拒绝 coordinate 表区键;可选 split_rules。
|
||||
validate 拒绝 legacy-only 与 dual-source;保留共同视觉匹配契约;可选 split_rules。
|
||||
"""
|
||||
|
||||
template_mode: Literal['xfa_dataset'] = 'xfa_dataset'
|
||||
# 统一视觉 Layout 的主表身份;正式明细模板必须先冻结该身份,
|
||||
# datasets 只负责字段最终取值,不再替代视觉表格建模。
|
||||
# 历史已发布版本在迁移前可能没有该键;创建/发布入口分别负责拒绝未补齐的草稿,
|
||||
# 契约层保持可读,避免历史冻结快照无法审计。
|
||||
main_table_id: str | None = Field(default=None, min_length=1, max_length=128)
|
||||
# 所有模板共享的视觉候选选择契约。它只决定“哪个 Profile”,绝不参与 XFA 最终取值。
|
||||
document_match: dict[str, Any] | None = None
|
||||
table_regions: list[dict[str, Any]] = Field(default_factory=list)
|
||||
order_field_layouts: list[dict[str, Any]] = Field(default_factory=list)
|
||||
draft_unbound_order_field_layouts: list[dict[str, Any]] = Field(default_factory=list)
|
||||
source_contract: XfaSourceContract
|
||||
# 迁移输入兼容:禁止正式运行时单独携带非空 legacy mappings(须 bindings-only)。
|
||||
header_mappings: list[XfaHeaderMapping] = Field(default_factory=list)
|
||||
@@ -602,26 +587,21 @@ class OrderXfaDatasetProfile(XfaContractModel):
|
||||
bindings: list[XfaUnifiedFieldBinding] = Field(default_factory=list)
|
||||
cross_checks: XfaCrossChecks = Field(default_factory=XfaCrossChecks)
|
||||
split_rules: list[dict[str, Any]] = Field(default_factory=list)
|
||||
# 合成预览摘要(可选;发布门禁优先读取 status / preview_render_checksum)
|
||||
# 仅为读取已存历史草稿而保留;运行时、确认和发布均不读取此字段。
|
||||
xfa_preview: dict[str, Any] | None = None
|
||||
# OCR 自动标记摘要(可选;未解决 mismatch 计数供发布门禁读取)
|
||||
xfa_ocr_automark: dict[str, Any] | None = None
|
||||
|
||||
@model_validator(mode='before')
|
||||
@classmethod
|
||||
def reject_coordinate_keys(cls, data: Any) -> Any:
|
||||
"""
|
||||
拒绝 coordinate 表区 / layout 键混入 XFA definition。
|
||||
拒绝已废弃 coordinate 重建键混入 XFA definition。
|
||||
|
||||
注意:不拒绝 visual_binding / normalized_bbox(统一绑定的视觉证据)。
|
||||
注意:共同视觉 matcher 的 document_match/table_regions 是合法键;
|
||||
共同视觉布局字段是合法键;历史 visual_binding 仅兼容读取。
|
||||
"""
|
||||
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',
|
||||
@@ -654,13 +634,81 @@ class OrderXfaDatasetProfile(XfaContractModel):
|
||||
mapping_ids.append(item.mapping_id)
|
||||
binding_ids: list[str] = []
|
||||
binding_field_keys: list[tuple[str, str]] = []
|
||||
rule_sets = parse_split_rule_sets(self.split_rules)
|
||||
split_segments = {
|
||||
str(rule.segment.segment_id): {
|
||||
'source_path_id': str(rule_set.source_path_id),
|
||||
'target_field_code': str(rule.segment.target_field_code or ''),
|
||||
}
|
||||
for rule_set in rule_sets
|
||||
for rule in rule_set.rules
|
||||
if rule.segment.handling == 'mapped'
|
||||
}
|
||||
shared_layouts = {
|
||||
str(item.get('layout_id') or '').strip(): item
|
||||
for item in self.order_field_layouts
|
||||
if isinstance(item, dict) and str(item.get('layout_id') or '').strip()
|
||||
}
|
||||
for table in self.table_regions:
|
||||
if not isinstance(table, dict):
|
||||
continue
|
||||
for line in table.get('line_layouts') or []:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
for field in line.get('field_regions') or []:
|
||||
if not isinstance(field, dict):
|
||||
continue
|
||||
layout_id = str(
|
||||
field.get('region_id')
|
||||
or field.get('layout_id')
|
||||
or f"{line.get('layout_id') or ''}:{field.get('field_code') or ''}"
|
||||
).strip(':')
|
||||
if layout_id:
|
||||
shared_layouts[layout_id] = {**field, 'scope': 'line'}
|
||||
for binding in self.bindings:
|
||||
# 硬冻结(2026-08-07):同模板允许 xfa_dataset / pdf_coordinate / ocr_coordinate 混用。
|
||||
if binding.value_binding.type not in {'xfa_dataset', 'pdf_coordinate', 'ocr_coordinate'}:
|
||||
raise ValueError(
|
||||
'OrderXfaDatasetProfile bindings must use value_binding.type in '
|
||||
'xfa_dataset|pdf_coordinate|ocr_coordinate',
|
||||
)
|
||||
if binding.value_binding.type != 'xfa_dataset':
|
||||
raise ValueError('XFA value bindings must use xfa_dataset')
|
||||
# 新定义以共同 Editor 的 order_field_layouts 为唯一视觉字段模型。
|
||||
# 没有共同布局的历史草稿仍可读取,保存与发布会在 adapter 门禁 fail-closed。
|
||||
if shared_layouts:
|
||||
layout_id = str(binding.field_layout_id or '').strip()
|
||||
if not layout_id:
|
||||
raise ValueError('field_layout_id is required when order_field_layouts are present')
|
||||
layout = shared_layouts.get(layout_id)
|
||||
if layout is None:
|
||||
raise ValueError('field_layout_id must reference an order_field_layouts entry')
|
||||
layout_field_code = str(layout.get('field_code') or '')
|
||||
if layout_field_code != binding.field_code:
|
||||
# 一个多行源值(MATNR)可以通过已确认拆分规则产出多个行字段。
|
||||
# 每个目标仍指向同一个真实 MATNR 框,避免伪造重叠视觉框。
|
||||
split_ref = binding.split_rule_ref
|
||||
segment = split_segments.get(str(split_ref.segment_id)) if split_ref else None
|
||||
is_split_target_visual_reuse = bool(
|
||||
binding.scope == 'line'
|
||||
and str(layout.get('scope') or '') == 'line'
|
||||
and binding.value_binding.type == 'xfa_dataset'
|
||||
and segment
|
||||
and segment['target_field_code'] == binding.field_code
|
||||
and segment['source_path_id'] == str(binding.value_binding.path_id or '')
|
||||
)
|
||||
if not is_split_target_visual_reuse:
|
||||
raise ValueError('field_layout_id field_code must match binding field_code')
|
||||
layout_scope = str(layout.get('scope') or 'header')
|
||||
if layout_scope != binding.scope:
|
||||
# 全单 Header 值(例如 Reservation)可被显式投影至每条明细。
|
||||
# 此时共同视觉证据必须保留其真实 Header 框,不能伪造表格内框;
|
||||
# 保存 adapter 仍会校验该 path 是当前 XFA 分析确认的 Header 叶子。
|
||||
authoritative_prefix = self.source_contract.authoritative_line_collection_path.rstrip('/') if self.source_contract.authoritative_line_collection_path else ''
|
||||
is_line_header_visual_inheritance = bool(
|
||||
binding.scope == 'line'
|
||||
and layout_scope == 'header'
|
||||
and binding.value_binding.type == 'xfa_dataset'
|
||||
and authoritative_prefix
|
||||
and binding.value_binding.data_path
|
||||
and not binding.value_binding.data_path.startswith(f'{authoritative_prefix}/')
|
||||
)
|
||||
if not is_line_header_visual_inheritance:
|
||||
raise ValueError('field_layout_id scope must match binding scope')
|
||||
binding_ids.append(binding.binding_id)
|
||||
binding_field_keys.append((binding.scope, binding.field_id))
|
||||
field_ids.append(binding.field_id)
|
||||
@@ -668,12 +716,22 @@ class OrderXfaDatasetProfile(XfaContractModel):
|
||||
raise ValueError('duplicate binding_id values are not allowed')
|
||||
if len(binding_field_keys) != len(set(binding_field_keys)):
|
||||
raise ValueError('duplicate Schema field_id bindings in the same scope are not allowed')
|
||||
rule_sets = parse_split_rule_sets(self.split_rules)
|
||||
split_target_field_ids: list[str] = []
|
||||
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)
|
||||
split_target_field_ids.append(rule.segment.target_field_id)
|
||||
has_legacy_mappings = bool(self.header_mappings) or bool(self.line_mapping.fields)
|
||||
if not self.source_contract.authoritative_line_collection_path and (
|
||||
self.bindings
|
||||
or has_legacy_mappings
|
||||
or self.line_mapping.row_path
|
||||
or rule_sets
|
||||
):
|
||||
raise ValueError(
|
||||
'authoritative_line_collection_required: XFA value mappings and split rules '
|
||||
'require an authoritative datasets line collection',
|
||||
)
|
||||
if self.bindings and has_legacy_mappings:
|
||||
raise ValueError(
|
||||
'xfa_dual_binding_source: bindings cannot coexist with '
|
||||
@@ -686,9 +744,17 @@ class OrderXfaDatasetProfile(XfaContractModel):
|
||||
)
|
||||
if len(field_ids) != len(set(field_ids)):
|
||||
raise ValueError('duplicate Schema field_id bindings are not allowed')
|
||||
# 拆分段的字段目标独立于 bindings[] 去重:同一字段的 binding 正是其共享
|
||||
# 视觉源框引用,不能被误判为双重正式取值;两个拆分段映射同一字段仍不允许。
|
||||
if len(split_target_field_ids) != len(set(split_target_field_ids)):
|
||||
raise ValueError('duplicate Schema field_id split targets 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:
|
||||
if (
|
||||
self.line_mapping.row_path
|
||||
and self.source_contract.authoritative_line_collection_path
|
||||
and self.line_mapping.row_path != self.source_contract.authoritative_line_collection_path
|
||||
):
|
||||
raise ValueError('line_mapping.row_path must equal authoritative_line_collection_path')
|
||||
object.__setattr__(
|
||||
self,
|
||||
|
||||
@@ -565,7 +565,7 @@ def serialize_tree_node(node: XfaDatasetNode, *, include_values: bool = False) -
|
||||
|
||||
Args:
|
||||
node: 数据集树节点。
|
||||
include_values: 是否包含当前管理端使用的完整样本值。
|
||||
include_values: 是否包含受控的样本展示值;不得暴露 raw_value。
|
||||
|
||||
Returns:
|
||||
安全 DTO 字典。
|
||||
@@ -583,10 +583,12 @@ def serialize_tree_node(node: XfaDatasetNode, *, include_values: bool = False) -
|
||||
'children': [serialize_tree_node(child, include_values=include_values) for child in node.children],
|
||||
}
|
||||
if include_values and node.is_leaf:
|
||||
payload['sample_value_masked'] = str(node.raw_value or '')
|
||||
payload['sample_value_display'] = str(node.raw_value or '')
|
||||
payload['display_policy'] = 'full'
|
||||
payload['can_reveal'] = False
|
||||
# 字段树是批量 DTO:即使管理端需要映射辅助,也绝不能把 datasets
|
||||
# 原文放入可缓存/可下载的树响应。完整值只能经单值受控读取与审计接口取得。
|
||||
payload['sample_value_masked'] = str(node.sample_value_masked or '')
|
||||
payload['sample_value_display'] = str(node.sample_value_display or '')
|
||||
payload['display_policy'] = str(node.display_policy or 'empty')
|
||||
payload['can_reveal'] = bool(node.can_reveal)
|
||||
payload['line_count'] = len(node.lines or [])
|
||||
return payload
|
||||
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_preview_cache.py
|
||||
|
||||
用途:XFA 合成预览进程内缓存(Phase 1 POC);按身份指纹键存取预览结果。
|
||||
依赖:threading、xfa_preview_contract.build_preview_identity_fingerprint。
|
||||
逻辑:由预览编排层调用;可选后续替换为 Redis;本模块不做 IO/渲染。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_preview_contract import (
|
||||
PreviewIdentityContext,
|
||||
build_preview_identity_fingerprint,
|
||||
)
|
||||
|
||||
_LOCK = threading.RLock()
|
||||
_CACHE: dict[str, tuple[float, dict[str, Any]]] = {}
|
||||
_DEFAULT_TTL_SECONDS = 30 * 60
|
||||
|
||||
|
||||
def build_preview_cache_key(
|
||||
*,
|
||||
structure_analysis_id: int | str | None,
|
||||
template_packet_checksum: str,
|
||||
datasets_packet_checksum: str,
|
||||
dataset_structure_fingerprint: str,
|
||||
source_content_hash: str,
|
||||
renderer_version: str,
|
||||
) -> str:
|
||||
"""
|
||||
构造预览缓存键(analysis_id + checksums + renderer_version)。
|
||||
|
||||
核心逻辑:委托 PreviewIdentityContext 指纹,page_count/preview_render_checksum 置空
|
||||
以便在渲染前即可定位缓存槽。
|
||||
|
||||
Args:
|
||||
structure_analysis_id: 冻结结构分析 ID。
|
||||
template_packet_checksum: template packet 校验和。
|
||||
datasets_packet_checksum: datasets packet 校验和。
|
||||
dataset_structure_fingerprint: datasets 结构指纹。
|
||||
source_content_hash: 源 PDF 内容哈希。
|
||||
renderer_version: 合成器版本。
|
||||
|
||||
Returns:
|
||||
稳定十六进制缓存键。
|
||||
"""
|
||||
ctx = PreviewIdentityContext(
|
||||
document_id=None,
|
||||
layout_version_id=None,
|
||||
structure_analysis_id=structure_analysis_id,
|
||||
source_content_hash=str(source_content_hash or ''),
|
||||
template_packet_checksum=str(template_packet_checksum or ''),
|
||||
datasets_packet_checksum=str(datasets_packet_checksum or ''),
|
||||
dataset_structure_fingerprint=str(dataset_structure_fingerprint or ''),
|
||||
preview_render_checksum='',
|
||||
renderer_version=str(renderer_version or ''),
|
||||
page_count=0,
|
||||
)
|
||||
return build_preview_identity_fingerprint(ctx)
|
||||
|
||||
|
||||
def get_preview_cache(key: str) -> dict[str, Any] | None:
|
||||
"""
|
||||
读取预览缓存条目。
|
||||
|
||||
核心逻辑:持锁检查 TTL;过期则删除并返回 None。
|
||||
|
||||
Args:
|
||||
key: build_preview_cache_key 结果。
|
||||
|
||||
Returns:
|
||||
缓存的预览结果字典;未命中或过期时为 None。
|
||||
"""
|
||||
text = str(key or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
now = time.time()
|
||||
with _LOCK:
|
||||
item = _CACHE.get(text)
|
||||
if item is None:
|
||||
return None
|
||||
expires_at, payload = item
|
||||
if expires_at <= now:
|
||||
_CACHE.pop(text, None)
|
||||
return None
|
||||
return dict(payload)
|
||||
|
||||
|
||||
def set_preview_cache(
|
||||
key: str,
|
||||
value: dict[str, Any],
|
||||
*,
|
||||
ttl_seconds: int = _DEFAULT_TTL_SECONDS,
|
||||
) -> None:
|
||||
"""
|
||||
写入预览缓存条目。
|
||||
|
||||
Args:
|
||||
key: 缓存键。
|
||||
value: 可浅拷贝的预览结果字典(调用方勿放入不可序列化巨型对象以外的副作用状态)。
|
||||
ttl_seconds: 存活秒数;最小 1。
|
||||
"""
|
||||
text = str(key or '').strip()
|
||||
if not text or not isinstance(value, dict):
|
||||
return
|
||||
expires_at = time.time() + max(1, int(ttl_seconds))
|
||||
with _LOCK:
|
||||
_CACHE[text] = (expires_at, dict(value))
|
||||
|
||||
|
||||
def invalidate_preview_cache(key: str | None = None) -> None:
|
||||
"""
|
||||
使预览缓存失效。
|
||||
|
||||
核心逻辑:key 为空时清空全部;否则仅删除指定键。
|
||||
|
||||
Args:
|
||||
key: 可选缓存键;None/空串表示清空。
|
||||
"""
|
||||
with _LOCK:
|
||||
if not key:
|
||||
_CACHE.clear()
|
||||
return
|
||||
_CACHE.pop(str(key), None)
|
||||
|
||||
|
||||
def clear_preview_cache() -> None:
|
||||
"""清空全部预览缓存(测试辅助)。"""
|
||||
invalidate_preview_cache(None)
|
||||
@@ -1,185 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_preview_contract.py
|
||||
|
||||
用途:冻结 XFA 自研静态合成预览(Phase 1 POC)契约——render_mode、预览状态、
|
||||
错误码、身份上下文、审计事件名与确定性指纹辅助。
|
||||
依赖:标准库 dataclasses/hashlib/json;被 xfa_preview_renderer / xfa_preview_cache /
|
||||
后续预览 API 与审计接线引用。
|
||||
逻辑:本模块只定义纯数据与纯函数,不读 PDF、不渲染、不落库;身份字段与
|
||||
preview_render_checksum 必须与合成器输出一致,供 stale 判定与发布证据绑定。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from dataclasses import asdict, dataclass
|
||||
from typing import Any, Final, Literal
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 渲染模式 / 预览状态
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
RENDER_MODE: Final[str] = 'xfa_dataset_preview'
|
||||
|
||||
XfaPreviewStatus = Literal['ready', 'needs_review', 'failed', 'stale']
|
||||
XFA_PREVIEW_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'ready',
|
||||
'needs_review',
|
||||
'failed',
|
||||
'stale',
|
||||
})
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 稳定错误码(短码;AppError 层可映射为 SHIPPING.ORDER_DOCUMENT_PROFILE_*)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
XFA_PREVIEW_STALE: Final[str] = 'XFA_PREVIEW_STALE'
|
||||
XFA_PREVIEW_FAILED: Final[str] = 'XFA_PREVIEW_FAILED'
|
||||
XFA_PREVIEW_UNAVAILABLE: Final[str] = 'XFA_PREVIEW_UNAVAILABLE'
|
||||
XFA_PREVIEW_PAGE_INCONSISTENT: Final[str] = 'XFA_PREVIEW_PAGE_INCONSISTENT'
|
||||
XFA_PREVIEW_VALUE_MISMATCH: Final[str] = 'XFA_PREVIEW_VALUE_MISMATCH'
|
||||
|
||||
XFA_PREVIEW_ERROR_CODES: Final[frozenset[str]] = frozenset({
|
||||
XFA_PREVIEW_STALE,
|
||||
XFA_PREVIEW_FAILED,
|
||||
XFA_PREVIEW_UNAVAILABLE,
|
||||
XFA_PREVIEW_PAGE_INCONSISTENT,
|
||||
XFA_PREVIEW_VALUE_MISMATCH,
|
||||
})
|
||||
|
||||
# AppError / i18n 完整码(与 SHIPPING.ORDER_DOCUMENT_PROFILE_* 风格对齐)
|
||||
SHIPPING_XFA_PREVIEW_STALE: Final[str] = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_STALE'
|
||||
SHIPPING_XFA_PREVIEW_FAILED: Final[str] = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_FAILED'
|
||||
SHIPPING_XFA_PREVIEW_UNAVAILABLE: Final[str] = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_UNAVAILABLE'
|
||||
SHIPPING_XFA_PREVIEW_PAGE_INCONSISTENT: Final[str] = (
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_PAGE_INCONSISTENT'
|
||||
)
|
||||
SHIPPING_XFA_PREVIEW_VALUE_MISMATCH: Final[str] = (
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_VALUE_MISMATCH'
|
||||
)
|
||||
|
||||
XFA_PREVIEW_SHIPPING_ERROR_BY_CODE: Final[dict[str, str]] = {
|
||||
XFA_PREVIEW_STALE: SHIPPING_XFA_PREVIEW_STALE,
|
||||
XFA_PREVIEW_FAILED: SHIPPING_XFA_PREVIEW_FAILED,
|
||||
XFA_PREVIEW_UNAVAILABLE: SHIPPING_XFA_PREVIEW_UNAVAILABLE,
|
||||
XFA_PREVIEW_PAGE_INCONSISTENT: SHIPPING_XFA_PREVIEW_PAGE_INCONSISTENT,
|
||||
XFA_PREVIEW_VALUE_MISMATCH: SHIPPING_XFA_PREVIEW_VALUE_MISMATCH,
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 审计事件(预览生命周期)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
XFA_PREVIEW_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_preview_requested',
|
||||
'xfa_preview_generated',
|
||||
'xfa_preview_failed',
|
||||
'xfa_preview_viewed',
|
||||
'xfa_preview_stale',
|
||||
})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PreviewIdentityContext:
|
||||
"""
|
||||
合成预览身份上下文:发布视觉证据与 stale 判定的冻结字段集合。
|
||||
|
||||
任一关键校验和/指纹变化即视为预览身份漂移,不得继续当作 ready 证据。
|
||||
"""
|
||||
|
||||
document_id: int | None
|
||||
layout_version_id: int | None
|
||||
structure_analysis_id: int | str | None
|
||||
source_content_hash: str
|
||||
template_packet_checksum: str
|
||||
datasets_packet_checksum: str
|
||||
dataset_structure_fingerprint: str
|
||||
preview_render_checksum: str
|
||||
render_mode: str = RENDER_MODE
|
||||
renderer_version: str = ''
|
||||
page_count: int = 0
|
||||
|
||||
|
||||
def shipping_error_code_for_preview(error_code: str | None) -> str | None:
|
||||
"""
|
||||
将预览短错误码映射为 SHIPPING.ORDER_DOCUMENT_PROFILE_* AppError 码。
|
||||
|
||||
核心逻辑:查 XFA_PREVIEW_SHIPPING_ERROR_BY_CODE;未知码原样返回。
|
||||
|
||||
Args:
|
||||
error_code: 预览短错误码或已是完整 SHIPPING.* 码。
|
||||
|
||||
Returns:
|
||||
完整业务错误码;输入为空时返回 None。
|
||||
"""
|
||||
text = str(error_code or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
if text.startswith('SHIPPING.'):
|
||||
return text
|
||||
return XFA_PREVIEW_SHIPPING_ERROR_BY_CODE.get(text, text)
|
||||
|
||||
|
||||
def preview_identity_to_dict(ctx: PreviewIdentityContext) -> dict[str, Any]:
|
||||
"""
|
||||
将 PreviewIdentityContext 序列化为可审计/可缓存的普通字典。
|
||||
|
||||
Args:
|
||||
ctx: 预览身份上下文。
|
||||
|
||||
Returns:
|
||||
字段字典(不含额外派生键)。
|
||||
"""
|
||||
return asdict(ctx)
|
||||
|
||||
|
||||
def build_preview_identity_fingerprint(ctx: PreviewIdentityContext) -> str:
|
||||
"""
|
||||
计算预览身份指纹(不含 preview_render_checksum 本身,避免循环依赖)。
|
||||
|
||||
核心逻辑:对 document/layout/analysis/内容哈希/packet/结构指纹/render_mode/
|
||||
renderer_version/page_count 做稳定 JSON 序列化后 SHA-256。
|
||||
|
||||
Args:
|
||||
ctx: 预览身份上下文。
|
||||
|
||||
Returns:
|
||||
64 位十六进制指纹字符串。
|
||||
"""
|
||||
payload = {
|
||||
'document_id': ctx.document_id,
|
||||
'layout_version_id': ctx.layout_version_id,
|
||||
'structure_analysis_id': ctx.structure_analysis_id,
|
||||
'source_content_hash': str(ctx.source_content_hash or ''),
|
||||
'template_packet_checksum': str(ctx.template_packet_checksum or ''),
|
||||
'datasets_packet_checksum': str(ctx.datasets_packet_checksum or ''),
|
||||
'dataset_structure_fingerprint': str(ctx.dataset_structure_fingerprint or ''),
|
||||
'render_mode': str(ctx.render_mode or RENDER_MODE),
|
||||
'renderer_version': str(ctx.renderer_version or ''),
|
||||
'page_count': int(ctx.page_count or 0),
|
||||
}
|
||||
raw = json.dumps(payload, sort_keys=True, separators=(',', ':'), ensure_ascii=True)
|
||||
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def is_preview_identity_stale(
|
||||
*,
|
||||
expected: PreviewIdentityContext,
|
||||
actual: PreviewIdentityContext,
|
||||
) -> bool:
|
||||
"""
|
||||
判断实际预览身份是否相对期望身份已过期(stale)。
|
||||
|
||||
核心逻辑:比较身份指纹与 preview_render_checksum;任一不等即 stale。
|
||||
|
||||
Args:
|
||||
expected: 期望/冻结身份(例如绑定证据快照)。
|
||||
actual: 当前重新计算的身份。
|
||||
|
||||
Returns:
|
||||
True 表示应标记 stale 并重新生成/重确认。
|
||||
"""
|
||||
if build_preview_identity_fingerprint(expected) != build_preview_identity_fingerprint(actual):
|
||||
return True
|
||||
return str(expected.preview_render_checksum or '') != str(actual.preview_render_checksum or '')
|
||||
@@ -1,200 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_preview_renderer.py
|
||||
|
||||
用途:XFA 离线完整 flatten 入口(硬冻结 §0)。当前未接入可复现 flatten 引擎时
|
||||
一律 fail-closed 返回 needs_review;禁止静态 overlay / 壳图充当 ready。
|
||||
依赖:xfa_preview_contract;未来真实引擎须离线、禁不受控脚本、输出可复现 checksum。
|
||||
逻辑:由预览编排服务调用 compose_xfa_dataset_preview_pages;settings
|
||||
SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY=true 且引擎实现就绪后才可返回 ready。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_preview_contract import (
|
||||
RENDER_MODE,
|
||||
XFA_PREVIEW_FAILED,
|
||||
XFA_PREVIEW_UNAVAILABLE,
|
||||
XfaPreviewStatus,
|
||||
)
|
||||
|
||||
# 版本号:v0_pending 表示尚未交付完整 flatten;不得与历史 overlay checksum 混用。
|
||||
RENDERER_VERSION = 'hxops.xfa_flatten.v0_pending'
|
||||
|
||||
|
||||
@dataclass
|
||||
class DrawnFieldEcho:
|
||||
"""单页上 flatten 回显痕迹(完整引擎就绪后使用)。"""
|
||||
|
||||
path_id: str
|
||||
value: str
|
||||
normalized_bbox: dict[str, float]
|
||||
page_no: int = 1
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaPreviewComposeResult:
|
||||
"""flatten / 预览文档级结果;status!=ready 时 pages 为空。"""
|
||||
|
||||
status: XfaPreviewStatus
|
||||
error_code: str | None
|
||||
render_mode: str
|
||||
renderer_version: str
|
||||
page_count: int
|
||||
preview_render_checksum: str | None
|
||||
pages: list[dict[str, Any]] = field(default_factory=list)
|
||||
diagnostics: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""序列化为普通字典。"""
|
||||
return {
|
||||
'status': self.status,
|
||||
'error_code': self.error_code,
|
||||
'render_mode': self.render_mode,
|
||||
'renderer_version': self.renderer_version,
|
||||
'page_count': self.page_count,
|
||||
'preview_render_checksum': self.preview_render_checksum,
|
||||
'pages': self.pages,
|
||||
'diagnostics': self.diagnostics,
|
||||
}
|
||||
|
||||
|
||||
def compute_preview_render_checksum(
|
||||
*,
|
||||
renderer_version: str,
|
||||
pages: list[dict[str, Any]],
|
||||
) -> str:
|
||||
"""
|
||||
计算可复现的预览渲染校验和。
|
||||
|
||||
核心逻辑:串联 renderer_version 与各页宽高/回显指纹/图像哈希后 SHA-256。
|
||||
|
||||
Args:
|
||||
renderer_version: 合成器版本。
|
||||
pages: 含 width/height/drawn_field_echoes/png_bytes 的页列表。
|
||||
|
||||
Returns:
|
||||
hex digest 字符串。
|
||||
"""
|
||||
parts: list[str] = [str(renderer_version or '')]
|
||||
for page in pages:
|
||||
page_no = int(page.get('page_no') or 0)
|
||||
width = float(page.get('width') or 0)
|
||||
height = float(page.get('height') or 0)
|
||||
echoes = page.get('drawn_field_echoes') if isinstance(page.get('drawn_field_echoes'), list) else []
|
||||
echo_fp = '|'.join(
|
||||
f"{item.get('path_id')}:{item.get('value')}"
|
||||
for item in echoes
|
||||
if isinstance(item, dict)
|
||||
)
|
||||
png = page.get('png_bytes')
|
||||
img_hash = ''
|
||||
if isinstance(png, (bytes, bytearray)) and png:
|
||||
img_hash = hashlib.sha256(bytes(png)).hexdigest()
|
||||
parts.append(f'{page_no}:{width}x{height}:{echo_fp}:{img_hash}')
|
||||
return hashlib.sha256('\n'.join(parts).encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def is_xfa_flatten_engine_ready() -> bool:
|
||||
"""
|
||||
完整离线 flatten 引擎是否已启用且可对外返回 ready。
|
||||
|
||||
核心逻辑:读取 settings.SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY;默认 false。
|
||||
引擎实现与人眼一致性完成前必须保持关闭。
|
||||
|
||||
Returns:
|
||||
True 仅当显式开启(当前仍无真实引擎实现,开启也不会 ready)。
|
||||
"""
|
||||
try:
|
||||
from app.core.config.settings import Settings
|
||||
|
||||
return bool(getattr(Settings, 'SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY', False))
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def attempt_offline_xfa_flatten(
|
||||
*,
|
||||
pdf_bytes: bytes,
|
||||
analysis_or_nodes: Any,
|
||||
page_boxes: list[dict[str, Any]] | None = None,
|
||||
template_bytes: bytes | None = None,
|
||||
) -> XfaPreviewComposeResult:
|
||||
"""
|
||||
尝试离线完整 XFA flatten(template + datasets → 有效 PDF/PNG)。
|
||||
|
||||
核心逻辑:硬冻结要求删除 overlay;真实引擎未交付前一律 needs_review。
|
||||
不得用 PDFium 壳图或黄框叠加冒充 ready。
|
||||
|
||||
Args:
|
||||
pdf_bytes: 源 XFA PDF 字节。
|
||||
analysis_or_nodes: datasets 分析或叶子映射(预留)。
|
||||
page_boxes: 可选期望页框(预留)。
|
||||
template_bytes: 可选 template packet(预留)。
|
||||
|
||||
Returns:
|
||||
当前恒为 needs_review / failed;未来引擎就绪后返回 ready + pages。
|
||||
"""
|
||||
del analysis_or_nodes, page_boxes, template_bytes # 真实引擎接入时启用
|
||||
if not pdf_bytes:
|
||||
return XfaPreviewComposeResult(
|
||||
status='failed',
|
||||
error_code=XFA_PREVIEW_FAILED,
|
||||
render_mode=RENDER_MODE,
|
||||
renderer_version=RENDERER_VERSION,
|
||||
page_count=0,
|
||||
preview_render_checksum=None,
|
||||
pages=[],
|
||||
diagnostics={'reason': 'empty_pdf_bytes'},
|
||||
)
|
||||
# [STEP] 完整 flatten 未交付:fail-closed(禁止 overlay ready)
|
||||
return XfaPreviewComposeResult(
|
||||
status='needs_review',
|
||||
error_code=XFA_PREVIEW_UNAVAILABLE,
|
||||
render_mode=RENDER_MODE,
|
||||
renderer_version=RENDERER_VERSION,
|
||||
page_count=0,
|
||||
preview_render_checksum=None,
|
||||
pages=[],
|
||||
diagnostics={
|
||||
'reason': 'flatten_engine_unavailable',
|
||||
'message': (
|
||||
'Offline reproducible XFA flatten is not available; '
|
||||
'shell PDF / PDFium shell / overlay must not be used as canvas source'
|
||||
),
|
||||
'flatten_engine_ready_flag': is_xfa_flatten_engine_ready(),
|
||||
'operational_status': 'OPERATIONAL_PENDING',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def compose_xfa_dataset_preview_pages(
|
||||
*,
|
||||
pdf_bytes: bytes,
|
||||
analysis_or_nodes: Any,
|
||||
page_boxes: list[dict[str, Any]] | None = None,
|
||||
template_bytes: bytes | None = None,
|
||||
) -> XfaPreviewComposeResult:
|
||||
"""
|
||||
XFA 标注图源编排入口(对外保持原函数名以兼容调用方)。
|
||||
|
||||
核心逻辑:委托 attempt_offline_xfa_flatten;未完成完整 flatten 前不得返回 ready。
|
||||
|
||||
Args:
|
||||
pdf_bytes: 源 PDF 字节。
|
||||
analysis_or_nodes: datasets 分析或叶子映射。
|
||||
page_boxes: 可选期望页框。
|
||||
template_bytes: 可选 template packet。
|
||||
|
||||
Returns:
|
||||
XfaPreviewComposeResult;当前预期 status=needs_review。
|
||||
"""
|
||||
return attempt_offline_xfa_flatten(
|
||||
pdf_bytes=pdf_bytes,
|
||||
analysis_or_nodes=analysis_or_nodes,
|
||||
page_boxes=page_boxes,
|
||||
template_bytes=template_bytes,
|
||||
)
|
||||
@@ -18,9 +18,6 @@ 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,
|
||||
@@ -47,6 +44,21 @@ from app.services.shipping_notice.order_schema.field_rules import (
|
||||
)
|
||||
|
||||
|
||||
# 引擎保留命中集合用于可审计诊断;这些信息本身不表示歧义,不能污染行级门禁。
|
||||
_SPLIT_INFORMATIONAL_DIAGNOSTIC_CODES = frozenset({
|
||||
'line_match_candidates',
|
||||
})
|
||||
|
||||
|
||||
def _split_blocking_issue_codes(split_result: Any) -> list[str]:
|
||||
"""只将会影响正式取值可信度的拆分诊断投影为业务 issue。"""
|
||||
return [
|
||||
f'xfa_split:{item.code}'
|
||||
for item in split_result.diagnostics
|
||||
if item.code and item.code not in _SPLIT_INFORMATIONAL_DIAGNOSTIC_CODES
|
||||
]
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaExtractedField:
|
||||
"""单字段提取结果(含内部原始值,对外投影时剥离)。"""
|
||||
@@ -354,9 +366,7 @@ def _apply_split_rules_for_header(
|
||||
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
|
||||
)
|
||||
issues.extend(_split_blocking_issue_codes(split_result))
|
||||
for segment in split_result.evidence_only_segments:
|
||||
evidence.append({
|
||||
'segment_id': segment.segment_id,
|
||||
@@ -441,9 +451,7 @@ def _apply_split_rules_for_row(
|
||||
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}')
|
||||
issues.extend(_split_blocking_issue_codes(split_result))
|
||||
for segment in split_result.evidence_only_segments:
|
||||
split_evidence.append({
|
||||
'segment_id': segment.segment_id,
|
||||
@@ -507,7 +515,7 @@ def extract_xfa_profile(
|
||||
|
||||
核心逻辑:校验 definition → 要求 bindings-only(拒绝 legacy mappings)→
|
||||
按 scope 迭代 bindings → 读权威集合行 → 从 schema_fields 标准化;
|
||||
无 bindings → xfa_visual_bindings_required;双源 → xfa_dual_binding_source。
|
||||
无 bindings → xfa_mapping_required;双源 → xfa_dual_binding_source。
|
||||
|
||||
Args:
|
||||
raw_profile: 冻结 Profile 快照(含 definition / checksum)。
|
||||
@@ -531,7 +539,7 @@ def extract_xfa_profile(
|
||||
if not has_bindings:
|
||||
return XfaExtractionResult(
|
||||
status='failed',
|
||||
reason_codes=['xfa_visual_bindings_required'],
|
||||
reason_codes=['xfa_mapping_required'],
|
||||
packet_checksum=packet_checksum,
|
||||
dataset_structure_fingerprint=dataset_structure_fingerprint,
|
||||
profile_checksum=str(raw_profile.get('checksum') or '') or None,
|
||||
@@ -690,32 +698,30 @@ def extract_xfa_profile(
|
||||
'evidence_ref': header.evidence,
|
||||
'highlight_source': 'xfa_dataset',
|
||||
})
|
||||
pending_price_unit_raw: str | None = None
|
||||
pending_price_unit_path: str | None = None
|
||||
for binding in line_bindings:
|
||||
if str(binding.field_code or '') in split_produced_codes:
|
||||
continue
|
||||
if str(binding.value_binding.path_id or '') in split_source_path_ids:
|
||||
continue
|
||||
data_path = str(binding.value_binding.data_path or '')
|
||||
raw_value = row_values.get(data_path)
|
||||
extract_raw = raw_value
|
||||
# 业务字段属于 line 不代表 datasets 值必须物理存放在每条 DATA 中。
|
||||
# 部分供应商 XFA 将整单 Reservation 放在 Header;该 binding 仍须由管理员
|
||||
# 显式确认到共同明细字段框,随后把同一份 datasets 正式证据投影到每行。
|
||||
inherited_from_header = bool(
|
||||
data_path and not data_path.startswith(f'{normalized_auth_path}/')
|
||||
)
|
||||
raw_value = (
|
||||
read_dataset_value(dataset_analysis, data_path)
|
||||
if inherited_from_header
|
||||
else row_values.get(data_path)
|
||||
)
|
||||
value_type, normalizer_key, validator_key = _schema_metadata_for_field(
|
||||
schema_fields=schema_fields,
|
||||
field_id=binding.field_id,
|
||||
field_code=binding.field_code,
|
||||
)
|
||||
# [STEP] NETPR 复合值:拆出单价;价格单位若无独立 binding 则稍后补齐。
|
||||
if str(binding.field_code or '') == 'unit_price':
|
||||
composite = parse_unit_price_with_price_unit(
|
||||
None if raw_value is None else str(raw_value)
|
||||
)
|
||||
if composite:
|
||||
extract_raw = composite['unit_price']
|
||||
pending_price_unit_raw = composite['price_unit']
|
||||
pending_price_unit_path = data_path
|
||||
extracted = _extract_one_field(
|
||||
raw_value=extract_raw if extract_raw is not None else raw_value,
|
||||
raw_value=raw_value,
|
||||
mapping_id=binding.binding_id,
|
||||
field_id=binding.field_id,
|
||||
field_code=binding.field_code,
|
||||
@@ -727,24 +733,6 @@ def extract_xfa_profile(
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
)
|
||||
# 保留原文 quote(含 ``898.72 / 1``)便于审计对账。
|
||||
if (
|
||||
str(binding.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:
|
||||
@@ -759,52 +747,9 @@ def extract_xfa_profile(
|
||||
'evidence_ref': extracted.evidence,
|
||||
'highlight_source': 'xfa_dataset',
|
||||
'row_index': index,
|
||||
**({'inherited_from_header': True} if inherited_from_header else {}),
|
||||
})
|
||||
|
||||
# 仅映射 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',
|
||||
@@ -817,6 +762,8 @@ def extract_xfa_profile(
|
||||
if has_unconfirmed_split_rules:
|
||||
reason_codes.append('xfa_split_rule_unconfirmed')
|
||||
source_mapping_incomplete = bool(required_missing)
|
||||
if source_mapping_incomplete:
|
||||
reason_codes.append('xfa_source_mapping_incomplete')
|
||||
|
||||
evidence_summary = sanitize_xfa_dto({
|
||||
'header_field_count': len(header_fields),
|
||||
|
||||
@@ -1,191 +0,0 @@
|
||||
"""
|
||||
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=[],
|
||||
)
|
||||
@@ -156,10 +156,21 @@ def compile_safe_regex(
|
||||
flags = 0 if case_sensitive else re.IGNORECASE
|
||||
if _HAS_RE2 and _re2 is not None:
|
||||
try:
|
||||
re2_flags = _re2.Flags(0)
|
||||
if not case_sensitive:
|
||||
re2_flags = _re2.Flags.CASE_INSENSITIVE # type: ignore[attr-defined]
|
||||
compiled_re2 = _re2.compile(str(pattern), re2_flags)
|
||||
# google-re2 bindings have two public shapes: older bindings expose
|
||||
# Flags, while current pybind bindings accept an Options instance.
|
||||
# Keep RE2 linear-time execution in both cases; never silently fall
|
||||
# through to in-process Python ``re`` merely because the API changed.
|
||||
if hasattr(_re2, 'Flags'):
|
||||
re2_flags = _re2.Flags(0)
|
||||
if not case_sensitive:
|
||||
re2_flags = _re2.Flags.CASE_INSENSITIVE # type: ignore[attr-defined]
|
||||
compiled_re2 = _re2.compile(str(pattern), re2_flags)
|
||||
elif hasattr(_re2, 'Options'):
|
||||
options = _re2.Options()
|
||||
options.case_sensitive = bool(case_sensitive)
|
||||
compiled_re2 = _re2.compile(str(pattern), options)
|
||||
else:
|
||||
raise SafeRegexError('unsupported re2 binding API')
|
||||
group_count = compiled_re2.groups if hasattr(compiled_re2, 'groups') else 0
|
||||
if int(group_count or 0) > max_groups:
|
||||
raise SafeRegexError('regex capture groups exceed limit')
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
backend/app/services/shipping_notice/document_layout/xfa_signature.py
|
||||
|
||||
用途:计算 XFA template packet checksum、datasets 结构指纹、统一 binding/拆分
|
||||
内容指纹与治理用 structure signature。
|
||||
内容指纹,供 xfa_dataset value adapter 身份复验。
|
||||
依赖:xfa_contract、xfa_dataset.XfaDatasetNode、标准库 hashlib/json。
|
||||
逻辑:由 xfa_analysis / 验证服务调用;指纹忽略业务值与行数;structure signature
|
||||
与 definition checksum 覆盖视觉绑定与拆分规则业务字段。
|
||||
逻辑:由 xfa_analysis / 验证服务调用;指纹忽略业务值与行数;共同 Profile
|
||||
视觉身份只使用 layout_signature,XFA 仅提供末端取值 adapter 证据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,7 +15,6 @@ import json
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XFA_STRUCTURE_SIGNATURE_ID,
|
||||
XfaStructureNodeSpec,
|
||||
XfaUnifiedFieldBinding,
|
||||
canonical_unified_bindings_payload,
|
||||
@@ -100,56 +99,6 @@ def build_signature_summary(
|
||||
}
|
||||
|
||||
|
||||
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),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def compute_unified_bindings_checksum(
|
||||
bindings: list[XfaUnifiedFieldBinding] | list[dict[str, Any]],
|
||||
) -> str:
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/document_layout/xfa_split_preview_token.py
|
||||
|
||||
用途:签发与校验 XFA 拆分规则预览确认令牌,防止客户端自行声明 confirmed。
|
||||
依赖:Flask current_app.SECRET_KEY、hmac、hashlib、time、secrets、redis_client。
|
||||
逻辑:由 preview_xfa_split_rules 签发;save_draft / 确认接口经 verify_and_consume 原子消费 jti;
|
||||
逻辑:由 datasets adapter 的拆分预览签发;共同保存流经 adapter 原子消费 jti;
|
||||
生产/预发/多 Worker:Redis 不可用时 fail-closed(STORE_UNAVAILABLE);
|
||||
仅 TESTING 或单进程 development(ALLOW_MEMORY_JTI)允许进程内兜底。
|
||||
"""
|
||||
|
||||
@@ -371,6 +371,9 @@ def split_rule_content_fingerprint(rule_set: XfaSplitRuleSet | dict[str, Any]) -
|
||||
payload.pop('requires_confirmation', None)
|
||||
payload.pop('rule_version', None)
|
||||
payload.pop('rule_id', None)
|
||||
# 指纹排除映射语义,但不得原地修改 definition_json 中的规则;调用者还会
|
||||
# 将同一规则对象交给 normalize/save,原地 pop 会使已确认草稿不可再次编辑。
|
||||
payload = json.loads(json.dumps(payload))
|
||||
for rule in payload.get('rules') or []:
|
||||
segment = rule.get('segment') if isinstance(rule, dict) else None
|
||||
if not isinstance(segment, dict):
|
||||
|
||||
@@ -1,294 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_template_parser.py
|
||||
|
||||
用途:防御性解析 XFA template packet,提取 field/draw 节点的 bind 引用与近似几何
|
||||
(x/y/w/h 属性),供自研静态合成预览定位回显文本。
|
||||
依赖:lxml、xfa_packets.preflight_xml_bytes、xfa_dataset._hardened_parser 模式。
|
||||
逻辑:由 xfa_preview_renderer 调用;不执行 JS/FormCalc、不联网;解析失败返回空列表。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from lxml import etree
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_packets import XfaPacketError, preflight_xml_bytes
|
||||
|
||||
_DIMENSION_RE = re.compile(
|
||||
r'^\s*(?P<value>-?\d+(?:\.\d+)?)\s*(?P<unit>pt|mm|in|cm|px)?\s*$',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
# 常见页面参考尺寸(Letter pt),仅用于将绝对单位粗略归一化。
|
||||
_DEFAULT_PAGE_WIDTH_PT = 612.0
|
||||
_DEFAULT_PAGE_HEIGHT_PT = 792.0
|
||||
_FIELD_DRAW_LOCAL_NAMES = frozenset({'field', 'draw'})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class XfaTemplateFieldGeometry:
|
||||
"""
|
||||
template 中可定位的 field/draw 摘要。
|
||||
|
||||
坐标为页面相对归一化框(左上原点 0..1);无法可靠归一化时 normalized_bbox 为空。
|
||||
"""
|
||||
|
||||
name: str
|
||||
bind_ref: str
|
||||
page_no: int
|
||||
raw_x: float | None
|
||||
raw_y: float | None
|
||||
raw_w: float | None
|
||||
raw_h: float | None
|
||||
normalized_bbox: dict[str, float] | None
|
||||
local_name: str
|
||||
|
||||
|
||||
def _local_name(tag: str) -> str:
|
||||
"""提取 XML localName,忽略命名空间前缀。"""
|
||||
return str(tag or '').rsplit('}', 1)[-1].lower()
|
||||
|
||||
|
||||
def _hardened_parser() -> etree.XMLParser:
|
||||
"""
|
||||
构造禁用外部实体与 DTD 的 lxml 解析器。
|
||||
|
||||
Returns:
|
||||
与 datasets 解析同策略的安全 XMLParser。
|
||||
"""
|
||||
return etree.XMLParser(
|
||||
resolve_entities=False,
|
||||
load_dtd=False,
|
||||
no_network=True,
|
||||
huge_tree=False,
|
||||
)
|
||||
|
||||
|
||||
def _parse_dimension(raw: str | None) -> float | None:
|
||||
"""
|
||||
解析 XFA 尺寸属性(可带 pt/mm/in/cm/px 后缀)为浮点数。
|
||||
|
||||
核心逻辑:无单位时原样返回数值;有单位时统一换算为 pt(近似)。
|
||||
|
||||
Args:
|
||||
raw: 属性字符串,如 ``36pt``、``10mm``、``0.25``。
|
||||
|
||||
Returns:
|
||||
数值(pt 或无单位原值);无法解析时返回 None。
|
||||
"""
|
||||
text = str(raw or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
match = _DIMENSION_RE.match(text)
|
||||
if not match:
|
||||
return None
|
||||
try:
|
||||
value = float(match.group('value'))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
unit = (match.group('unit') or '').lower()
|
||||
if not unit or unit == 'pt' or unit == 'px':
|
||||
return value
|
||||
if unit == 'in':
|
||||
return value * 72.0
|
||||
if unit == 'mm':
|
||||
return value * 72.0 / 25.4
|
||||
if unit == 'cm':
|
||||
return value * 72.0 / 2.54
|
||||
return value
|
||||
|
||||
|
||||
def _attr(element: etree._Element, *names: str) -> str:
|
||||
"""按候选属性名读取第一个非空值(忽略命名空间前缀)。"""
|
||||
for name in names:
|
||||
for key, value in element.attrib.items():
|
||||
local = str(key).rsplit('}', 1)[-1]
|
||||
if local.lower() == name.lower() and str(value or '').strip():
|
||||
return str(value).strip()
|
||||
return ''
|
||||
|
||||
|
||||
def _extract_bind_ref(element: etree._Element) -> str:
|
||||
"""
|
||||
从 field/draw 或其 bind 子节点提取 dataRef。
|
||||
|
||||
核心逻辑:优先读子节点 ``bind`` 的 ref/dataRef;否则读自身 bind/ref 属性。
|
||||
"""
|
||||
direct = _attr(element, 'bind', 'ref', 'dataRef')
|
||||
if direct:
|
||||
return direct
|
||||
for child in element:
|
||||
if not isinstance(child.tag, str):
|
||||
continue
|
||||
if _local_name(child.tag) != 'bind':
|
||||
continue
|
||||
ref = _attr(child, 'ref', 'dataRef', 'match')
|
||||
if ref and ref.lower() not in {'none', 'dataref', 'once', 'global', 'dataRef'.lower()}:
|
||||
return ref
|
||||
# match="dataRef" 时真正路径常在 ref
|
||||
ref2 = _attr(child, 'ref', 'dataRef')
|
||||
if ref2:
|
||||
return ref2
|
||||
return ''
|
||||
|
||||
|
||||
def _normalize_bbox_from_raw(
|
||||
*,
|
||||
x: float | None,
|
||||
y: float | None,
|
||||
w: float | None,
|
||||
h: float | None,
|
||||
page_width: float,
|
||||
page_height: float,
|
||||
) -> dict[str, float] | None:
|
||||
"""
|
||||
将 template 原始 x/y/w/h 粗略归一化为左上原点 0..1 框。
|
||||
|
||||
核心逻辑:若数值均落在 0..1 则视为已归一化;否则按 page pt 尺寸换算。
|
||||
XFA 模板常以左下为原点,此处按「y 为距底边」尝试翻转;若翻转后越界则按左上解释。
|
||||
|
||||
Args:
|
||||
x/y/w/h: 原始尺寸(pt 或相对)。
|
||||
page_width/page_height: 参考页尺寸(pt)。
|
||||
|
||||
Returns:
|
||||
``{x0,y0,x1,y1}``;无法构成有效框时返回 None。
|
||||
"""
|
||||
if x is None or y is None or w is None or h is None:
|
||||
return None
|
||||
if w <= 0 or h <= 0:
|
||||
return None
|
||||
if page_width <= 0 or page_height <= 0:
|
||||
return None
|
||||
|
||||
# [STEP 1] 已是相对坐标
|
||||
if 0.0 <= x <= 1.0 and 0.0 <= y <= 1.0 and 0.0 < w <= 1.0 and 0.0 < h <= 1.0:
|
||||
x0, y0, x1, y1 = x, y, x + w, y + h
|
||||
else:
|
||||
# [STEP 2] 绝对 pt:优先按 PDF 左下原点翻转
|
||||
x0 = x / page_width
|
||||
x1 = (x + w) / page_width
|
||||
y0_flip = 1.0 - ((y + h) / page_height)
|
||||
y1_flip = 1.0 - (y / page_height)
|
||||
y0_top = y / page_height
|
||||
y1_top = (y + h) / page_height
|
||||
if 0.0 <= y0_flip <= 1.0 and 0.0 <= y1_flip <= 1.0 and y1_flip > y0_flip:
|
||||
y0, y1 = y0_flip, y1_flip
|
||||
else:
|
||||
y0, y1 = y0_top, y1_top
|
||||
|
||||
x0 = max(0.0, min(1.0, x0))
|
||||
x1 = max(0.0, min(1.0, x1))
|
||||
y0 = max(0.0, min(1.0, y0))
|
||||
y1 = max(0.0, min(1.0, y1))
|
||||
if x1 <= x0 or y1 <= y0:
|
||||
return None
|
||||
return {'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1}
|
||||
|
||||
|
||||
def _resolve_page_no(element: etree._Element, default_page: int = 1) -> int:
|
||||
"""从节点或其祖先读取 page/pageNum 属性;非法时回退 default_page。"""
|
||||
current: etree._Element | None = element
|
||||
while current is not None:
|
||||
raw = _attr(current, 'page', 'pageNum', 'page_no')
|
||||
if raw:
|
||||
try:
|
||||
value = int(float(raw))
|
||||
if value >= 1:
|
||||
return value
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
parent = current.getparent()
|
||||
current = parent if isinstance(parent, etree._Element) else None
|
||||
return max(1, int(default_page))
|
||||
|
||||
|
||||
def parse_xfa_template_field_geometries(
|
||||
template_bytes: bytes,
|
||||
*,
|
||||
page_width: float = _DEFAULT_PAGE_WIDTH_PT,
|
||||
page_height: float = _DEFAULT_PAGE_HEIGHT_PT,
|
||||
) -> list[XfaTemplateFieldGeometry]:
|
||||
"""
|
||||
解析 XFA template packet,提取带 bind 与近似位置的 field/draw 节点。
|
||||
|
||||
核心逻辑:preflight → hardened lxml 解析 → 遍历 field/draw;读取 name/bind 与
|
||||
x/y/w/h;失败或不可解析时返回空列表(不抛给调用方)。
|
||||
|
||||
Args:
|
||||
template_bytes: template packet XML 字节。
|
||||
page_width: 用于绝对坐标归一化的参考页宽(pt)。
|
||||
page_height: 用于绝对坐标归一化的参考页高(pt)。
|
||||
|
||||
Returns:
|
||||
几何摘要列表;不可解析时为空列表。
|
||||
"""
|
||||
if not template_bytes:
|
||||
return []
|
||||
try:
|
||||
preflight_xml_bytes(template_bytes)
|
||||
root = etree.fromstring(template_bytes, parser=_hardened_parser())
|
||||
except (XfaPacketError, etree.XMLSyntaxError, ValueError, TypeError, OSError):
|
||||
return []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
results: list[XfaTemplateFieldGeometry] = []
|
||||
for element in root.iter():
|
||||
if not isinstance(element.tag, str):
|
||||
continue
|
||||
local = _local_name(element.tag)
|
||||
if local not in _FIELD_DRAW_LOCAL_NAMES:
|
||||
continue
|
||||
name = _attr(element, 'name') or local
|
||||
bind_ref = _extract_bind_ref(element)
|
||||
x = _parse_dimension(_attr(element, 'x'))
|
||||
y = _parse_dimension(_attr(element, 'y'))
|
||||
w = _parse_dimension(_attr(element, 'w', 'width'))
|
||||
h = _parse_dimension(_attr(element, 'h', 'height'))
|
||||
page_no = _resolve_page_no(element)
|
||||
bbox = _normalize_bbox_from_raw(
|
||||
x=x, y=y, w=w, h=h, page_width=page_width, page_height=page_height,
|
||||
)
|
||||
results.append(XfaTemplateFieldGeometry(
|
||||
name=name,
|
||||
bind_ref=bind_ref,
|
||||
page_no=page_no,
|
||||
raw_x=x,
|
||||
raw_y=y,
|
||||
raw_w=w,
|
||||
raw_h=h,
|
||||
normalized_bbox=bbox,
|
||||
local_name=local,
|
||||
))
|
||||
return results
|
||||
|
||||
|
||||
def serialize_template_field_geometries(
|
||||
items: list[XfaTemplateFieldGeometry],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
将 template 几何摘要序列化为普通字典列表(测试/诊断用)。
|
||||
|
||||
Args:
|
||||
items: parse_xfa_template_field_geometries 结果。
|
||||
|
||||
Returns:
|
||||
可 JSON 化的字典列表。
|
||||
"""
|
||||
return [
|
||||
{
|
||||
'name': item.name,
|
||||
'bind_ref': item.bind_ref,
|
||||
'page_no': item.page_no,
|
||||
'raw_x': item.raw_x,
|
||||
'raw_y': item.raw_y,
|
||||
'raw_w': item.raw_w,
|
||||
'raw_h': item.raw_h,
|
||||
'normalized_bbox': item.normalized_bbox,
|
||||
'local_name': item.local_name,
|
||||
}
|
||||
for item in items
|
||||
]
|
||||
@@ -74,7 +74,7 @@ def _normalize_comparable(value: Any, *, value_type: str | None = None) -> str |
|
||||
"""
|
||||
将 datasets / AcroForm 展示值收敛为可比较的标准化字符串。
|
||||
|
||||
核心逻辑:金额去千分位;日期接受 ISO 与 DD/MM/YYYY;数量去尾随零。
|
||||
核心逻辑:金额去千分位;日期接受 ISO、数字日期及明确英文月份;数量去尾随零。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
@@ -83,7 +83,10 @@ def _normalize_comparable(value: Any, *, value_type: str | None = None) -> str |
|
||||
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')
|
||||
date_patterns = (
|
||||
'%Y-%m-%d', '%Y/%m/%d', '%d/%m/%Y', '%m/%d/%Y', '%d-%m-%Y', '%Y%m%d',
|
||||
'%d-%b-%Y', '%d-%B-%Y',
|
||||
)
|
||||
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:
|
||||
@@ -115,8 +118,10 @@ def _normalize_comparable(value: Any, *, value_type: str | None = None) -> str |
|
||||
return text.casefold()
|
||||
|
||||
|
||||
def _field_map_from_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""从提取行中收集 field_code → value 映射(按行)。"""
|
||||
def _field_map_from_rows(
|
||||
rows: list[dict[str, Any]], *, registered_field_codes: set[str] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""从提取行中收集已正式绑定的 field_code → value 映射(按行)。"""
|
||||
result: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
mapping: dict[str, Any] = {}
|
||||
@@ -124,24 +129,39 @@ def _field_map_from_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
code = str(item.get('field_code') or '').strip()
|
||||
if code:
|
||||
if code and (registered_field_codes is None or code in registered_field_codes):
|
||||
mapping[code] = item.get('value')
|
||||
result.append(mapping)
|
||||
return result
|
||||
|
||||
|
||||
def _line_amount_operands(mapping: dict[str, Any]) -> tuple[Any, Any, Any]:
|
||||
"""读取通用金额恒等式的数量、单价与金额字段。"""
|
||||
return (
|
||||
mapping.get('quantity', mapping.get('qty')),
|
||||
mapping.get('unit_price'),
|
||||
mapping.get('amount', mapping.get('line_amount_with_tax')),
|
||||
)
|
||||
|
||||
|
||||
def _line_amount_expected(*, quantity: Decimal, unit_price: Decimal) -> Decimal:
|
||||
"""计算通用金额恒等式的预期值:数量 × 已归一化单价。"""
|
||||
return quantity * unit_price
|
||||
|
||||
|
||||
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'))
|
||||
quantity_value, unit_price_value, amount_value = _line_amount_operands(mapping)
|
||||
quantity = _to_decimal(quantity_value)
|
||||
unit_price = _to_decimal(unit_price_value)
|
||||
amount = _to_decimal(amount_value)
|
||||
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
|
||||
expected = _line_amount_expected(
|
||||
quantity=quantity,
|
||||
unit_price=unit_price,
|
||||
)
|
||||
if expected.quantize(Decimal('0.01')) != amount.quantize(Decimal('0.01')):
|
||||
# 允许未量化的精确相等。
|
||||
if expected != amount:
|
||||
@@ -150,30 +170,35 @@ def _validate_line_amount_formula(line_maps: list[dict[str, Any]]) -> bool:
|
||||
|
||||
|
||||
def _line_amount_failures(line_maps: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""返回明细金额校验失败的具体行和值,供模板管理员定位映射或数据问题。"""
|
||||
"""返回通用金额恒等式校验失败的具体行和值。"""
|
||||
failures: list[dict[str, Any]] = []
|
||||
for row_index, mapping in enumerate(line_maps, start=1):
|
||||
quantity = _to_decimal(mapping.get('quantity'))
|
||||
unit_price = _to_decimal(mapping.get('unit_price'))
|
||||
amount = _to_decimal(mapping.get('amount'))
|
||||
price_unit = _to_decimal(mapping.get('price_unit')) or Decimal('1')
|
||||
if quantity is None or unit_price is None or amount is None or price_unit == 0:
|
||||
quantity_value, unit_price_value, amount_value = _line_amount_operands(mapping)
|
||||
quantity = _to_decimal(quantity_value)
|
||||
unit_price = _to_decimal(unit_price_value)
|
||||
amount = _to_decimal(amount_value)
|
||||
expected = (
|
||||
_line_amount_expected(
|
||||
quantity=quantity,
|
||||
unit_price=unit_price,
|
||||
)
|
||||
if quantity is not None and unit_price is not None
|
||||
else None
|
||||
)
|
||||
if quantity is None or unit_price is None or amount is None or expected is None:
|
||||
failures.append({
|
||||
'row_index': row_index,
|
||||
'quantity': mapping.get('quantity'),
|
||||
'unit_price': mapping.get('unit_price'),
|
||||
'price_unit': mapping.get('price_unit'),
|
||||
'amount': mapping.get('amount'),
|
||||
'quantity': quantity_value,
|
||||
'unit_price': unit_price_value,
|
||||
'amount': amount_value,
|
||||
'reason': 'missing_or_invalid_operand',
|
||||
})
|
||||
continue
|
||||
expected = (quantity * unit_price) / price_unit
|
||||
if expected.quantize(Decimal('0.01')) != amount.quantize(Decimal('0.01')) and expected != amount:
|
||||
failures.append({
|
||||
'row_index': row_index,
|
||||
'quantity': str(quantity),
|
||||
'unit_price': str(unit_price),
|
||||
'price_unit': str(price_unit),
|
||||
'amount': str(amount),
|
||||
'expected_amount': str(expected),
|
||||
'reason': 'amount_mismatch',
|
||||
@@ -421,6 +446,10 @@ def _validate_acroform(
|
||||
)
|
||||
if not dataset_values:
|
||||
continue
|
||||
# 只有明确指向已确认拆分段的 binding 才能跳过原始 Widget 全文对账;
|
||||
# 不再按字段名猜测“单价/价格单位”复合语义。
|
||||
if binding.split_rule_ref is not None:
|
||||
continue
|
||||
if not acro_values:
|
||||
missing_counterpart += len(dataset_values)
|
||||
continue
|
||||
@@ -719,11 +748,19 @@ def validate_xfa_extraction(
|
||||
summary['acroform_status'] = acro_status
|
||||
summary['acroform_mismatches'] = acro_mismatches
|
||||
|
||||
line_maps = _field_map_from_rows(extraction.rows)
|
||||
registered_line_field_codes = {
|
||||
str(binding.field_code or '') for binding in profile.bindings
|
||||
if binding.scope == 'line' and str(binding.field_code or '').strip()
|
||||
}
|
||||
line_maps = _field_map_from_rows(
|
||||
extraction.rows, registered_field_codes=registered_line_field_codes,
|
||||
)
|
||||
|
||||
# [STEP 3] 明细金额公式
|
||||
if profile.cross_checks.line_amount_formula == 'quantity_times_unit_price':
|
||||
line_amount_failures = _line_amount_failures(line_maps)
|
||||
line_amount_failures = _line_amount_failures(
|
||||
line_maps,
|
||||
)
|
||||
if line_amount_failures:
|
||||
reason_codes.append('xfa_business_validation_failed')
|
||||
summary['line_amount_status'] = 'failed'
|
||||
|
||||
@@ -1,336 +0,0 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_visual_binding.py
|
||||
|
||||
用途:XFA 统一视觉绑定的候选评分、歧义诊断与建议结果组装(纯函数,不写数据库)。
|
||||
依赖:xfa_acroform、xfa_dataset、xfa_contract(归一化框与 path 哈希)。
|
||||
逻辑:由 order_document_profile_visual_binding_service 调用;画框或 Widget 命中后
|
||||
返回 suggested 候选列表与 diagnostics;高置信也不得自动 confirmed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Literal
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_acroform import (
|
||||
XfaAcroformWidget,
|
||||
build_widget_path_candidates,
|
||||
read_acroform_widgets,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import hash_data_path
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import XfaDatasetAnalysis
|
||||
|
||||
|
||||
VisualCandidateStatus = Literal['suggested']
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VisualPathCandidate:
|
||||
"""datasets 路径候选摘要(不含完整 XPath 明文时可仅含 hash)。"""
|
||||
|
||||
path_id: str
|
||||
data_path_hash: str
|
||||
dataset_value_masked: str
|
||||
match_hint: str
|
||||
confidence: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class VisualBindingCandidate:
|
||||
"""单个 Widget/区域视觉绑定候选;status 恒为 suggested,禁止自动 confirmed。"""
|
||||
|
||||
candidate_id: str
|
||||
widget_id: str
|
||||
page_no: int
|
||||
normalized_bbox: dict[str, float]
|
||||
acroform_field_name_tail: str
|
||||
display_value_masked: str
|
||||
path_candidates: list[VisualPathCandidate] = field(default_factory=list)
|
||||
overlap_score: float = 0.0
|
||||
value_match_score: float = 0.0
|
||||
confidence: float = 0.0
|
||||
status: VisualCandidateStatus = 'suggested'
|
||||
|
||||
|
||||
@dataclass
|
||||
class VisualBindingDiagnostics:
|
||||
"""歧义与覆盖诊断;供管理员确认前展示。"""
|
||||
|
||||
candidate_count: int = 0
|
||||
ambiguous: bool = False
|
||||
ambiguity_reason: str | None = None
|
||||
top_confidence: float = 0.0
|
||||
second_confidence: float = 0.0
|
||||
auto_confirm_blocked: bool = True
|
||||
notes: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def _bbox_area(bbox: dict[str, float]) -> float:
|
||||
"""计算归一化框面积;非法框返回 0。"""
|
||||
x0 = float(bbox.get('x0') or 0)
|
||||
y0 = float(bbox.get('y0') or 0)
|
||||
x1 = float(bbox.get('x1') or 0)
|
||||
y1 = float(bbox.get('y1') or 0)
|
||||
if x1 <= x0 or y1 <= y0:
|
||||
return 0.0
|
||||
return (x1 - x0) * (y1 - y0)
|
||||
|
||||
|
||||
def _bbox_intersection_area(a: dict[str, float], b: dict[str, float]) -> float:
|
||||
"""两框交集面积。"""
|
||||
x0 = max(float(a.get('x0') or 0), float(b.get('x0') or 0))
|
||||
y0 = max(float(a.get('y0') or 0), float(b.get('y0') or 0))
|
||||
x1 = min(float(a.get('x1') or 0), float(b.get('x1') or 0))
|
||||
y1 = min(float(a.get('y1') or 0), float(b.get('y1') or 0))
|
||||
if x1 <= x0 or y1 <= y0:
|
||||
return 0.0
|
||||
return (x1 - x0) * (y1 - y0)
|
||||
|
||||
|
||||
def _bbox_overlap_score(region: dict[str, float], widget_bbox: dict[str, float]) -> float:
|
||||
"""
|
||||
区域与 Widget 框重叠得分(IoU 优先,退化时为交集占区域面积比)。
|
||||
|
||||
Args:
|
||||
region: 用户画框或查询区域(0..1)。
|
||||
widget_bbox: AcroForm Widget 归一化框。
|
||||
|
||||
Returns:
|
||||
0..1 重叠得分。
|
||||
"""
|
||||
intersection = _bbox_intersection_area(region, widget_bbox)
|
||||
if intersection <= 0:
|
||||
return 0.0
|
||||
region_area = _bbox_area(region)
|
||||
widget_area = _bbox_area(widget_bbox)
|
||||
union = region_area + widget_area - intersection
|
||||
if union > 0:
|
||||
return intersection / union
|
||||
return intersection / region_area if region_area > 0 else 0.0
|
||||
|
||||
|
||||
def _normalize_compare_value(value: str) -> str:
|
||||
"""值对账用的空白无关规范化。"""
|
||||
return ''.join(str(value or '').casefold().split())
|
||||
|
||||
|
||||
def _value_match_score(display_value: str, dataset_value: str) -> float:
|
||||
"""
|
||||
页面展示值与 datasets 叶子值的标准化匹配分。
|
||||
|
||||
Returns:
|
||||
1.0 精确匹配;0.5 包含关系;0 不匹配。
|
||||
"""
|
||||
left = _normalize_compare_value(display_value)
|
||||
right = _normalize_compare_value(dataset_value)
|
||||
if not left or not right:
|
||||
return 0.0
|
||||
if left == right:
|
||||
return 1.0
|
||||
if left in right or right in left:
|
||||
return 0.5
|
||||
return 0.0
|
||||
|
||||
|
||||
def _candidate_id(widget_id: str, path_id: str) -> str:
|
||||
"""生成稳定的候选 ID(不含敏感明文)。"""
|
||||
digest = hashlib.sha256(f'{widget_id}:{path_id}'.encode('utf-8')).hexdigest()[:16]
|
||||
return f'vbc-{digest}'
|
||||
|
||||
|
||||
def _diagnose_ambiguity(candidates: list[VisualBindingCandidate]) -> VisualBindingDiagnostics:
|
||||
"""
|
||||
诊断候选歧义;同分或接近时标记 ambiguous,且始终阻断自动确认。
|
||||
|
||||
Args:
|
||||
candidates: 已按 confidence 降序排列的候选。
|
||||
|
||||
Returns:
|
||||
诊断摘要。
|
||||
"""
|
||||
diagnostics = VisualBindingDiagnostics(candidate_count=len(candidates))
|
||||
if not candidates:
|
||||
diagnostics.notes.append('no_widget_overlap')
|
||||
return diagnostics
|
||||
diagnostics.top_confidence = float(candidates[0].confidence)
|
||||
if len(candidates) > 1:
|
||||
diagnostics.second_confidence = float(candidates[1].confidence)
|
||||
# [STEP 1] 高置信接近时视为歧义,禁止自动确认
|
||||
if len(candidates) >= 2 and abs(diagnostics.top_confidence - diagnostics.second_confidence) < 0.05:
|
||||
diagnostics.ambiguous = True
|
||||
diagnostics.ambiguity_reason = 'top_candidates_too_close'
|
||||
elif len(candidates) >= 2 and diagnostics.top_confidence >= 0.85 and diagnostics.second_confidence >= 0.75:
|
||||
diagnostics.ambiguous = True
|
||||
diagnostics.ambiguity_reason = 'multiple_high_confidence'
|
||||
top_paths = candidates[0].path_candidates
|
||||
if len(top_paths) > 1:
|
||||
diagnostics.ambiguous = True
|
||||
diagnostics.ambiguity_reason = diagnostics.ambiguity_reason or 'multiple_path_candidates'
|
||||
diagnostics.auto_confirm_blocked = True
|
||||
return diagnostics
|
||||
|
||||
|
||||
def suggest_visual_binding_candidates(
|
||||
*,
|
||||
page_no: int,
|
||||
normalized_bbox: dict[str, float],
|
||||
dataset_analysis: XfaDatasetAnalysis,
|
||||
pdf_bytes: bytes | None = None,
|
||||
widgets: list[XfaAcroformWidget] | None = None,
|
||||
min_overlap: float = 0.05,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为指定页面区域生成 AcroForm Widget → datasets 路径的视觉绑定候选。
|
||||
|
||||
核心逻辑:按框重叠筛选 Widget → 为每个 Widget 生成路径候选 → 综合重叠与值匹配
|
||||
评分;所有候选 status 恒为 suggested,歧义写入 diagnostics。
|
||||
|
||||
Args:
|
||||
page_no: 目标 PDF 页码(1-based)。
|
||||
normalized_bbox: 用户画框或查询区域(0..1,左上原点)。
|
||||
dataset_analysis: 已解析的 datasets 结构。
|
||||
pdf_bytes: 原始 PDF;widgets 未传入时用于读取 AcroForm Widget。
|
||||
widgets: 可选预读 Widget 列表(测试/mock 用)。
|
||||
min_overlap: 最小 IoU/重叠阈值。
|
||||
|
||||
Returns:
|
||||
{candidates, diagnostics, page_no, normalized_bbox} 安全 DTO。
|
||||
"""
|
||||
region = {
|
||||
'x0': float(normalized_bbox.get('x0') or 0),
|
||||
'y0': float(normalized_bbox.get('y0') or 0),
|
||||
'x1': float(normalized_bbox.get('x1') or 0),
|
||||
'y1': float(normalized_bbox.get('y1') or 0),
|
||||
}
|
||||
if _bbox_area(region) <= 0:
|
||||
return {
|
||||
'page_no': int(page_no),
|
||||
'normalized_bbox': region,
|
||||
'candidates': [],
|
||||
'diagnostics': VisualBindingDiagnostics(
|
||||
candidate_count=0,
|
||||
notes=['invalid_region_bbox'],
|
||||
).__dict__,
|
||||
}
|
||||
|
||||
widget_list = list(widgets or [])
|
||||
if not widget_list and pdf_bytes:
|
||||
widget_list = read_acroform_widgets(pdf_bytes)
|
||||
|
||||
candidates: list[VisualBindingCandidate] = []
|
||||
for widget in widget_list:
|
||||
if int(widget.page_no) != int(page_no):
|
||||
continue
|
||||
overlap = _bbox_overlap_score(region, widget.normalized_bbox)
|
||||
if overlap < float(min_overlap):
|
||||
continue
|
||||
path_items = build_widget_path_candidates(
|
||||
widget=widget,
|
||||
dataset_analysis=dataset_analysis,
|
||||
)
|
||||
path_candidates: list[VisualPathCandidate] = []
|
||||
best_value_score = 0.0
|
||||
for item in path_items:
|
||||
value_score = _value_match_score(widget.value, item.get('raw_value') or '')
|
||||
best_value_score = max(best_value_score, value_score)
|
||||
path_candidates.append(VisualPathCandidate(
|
||||
path_id=str(item.get('path_id') or ''),
|
||||
data_path_hash=str(item.get('data_path_hash') or ''),
|
||||
dataset_value_masked=str(item.get('dataset_value_masked') or ''),
|
||||
match_hint=str(item.get('match_hint') or 'unmatched'),
|
||||
confidence=round(min(1.0, overlap * 0.6 + value_score * 0.4), 4),
|
||||
))
|
||||
confidence = round(min(1.0, overlap * 0.55 + best_value_score * 0.45), 4)
|
||||
top_path_id = path_candidates[0].path_id if path_candidates else ''
|
||||
candidates.append(VisualBindingCandidate(
|
||||
candidate_id=_candidate_id(widget.widget_id, top_path_id or widget.widget_id),
|
||||
widget_id=widget.widget_id,
|
||||
page_no=int(widget.page_no),
|
||||
normalized_bbox=dict(widget.normalized_bbox),
|
||||
acroform_field_name_tail=widget.short_name,
|
||||
display_value_masked=widget.value_masked,
|
||||
path_candidates=path_candidates,
|
||||
overlap_score=round(overlap, 4),
|
||||
value_match_score=round(best_value_score, 4),
|
||||
confidence=confidence,
|
||||
status='suggested',
|
||||
))
|
||||
|
||||
candidates.sort(key=lambda item: (-item.confidence, item.widget_id))
|
||||
diagnostics = _diagnose_ambiguity(candidates)
|
||||
|
||||
return {
|
||||
'page_no': int(page_no),
|
||||
'normalized_bbox': region,
|
||||
'candidates': [
|
||||
{
|
||||
'candidate_id': item.candidate_id,
|
||||
'widget_id': item.widget_id,
|
||||
'page_no': item.page_no,
|
||||
'normalized_bbox': item.normalized_bbox,
|
||||
'acroform_field_name_tail': item.acroform_field_name_tail,
|
||||
'display_value_masked': item.display_value_masked,
|
||||
'path_candidates': [
|
||||
{
|
||||
'path_id': path.path_id,
|
||||
'data_path_hash': path.data_path_hash,
|
||||
'dataset_value_masked': path.dataset_value_masked,
|
||||
'match_hint': path.match_hint,
|
||||
'confidence': path.confidence,
|
||||
}
|
||||
for path in item.path_candidates
|
||||
],
|
||||
'overlap_score': item.overlap_score,
|
||||
'value_match_score': item.value_match_score,
|
||||
'confidence': item.confidence,
|
||||
'status': item.status,
|
||||
}
|
||||
for item in candidates
|
||||
],
|
||||
'diagnostics': {
|
||||
'candidate_count': diagnostics.candidate_count,
|
||||
'ambiguous': diagnostics.ambiguous,
|
||||
'ambiguity_reason': diagnostics.ambiguity_reason,
|
||||
'top_confidence': diagnostics.top_confidence,
|
||||
'second_confidence': diagnostics.second_confidence,
|
||||
'auto_confirm_blocked': diagnostics.auto_confirm_blocked,
|
||||
'notes': list(diagnostics.notes),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def visual_binding_audit_snapshot(binding: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
"""
|
||||
提取视觉绑定审计摘要(before/after 用),不含 datasets 明文路径。
|
||||
|
||||
Args:
|
||||
binding: 统一 binding 字典或 None。
|
||||
|
||||
Returns:
|
||||
含 status、bbox、page_no、confidence 的摘要;None 表示无绑定。
|
||||
"""
|
||||
if not isinstance(binding, dict):
|
||||
return None
|
||||
visual = binding.get('visual_binding') if isinstance(binding.get('visual_binding'), dict) else {}
|
||||
if not visual:
|
||||
return None
|
||||
bbox = visual.get('normalized_bbox') if isinstance(visual.get('normalized_bbox'), dict) else {}
|
||||
value = binding.get('value_binding') if isinstance(binding.get('value_binding'), dict) else {}
|
||||
return {
|
||||
'binding_id': binding.get('binding_id'),
|
||||
'field_id': binding.get('field_id'),
|
||||
'field_code': binding.get('field_code'),
|
||||
'status': visual.get('status'),
|
||||
'page_no': visual.get('page_no'),
|
||||
'normalized_bbox': {
|
||||
'x0': bbox.get('x0'),
|
||||
'y0': bbox.get('y0'),
|
||||
'x1': bbox.get('x1'),
|
||||
'y1': bbox.get('y1'),
|
||||
},
|
||||
'source': visual.get('source'),
|
||||
'confidence': visual.get('confidence'),
|
||||
'path_id': value.get('path_id'),
|
||||
'data_path_hash': hash_data_path(str(value.get('data_path') or '')) if value.get('data_path') else None,
|
||||
}
|
||||
Reference in new issue
Block a user