feat(shipping-notice): 增强发货通知与审计功能,支持敏感数据控制与哈希链校验

- 更新发货通知工具 API,剥离不可信的操作人身份字段,确保审计安全
- 引入审计事件的哈希链校验机制,支持数据完整性验证
- 增强订单抽取与审计功能,支持敏感快照的访问控制
- 更新相关模型与服务,确保新功能的完整性与可追溯性
- 完善文档与代码注释,反映新的业务逻辑与审计要求
This commit is contained in:
hugo committed 2026-07-31 08:59:44 +08:00
1 parent 95cdfe66b0
commit d0fe084999
225 files changed
+25923 -6653

No files matched your search

@@ -1,8 +1,9 @@
"""
从 PDF 原生字符坐标重建被 HTML 网格错误拆分的订单表格候选。
依赖:布局 bbox 契约和 PositionedCharacter。调用方必须先提供已人工确认的列锚点;本模块
只按几何、有限内容形态和相邻行连续性生成可审计的 needs_review 候选,绝不自动接受。
依赖:布局 bbox 契约、PositionedCharacter、order_schema.field_rules。
逻辑:调用方提供已确认的列锚点与可配置起行字段;本模块按几何与起行值生成可审计候选;
默认起行锚点为 customer_po_line_no;line_no 作为可识别内部项次亦可绑定。
"""
from __future__ import annotations
@@ -18,8 +19,40 @@ from app.services.shipping_notice.document_layout.text_cell_alignment import Pos
from app.services.shipping_notice.document_layout.order_profile_extractors import extract_profile_field_value
# 客户 PO 行号常见形态(含前导零);起行锚点默认按此形态识别,不做数值归一化。
_LINE_NUMBER_PATTERN = re.compile(r'^(?:0{2,}\d+|\d{1,6})$')
_DELETED_PATTERN = re.compile(r'^\*+itemdeleted\*+$', re.IGNORECASE)
DEFAULT_LINE_START_FIELD_CODE = 'customer_po_line_no'
def resolve_line_start_field_code(value: Any = None) -> str:
"""
规范化模板起行锚点字段编码。
核心逻辑:缺省为客户 PO 行号;字段编码由已冻结的模板定义决定。
Args:
value: 模板配置或调用方传入的字段编码。
Returns:
可用于重建的稳定字段编码。
Raises:
ValueError: 编码为空。
"""
code = str(value or DEFAULT_LINE_START_FIELD_CODE).strip() or DEFAULT_LINE_START_FIELD_CODE
return code
def is_valid_line_start_value(raw: Any) -> bool:
"""
判断抽取文本是否可作为逻辑明细起行值。
核心逻辑:仅折叠空白后做形态校验,保留 ``00010`` 等前导零;不做整数转换。
"""
text = re.sub(r'\s+', '', str(raw or ''))
return bool(text and _LINE_NUMBER_PATTERN.fullmatch(text))
class CoordinateReconstructionModel(BaseModel):
@@ -230,15 +263,19 @@ def reconstruct_coordinate_profile_rows(
initial_fields: dict[str, str] | None = None,
initial_next_offset: int = 0,
include_deleted: bool = False,
line_start_field_code: str | None = None,
include_unanchored_rows: bool = False,
) -> list[CoordinateProfileLogicalRow]:
"""
按 v2 物理行和字段区域合并逻辑明细,不使用 MinerU 的行列结果。
主行必须在其已绑定 ``line_no`` 区域中出现有效行号才启动明细;未满足此条件的
视觉行不会被猜测为新行。随后只按连续 ``row_offset`` 消费 continuation,避免描述
换行、合计或相邻无关表区静默混入当前订单行。``include_deleted`` 仅供标注预览
返回删除行证据;正式解析保持默认值,删除行不会进入业务结果。
主行必须在其已绑定起行锚点字段(默认 ``customer_po_line_no``)中出现有效值才启动明细;
未满足此条件的视觉行不会被猜测为新行。随后只按连续 ``row_offset`` 消费 continuation,
避免描述换行、合计或相邻无关表区静默混入当前订单行。``include_deleted`` 仅供标注预览
返回删除行证据;正式解析保持默认值,删除行不会进入业务结果。仅管理员预览可开启
``include_unanchored_rows``,在没有任何有效起行值时返回待复核的主行字段,不能用于正式解析。
"""
start_field_code = resolve_line_start_field_code(line_start_field_code)
bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox)
ordered_layouts = sorted((item for item in line_layouts if isinstance(item, dict)), key=lambda item: item.get('row_offset', -1))
if not ordered_layouts or [item.get('row_offset') for item in ordered_layouts] != list(range(len(ordered_layouts))):
@@ -291,6 +328,8 @@ def reconstruct_coordinate_profile_rows(
termination_rules=termination_rules or [],
initial_fields=initial_fields,
include_deleted=include_deleted,
line_start_field_code=start_field_code,
include_unanchored_rows=include_unanchored_rows,
)
if relative_y_rows is not None:
return relative_y_rows
@@ -346,12 +385,14 @@ def reconstruct_coordinate_profile_rows(
flush(role='deleted')
continue
main_values, main_issues = values_for(band, ordered_layouts[0])
line_no = re.sub(r'\s+', '', main_values.get('line_no', ''))
if _LINE_NUMBER_PATTERN.fullmatch(line_no):
if is_valid_line_start_value(main_values.get(start_field_code, '')):
flush()
current, sources, next_offset, current_issues = main_values, [row_index], 1, main_issues
continue
if current is None or next_offset >= len(ordered_layouts):
if include_unanchored_rows and main_values:
flush()
current, sources, next_offset, current_issues = main_values, [row_index], 1, main_issues
continue
if not layout_order_valid:
current_issues.append('coordinate_profile_layout_region_mismatch')
@@ -386,15 +427,17 @@ def _reconstruct_relative_y_profile_rows(
termination_rules: list[dict[str, Any]],
initial_fields: dict[str, str] | None,
include_deleted: bool,
line_start_field_code: str,
include_unanchored_rows: bool,
) -> list[CoordinateProfileLogicalRow] | None:
"""
将单个多视觉行物理框按父行内相对 Y 投影到每条重复明细。
只有字段框明确切分了父物理行的纵向子带时才启用;旧模板的整高字段和多物理行
row_offset 继续走原有逐视觉行算法。运行时先用 ``line_no`` 找到每条明细起点,再把
row_offset 继续走原有逐视觉行算法。运行时先用可配置起行字段找到每条明细起点,再把
样例字段的相对 Y 映射到相邻起点之间,避免料号尾数污染下方数量、单位和日期。
"""
if initial_fields or len(ordered_layouts) != 1:
if include_unanchored_rows or initial_fields or len(ordered_layouts) != 1:
return None
layout = ordered_layouts[0]
parent = layout.get('region')
@@ -404,8 +447,11 @@ def _reconstruct_relative_y_profile_rows(
]
if not isinstance(parent, dict) or not _has_relative_y_subregions(parent, fields):
return None
line_field = next((field for field in fields if str(field.get('field_code') or '') == 'line_no'), None)
if line_field is None:
start_field = next(
(field for field in fields if str(field.get('field_code') or '') == line_start_field_code),
None,
)
if start_field is None:
return None
bands = _group_visual_rows(glyphs)
usable_bands: list[tuple[int, list[tuple[int, PositionedCharacter]]]] = []
@@ -417,11 +463,11 @@ def _reconstruct_relative_y_profile_rows(
if not usable_bands:
return []
line_region = _absolute_relative_region(table_bbox, line_field['region'])
start_region = _absolute_relative_region(table_bbox, start_field['region'])
anchors: list[int] = []
for index, (_, band) in enumerate(usable_bands):
line_text = re.sub(r'\s+', '', _text_in_horizontal_region(band, line_region))
if _LINE_NUMBER_PATTERN.fullmatch(line_text):
start_text = _text_in_horizontal_region(band, start_region)
if is_valid_line_start_value(start_text):
anchors.append(index)
if not anchors:
return []
@@ -445,6 +491,7 @@ def _reconstruct_relative_y_profile_rows(
record=record,
expected_indices=field_band_indices,
table_bbox=table_bbox,
line_start_field_code=line_start_field_code,
)
issues.extend(alignment_issues)
for field in fields:
@@ -467,8 +514,7 @@ def _reconstruct_relative_y_profile_rows(
issues.append(f'coordinate_profile_composite_conflict:{extracted_code}')
else:
values[extracted_code] = extracted_value
line_no = re.sub(r'\s+', '', values.get('line_no', ''))
if _LINE_NUMBER_PATTERN.fullmatch(line_no):
if is_valid_line_start_value(values.get(line_start_field_code, '')):
results.append(CoordinateProfileLogicalRow(
fields=values,
source_row_indices=[row_index for row_index, _ in record],
@@ -513,7 +559,7 @@ def suggest_multi_subrow_layouts(
从实际物理行和文本起始位置自动建议动态多行版式。
AI/调用方触发时机:管理员打开坐标重建且不清楚相对边界时调用。算法只负责把
同一明细中的第 1..N 行分组并建议列区间;除可确定的 ``line_no`` 外不猜业务字段,
同一明细中的第 1..N 行分组并建议列区间;除可确定的起行锚点字段外不猜业务字段,
建议结果仍须管理员结合示例文字确认。
Args:
@@ -572,7 +618,7 @@ def suggest_multi_subrow_layouts(
y1=min(1, (y1 - bbox.y0) / (bbox.y1 - bbox.y0)),
column_samples=column_samples,
suggested_field_codes=[
'line_no' if row_offset == 0 and index == line_column else None
DEFAULT_LINE_START_FIELD_CODE if row_offset == 0 and index == line_column else None
for index in range(len(boundaries) - 1)
],
))
@@ -726,29 +772,30 @@ def reconstruct_multi_subrow_table(
characters: list[PositionedCharacter | dict[str, Any]],
table_bbox: LayoutBBox,
subrow_layouts: list[CoordinateSubrowLayout | dict[str, Any]],
line_start_field_code: str = 'line_no',
line_start_field_code: str = DEFAULT_LINE_START_FIELD_CODE,
) -> list[ReconstructedLogicalRow]:
"""
使用每种子行的独立边界,将重叠版式的多条物理行合并为订单明细。
核心逻辑:每个视觉行先按主行布局寻找行号;命中后开始新明细。后续物理行按
核心逻辑:每个视觉行先按主行布局寻找起行锚点;命中后开始新明细。后续物理行按
``row_offset`` 选择第 2..N 行布局,将值直接合并到固定字段,而不是沿用首行列号。
Args:
characters: 表格范围内的原生或 OCR 字符坐标。
table_bbox: 当前数据表页面范围。
subrow_layouts: 主行、补充行和属性行的独立边界及字段映射。
line_start_field_code: 标记新明细的固定字段,默认 ``line_no``。
line_start_field_code: 标记新明细的可配置字段,默认 ``customer_po_line_no``。
Returns:
合并后的逻辑明细;纯表头、说明和合计区域不会返回。
"""
start_field_code = resolve_line_start_field_code(line_start_field_code)
layouts = [
item if isinstance(item, CoordinateSubrowLayout) else CoordinateSubrowLayout.model_validate(item)
for item in subrow_layouts
]
by_offset = {item.row_offset: item for item in layouts}
main = by_offset.get(0)
if main is None or not any(code == line_start_field_code for code in main.column_field_codes):
if main is None or not any(code == start_field_code for code in main.column_field_codes):
raise ValueError('multi-subrow reconstruction requires a main row line-start field')
glyphs = _table_glyphs(characters, table_bbox)
if not glyphs:
@@ -787,8 +834,7 @@ def reconstruct_multi_subrow_table(
continue
main_values = _band_field_values(band, anchors[0])
line_value = re.sub(r'\s+', '', main_values.get(line_start_field_code, ''))
if _LINE_NUMBER_PATTERN.fullmatch(line_value):
if is_valid_line_start_value(main_values.get(start_field_code, '')):
flush()
current_fields = main_values
current_sources = [row_index]
@@ -1008,6 +1054,7 @@ def _match_field_band_groups(
record: list[tuple[int, list[tuple[int, PositionedCharacter]]]],
expected_indices: dict[int, int],
table_bbox: LayoutBBox,
line_start_field_code: str = DEFAULT_LINE_START_FIELD_CODE,
) -> tuple[dict[int, int], list[str]]:
"""将样例纵向字段组单调对齐到运行时 bands;额外换行可插入但组顺序不可倒退。"""
if not record:
@@ -1019,7 +1066,7 @@ def _match_field_band_groups(
issues: list[str] = []
previous_index = -1
for expected_index, group_fields in sorted(groups.items()):
if any(str(field.get('field_code') or '') == 'line_no' for field in group_fields):
if any(str(field.get('field_code') or '') == line_start_field_code for field in group_fields):
selected_index = 0
else:
candidates: list[tuple[float, int]] = []
@@ -1216,8 +1263,8 @@ def _field_content_score(text: str, field_code: str | None) -> float:
if not value or not field_code:
return 0.0
compact = value.replace(',', '').replace(' ', '')
if field_code == 'line_no':
return 1.0 if _LINE_NUMBER_PATTERN.fullmatch(compact) else -1.0
if field_code in {'line_no', DEFAULT_LINE_START_FIELD_CODE, 'customer_po_line_no'}:
return 1.0 if is_valid_line_start_value(compact) else -1.0
if field_code in {'qty', 'unit_price', 'amount', 'line_amount_before_tax', 'line_amount_with_tax'}:
return 1.0 if re.fullmatch(r'[-+]?\d+(?:\.\d+)?', compact) else -1.0
if field_code == 'uom':
@@ -2,7 +2,8 @@
backend/app/services/shipping_notice/document_layout/lifecycle.py
用途:管理 ShippingNoticeDocument 的版面版本、checksum、大小门禁和当前成功快照。
依赖:ShippingDocumentLayoutVersion、Flask 配置、SQLAlchemy Session。
依赖:ShippingDocumentLayoutVersion、Flask 配置、SQLAlchemy Session、workflow_ledger_service
(claim/complete/recovery 尽力同步 WorkflowItem,缺 Item 不阻断版面收口)。
逻辑:相同内容/parser/checksum 幂等复用;失败版本保留审计,只有可用终态更新 Document 当前引用。
"""
@@ -10,6 +11,7 @@ from __future__ import annotations
import hashlib
import json
import logging
from datetime import datetime
from typing import Any
@@ -19,6 +21,8 @@ from sqlalchemy import and_, func, or_, update
from app.extensions import db
from app.models import ShippingDocumentLayoutVersion, ShippingNoticeDocument, ShippingNoticeIntake
_LOGGER = logging.getLogger(__name__)
LAYOUT_PARSER_NAME = 'mineru'
LAYOUT_BACKEND = 'pipeline'
@@ -27,6 +31,97 @@ CURRENT_LAYOUT_STATUSES = frozenset({'ready', 'needs_review'})
TERMINAL_LAYOUT_STATUSES = frozenset({'ready', 'needs_review', 'failed', 'unsupported'})
def _conversation_id_for_document(document_id: int) -> str | None:
"""
从 Document → Intake 解析会话 ID,供 WorkflowItem 定位。
Args:
document_id: ShippingNoticeDocument 主键。
Returns:
conversation_id 或 None。
"""
row = (
db.session.query(ShippingNoticeIntake.conversation_id)
.join(ShippingNoticeDocument, ShippingNoticeDocument.intake_id == ShippingNoticeIntake.id)
.filter(ShippingNoticeDocument.id == int(document_id))
.first()
)
if row is None:
return None
text = str(row[0] or '').strip()
return text or None
def _sync_workflow_item_for_layout(
*,
document_id: int,
lifecycle_status: str | None = None,
event_code: str | None = None,
reason: str | None = None,
) -> None:
"""
尽力同步版面阶段的 WorkflowItem 状态/事件;Item 缺失时仅记日志。
Args:
document_id: 版面所属 Document。
lifecycle_status: 可选目标生命周期(queued/layout_parsing/failed 等)。
event_code: 可选用户可见事件码(如 layout_completed)。
reason: 迁移理由。
"""
try:
from app.models.shipping_notice_workflow import ShippingNoticeWorkflow
from app.services.shipping_notice.workflow_ledger_service import (
append_workflow_event,
find_item_by_root,
transition_item_status,
)
conversation_id = _conversation_id_for_document(int(document_id))
if not conversation_id:
return
item = find_item_by_root(
conversation_id=conversation_id,
root_document_id=int(document_id),
for_update=True,
)
if item is None:
return
if lifecycle_status and str(item.lifecycle_status or '') != str(lifecycle_status):
if str(item.lifecycle_status or '') not in {
'closed', 'cancelled', 'manual_upload_pending', 'pending_review',
}:
transition_item_status(
item=item,
lifecycle_status=str(lifecycle_status),
stage=str(lifecycle_status),
actor_type='system',
actor_id='layout',
reason=reason or f'layout:{lifecycle_status}',
)
if event_code:
workflow = db.session.get(ShippingNoticeWorkflow, int(item.workflow_id))
if workflow is not None:
append_workflow_event(
workflow=workflow,
item=item,
event_code=str(event_code),
stage_code=str(item.current_stage or item.lifecycle_status),
message_code=f'shipping.workflow_item.{event_code}',
actor_type='system',
actor_id='layout',
payload={'document_id': int(document_id)},
reason=reason,
)
except Exception:
_LOGGER.exception(
'layout workflow sync skipped document_id=%s status=%s event=%s',
document_id,
lifecycle_status,
event_code,
)
def current_layout_parser_key() -> str:
"""生成运维可轮转的 parser 身份;Provider/模型升级必须提升 revision 防止复用旧结果。"""
revision = str(current_app.config.get(
@@ -136,6 +231,32 @@ def record_inline_layout_snapshot(
return version
def _clone_reusable_layout_for_document(
document: ShippingNoticeDocument,
reusable: ShippingDocumentLayoutVersion,
) -> ShippingDocumentLayoutVersion | None:
"""
将同一所有者的已完成布局快照本地化到目标 Document。
LayoutVersion 的 document_id 是不可跨文档共享的外键语义;相同内容只能复用
已冻结 payload,不能让目标 Document 指向源 Document 的版本记录。
"""
payload = reusable.payload_json
if not isinstance(payload, dict):
return None
copied_payload = dict(payload)
copied_payload['status'] = str(reusable.status or copied_payload.get('status') or 'failed')
copied_payload.setdefault('provider', reusable.parser_name or LAYOUT_PARSER_NAME)
copied_payload.setdefault('provider_version', reusable.parser_version)
copied_payload.setdefault('backend', reusable.backend or LAYOUT_BACKEND)
copied_payload.setdefault('snapshot_version', reusable.contract_version or LAYOUT_CONTRACT_VERSION)
return record_inline_layout_snapshot(
document,
copied_payload,
parser_key=str(reusable.parser_key or current_layout_parser_key()),
)
def schedule_layout_version(
document: ShippingNoticeDocument,
*,
@@ -175,8 +296,9 @@ def schedule_layout_version(
.first()
)
if reusable_from_owner is not None:
document.current_layout_version_id = reusable_from_owner.id
return reusable_from_owner
localized = _clone_reusable_layout_for_document(document, reusable_from_owner)
if localized is not None:
return localized
active = ShippingDocumentLayoutVersion.query.filter(
ShippingDocumentLayoutVersion.document_id == int(document.id),
ShippingDocumentLayoutVersion.status.in_({'queued', 'running'}),
@@ -357,6 +479,19 @@ def claim_layout_version(
return None
db.session.commit()
version = db.session.get(ShippingDocumentLayoutVersion, int(version_id))
if version is not None:
# [STEP] claim 成功后迁 Item 到 layout_parsing,供工作台在版面阶段可见。
_sync_workflow_item_for_layout(
document_id=int(version.document_id),
lifecycle_status='layout_parsing',
event_code='layout_parsing_started',
reason='claim_layout_version',
)
try:
db.session.commit()
except Exception:
db.session.rollback()
_LOGGER.exception('layout claim workflow commit failed version_id=%s', version_id)
return (version, lease) if version is not None else None
@@ -395,6 +530,25 @@ def complete_layout_version(
if status in CURRENT_LAYOUT_STATUSES:
version.document.current_layout_version_id = version.id
db.session.commit()
# [STEP] 版面完成写用户可见事件;失败版本同步 Item failed。
if status in CURRENT_LAYOUT_STATUSES:
_sync_workflow_item_for_layout(
document_id=int(version.document_id),
event_code='layout_completed',
reason='complete_layout_version',
)
elif status in {'failed', 'unsupported'}:
_sync_workflow_item_for_layout(
document_id=int(version.document_id),
lifecycle_status='failed',
event_code='layout_failed',
reason='complete_layout_version',
)
try:
db.session.commit()
except Exception:
db.session.rollback()
_LOGGER.exception('layout complete workflow commit failed version_id=%s', version_id)
return True
@@ -407,12 +561,24 @@ def sync_layout_after_job_recovery(job: Any) -> None:
version.updated_at = datetime.utcnow()
if str(job.status or '') == 'queued':
version.status = 'queued'
_sync_workflow_item_for_layout(
document_id=int(version.document_id),
lifecycle_status='queued',
event_code='layout_retry_queued',
reason='layout_job_recovery:queued',
)
elif str(job.status or '') in {'failed', 'cancelled'}:
version.status = 'failed'
version.finished_at = datetime.utcnow()
version.issues_json = sorted(set(list(version.issues_json or []) + [
'shipping_document_layout_job_exhausted',
]))
_sync_workflow_item_for_layout(
document_id=int(version.document_id),
lifecycle_status='failed',
event_code='layout_failed',
reason=f'layout_job_recovery:{job.status}',
)
def sync_layout_after_job_failure(job_id: int) -> None:
@@ -34,6 +34,7 @@ class OrderFieldExtraction(BaseModel):
field_id: str
field_code: str
scope: Literal['header']
value: Any = None
status: Literal['confirmed', 'needs_review', 'unavailable']
source: Literal['pdf_coordinate', 'ocr_coordinate'] | None = None
@@ -112,7 +113,10 @@ def _extract_layout(
fallback=True,
))
continue
matches = _find_anchor_matches(glyphs, layout.anchor, page_width=width, page_height=height)
matches = _find_anchor_matches(
glyphs, layout.anchor, page_width=width, page_height=height,
ignore_reference_region=_uses_movable_anchor_value_region(layout=layout, width=width, height=height),
)
if not matches:
reference_anchor = (
_anchor_from_reference_region(
@@ -135,7 +139,7 @@ def _extract_layout(
continue
if len(matches) != 1:
results.append(OrderFieldExtraction(
field_id=layout.field_id, field_code=layout.field_code, status='needs_review', source=source,
field_id=layout.field_id, field_code=layout.field_code, scope=layout.scope, status='needs_review', source=source,
page_no=page_no, issues=['order_field_anchor_ambiguous'],
))
continue
@@ -179,7 +183,7 @@ def _read_value_region(
if layout.value_mode != 'multi_line':
text = text.split('\n', 1)[0].strip()
if layout.value_mode == 'right_of_anchor':
text = text.lstrip(':: ').strip()
text = text.lstrip('::# ').strip()
if str(config.get('value_type') or '') == 'date':
text = _recover_trailing_date_glyph(text=text, glyphs=glyphs, region=region)
if not text:
@@ -197,7 +201,7 @@ def _read_value_region(
if review_issue:
issues.append(review_issue)
return OrderFieldExtraction(
field_id=layout.field_id, field_code=layout.field_code, value=value, status=status, source=source,
field_id=layout.field_id, field_code=layout.field_code, scope=layout.scope, value=value, status=status, source=source,
page_no=page_no, anchor_bbox=anchor_bbox, value_bbox=region,
glyph_indices=[index for index, _item in selected], issues=issues,
)
@@ -272,6 +276,7 @@ def _recover_trailing_date_glyph(*, text: str, glyphs: list[dict[str, Any]], reg
def _find_anchor_matches(
glyphs: list[dict[str, Any]], anchor: AnchorRule, *, page_width: float | None = None, page_height: float | None = None,
ignore_reference_region: bool = False,
) -> list[tuple[LayoutBBox, list[int]]]:
"""在每个视觉行内执行精确标签匹配,返回去重后的字符联合框。"""
expected = [anchor.text, *anchor.aliases]
@@ -285,9 +290,12 @@ def _find_anchor_matches(
row_text = ''.join(str(item.get('text') or '') for _index, item in compact)
# Field anchors are part of the frozen Schema/Profile contract; matching
# them case-sensitively prevents one label from being mistaken for another.
folded = row_text
# PDF text case is not stable across generators (for example ``Billto``
# versus a canvas label ``Bill To``). Whitespace remains folded and exact
# word boundaries below still prevent partial-word matches.
folded = row_text.casefold()
for label in expected:
normalized = re.sub(r'\s+', '', label)
normalized = re.sub(r'\s+', '', label).casefold()
start = 0
while normalized and (position := folded.find(normalized, start)) >= 0:
consumed = compact[position:position + len(normalized)]
@@ -295,7 +303,7 @@ def _find_anchor_matches(
compact, position=position, length=len(normalized), anchor=anchor,
):
bbox = _union_bbox([item for _index, item in consumed])
if _anchor_bbox_in_reference_region(
if ignore_reference_region or _anchor_bbox_in_reference_region(
bbox, anchor=anchor, page_width=page_width, page_height=page_height,
):
matches.append((bbox, [index for index, _item in consumed]))
@@ -303,7 +311,20 @@ def _find_anchor_matches(
unique: dict[tuple[float, float, float, float], tuple[LayoutBBox, list[int]]] = {}
for bbox, indices in matches:
unique[(bbox.x0, bbox.y0, bbox.x1, bbox.y1)] = (bbox, indices)
return list(unique.values())
resolved = list(unique.values())
# An unlocked label may shift between documents, so its reference box must
# not suppress a sole match. When the same label occurs multiple times,
# however, the saved canvas position is decisive evidence for this sample.
if len(resolved) > 1 and anchor.region is not None and page_width and page_height:
positioned = [
item for item in resolved
if _anchor_bbox_in_reference_region(
item[0], anchor=anchor, page_width=page_width, page_height=page_height, enforce=True,
)
]
if len(positioned) == 1:
return positioned
return resolved
def _anchor_occurrence_is_exact(
@@ -331,9 +352,10 @@ def _glyph_gap_is_word_boundary(left: dict[str, Any], right: dict[str, Any]) ->
def _anchor_bbox_in_reference_region(
bbox: LayoutBBox, *, anchor: AnchorRule, page_width: float | None, page_height: float | None,
enforce: bool = False,
) -> bool:
"""锚点配置了参考区时只接受该页相对位置内的命中,避免页眉重复标签干扰。"""
if anchor.region is None:
if anchor.region is None or (not enforce and not anchor.position_locked):
return True
if page_width is None or page_height is None or page_width <= 0 or page_height <= 0:
return False
@@ -448,10 +470,50 @@ def _absolute_anchor_region(region: AnchorRelativeRegion | None, anchor: LayoutB
def _absolute_value_region(*, layout: OrderFieldLayout, anchor: LayoutBBox, width: float, height: float) -> LayoutBBox:
"""优先使用管理员画布绝对值框;旧模板才按锚点偏移投影。"""
"""读取值区;旧版“标签右侧/下方”绝对框自动转换为可移动相对框。"""
if layout.value_region is not None:
region = _absolute_anchor_region(layout.value_region, anchor)
if layout.value_mode == 'right_of_anchor':
# The left edge of a right-side field is semantic, not a canvas
# gap: start at the matched label so font-width differences cannot
# discard the first value character on another document.
return LayoutBBox(x0=anchor.x1, y0=region.y0, x1=region.x1, y1=region.y1)
return region
if _uses_movable_anchor_value_region(layout=layout, width=width, height=height):
# Historical canvas persisted a page box even when the UI said "right of
# anchor". Rebase it onto the actual label to retain that relationship.
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height)
saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height)
reference_width = reference.x1 - reference.x0
reference_height = reference.y1 - reference.y0
relative = AnchorRelativeRegion(
# The old canvas selected a page box, whose left gap depends on
# preceding text. The mode itself is the durable intent: begin at
# the matched label's right edge and retain the configured extent.
x0=1,
y0=0,
x1=1 + (saved.x1 - reference.x1) / reference_width,
y1=1,
)
return _absolute_anchor_region(relative, anchor)
if layout.absolute_value_region is not None:
return _absolute_relative_region(layout.absolute_value_region, width=width, height=height)
return _absolute_anchor_region(layout.value_region, anchor)
raise ValueError('anchored order field has no value region')
def _uses_movable_anchor_value_region(*, layout: OrderFieldLayout, width: float, height: float) -> bool:
"""判断新相对规则或同一行的旧右侧框是否应跟随实际标签移动。"""
if layout.value_region is not None:
return True
if (
layout.absolute_value_region is None or layout.anchor is None or layout.anchor.region is None
or layout.value_mode not in {'right_of_anchor', 'below_anchor'}
):
return False
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height)
saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height)
tolerance = max(reference.y1 - reference.y0, saved.y1 - saved.y0) * 2
return saved.y0 <= reference.y1 + tolerance and reference.y0 <= saved.y1 + tolerance
def _glyph_bbox(glyph: dict[str, Any]) -> LayoutBBox:
@@ -479,7 +541,7 @@ def _unavailable(
anchor_bbox: LayoutBBox | None = None, value_bbox: LayoutBBox | None = None,
) -> OrderFieldExtraction:
"""构造无可用坐标证据的失败关闭结果。"""
return OrderFieldExtraction(field_id=layout.field_id, field_code=layout.field_code, status='unavailable', source=source, page_no=page_no, anchor_bbox=anchor_bbox, value_bbox=value_bbox, issues=[issue])
return OrderFieldExtraction(field_id=layout.field_id, field_code=layout.field_code, scope=layout.scope, status='unavailable', source=source, page_no=page_no, anchor_bbox=anchor_bbox, value_bbox=value_bbox, issues=[issue])
def _review(
@@ -488,7 +550,7 @@ def _review(
) -> OrderFieldExtraction:
"""构造带最小证据索引的人工复核候选。"""
return OrderFieldExtraction(
field_id=layout.field_id, field_code=layout.field_code, status='needs_review', source=source,
field_id=layout.field_id, field_code=layout.field_code, scope=layout.scope, status='needs_review', source=source,
page_no=page_no, anchor_bbox=anchor_bbox, value_bbox=value_bbox,
glyph_indices=[index for index, _item in selected], issues=[issue],
)
@@ -88,6 +88,7 @@ class AnchorRule(OrderProfileModel):
aliases: list[str] = Field(default_factory=list, max_length=16)
match_mode: Literal['exact', 'contains'] = 'contains'
region: RelativeRegion | None = None
position_locked: bool = True
minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate'
@model_validator(mode='after')
@@ -107,6 +108,7 @@ class OrderFieldLayout(OrderProfileModel):
layout_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
field_id: str = Field(min_length=1, max_length=128)
field_code: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
scope: Literal['header']
page_scope: Literal['first_page', 'all_pages', 'exact_page'] = 'first_page'
page_no: int | None = Field(default=None, ge=1)
anchor: AnchorRule | None = None
@@ -149,6 +151,7 @@ class FieldRegion(OrderProfileModel):
field_id: str = Field(min_length=1, max_length=128)
field_code: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
scope: Literal['header', 'line']
region: RelativeRegion
extractor_key: Literal['direct', 'temp_internal_parts', 'quantity_uom', 'amount_currency', 'price_currency'] = 'direct'
allowed_sources: list[Literal['pdf_coordinate', 'ocr_coordinate']] = Field(min_length=1)
@@ -161,8 +164,11 @@ class FieldRegion(OrderProfileModel):
if len(self.allowed_sources) != len(set(self.allowed_sources)):
raise ValueError('field region sources must be unique')
if self.target_fields:
codes = [str(item.get('field_code') or '') for item in self.target_fields]
if len(codes) != len(set(codes)) or self.field_code not in codes:
identities = [
(str(item.get('scope') or ''), str(item.get('field_code') or ''))
for item in self.target_fields
]
if len(identities) != len(set(identities)) or (self.scope, self.field_code) not in identities:
raise ValueError('field region targets must be unique and include field_code')
return self
@@ -242,6 +248,8 @@ class DraftUnboundOrderFieldLayout(OrderProfileModel):
"""复用订单字段的区域互斥与页作用域规则,避免迁移草稿保存坏坐标。"""
OrderFieldLayout(
layout_id=self.layout_id, field_id='draft_unbound', field_code='draft_unbound',
# 未绑定草稿仅保留坐标证据,不属于任何 Schema scope。
scope='header',
page_scope=self.page_scope, page_no=self.page_no, anchor=self.anchor,
value_region=self.value_region, absolute_value_region=self.absolute_value_region,
fallback_value_region=self.fallback_value_region,
@@ -258,6 +266,8 @@ class TableRegionProfile(OrderProfileModel):
page_scope: Literal['first_page', 'all_pages', 'continuation_pages', 'exact_page'] = 'all_pages'
page_no: int | None = Field(default=None, ge=1)
region: RelativeRegion
# 逻辑明细起行锚点;默认客户 PO 行号,可使用任一已绑定明细字段。
line_start_field_code: str = Field(default='customer_po_line_no', pattern=r'^[a-z][a-z0-9_]{0,63}$')
header_layouts: list[HeaderLayout] = Field(default_factory=list)
line_layouts: list[LineLayout] = Field(default_factory=list)
continuation_rule: ContinuationRule = Field(default_factory=ContinuationRule)
@@ -289,6 +299,11 @@ class TableRegionProfile(OrderProfileModel):
fields = [field.field_code for item in self.line_layouts for field in item.field_regions]
if len(fields) != len(set(fields)):
raise ValueError('field_code may bind to only one coordinate region per table')
# 草稿可先框物理行;一旦主行开始绑字段,就必须包含起行锚点。
if self.line_layouts and self.line_layouts[0].field_regions and self.line_start_field_code not in {
field.field_code for field in self.line_layouts[0].field_regions
}:
raise ValueError('main line layout must bind the configured line-start field')
# A physical text band must have exactly one layout interpretation. Allowing
# overlapping header/line regions would reintroduce the cross-row ambiguity
# that v2 coordinate profiles are intended to eliminate.