feat(shipping-notice): 实现滚动履约功能,优化发货通知流程与代码清理
清理废弃的ShippingCase相关代码与依赖,统一使用ShippingNotice直接关联客户数据。调整库存网关依赖规则,支持仅对库存满足或已人工放行的订单行生成发货Excel,实现滚动履约逻辑。
This commit is contained in:
1 parent
7cfd5d167e
commit
1e5aedb9ed
235 files changed
+11394
-9613
No files matched your search
-231
@@ -1,231 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/coordinate_region_source_adapter.py
|
||||
|
||||
用途:CoordinateRegionSourceAdapter——将 Profile.named_regions 圈选的物理区域映射为
|
||||
可直接送入 Split Core 的区域原文 + 可引用 bbox 证据(page_no + 绝对坐标)。
|
||||
依赖:profile_vendor_comments_contract.NamedRegion;coordinate_region_text.read_coordinate_region_text
|
||||
与 visual_glyph_rows + positioned_token_spans(证据粒度生成)。
|
||||
逻辑:不读 MinIO、不查 DB;只接收 caller 已加载的 glyphs/page 字典;严格按 Q14 约定
|
||||
page_scope 规则选择「代表页」——last_page 时从多页集合取末页;失败不抛错,统一
|
||||
返回 status=unavailable + 诊断码,供上游 ProfileFieldSourceMappingService 分支处理。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Literal
|
||||
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import (
|
||||
positioned_token_spans,
|
||||
read_coordinate_region_text,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import (
|
||||
NamedRegion,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class CoordinateRegionEvidence:
|
||||
"""单个命中的 token 级证据——供 Observation.evidence_metadata_json 直接序列化。"""
|
||||
|
||||
page_no: int
|
||||
text: str
|
||||
x0: float # 0..1 归一化
|
||||
x1: float
|
||||
y0: float
|
||||
y1: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class CoordinateRegionSourceResult:
|
||||
"""区域抽取结果——对齐 Split Core 结果形状但不做拆分,仅负责原文渲染。"""
|
||||
|
||||
region_id: str
|
||||
label: str
|
||||
status: Literal['available', 'unavailable']
|
||||
page_no: int | None = None
|
||||
raw_text: str = ''
|
||||
lines: list[str] = field(default_factory=list)
|
||||
evidence_tokens: list[CoordinateRegionEvidence] = field(default_factory=list)
|
||||
diagnostic_code: str | None = None
|
||||
diagnostic_message: str | None = None
|
||||
|
||||
|
||||
class CoordinateRegionSourceAdapter:
|
||||
"""
|
||||
将 NamedRegion → 原文 + 证据的薄适配器。
|
||||
|
||||
【AI 触发时机】:三来源收集阶段,上游遍历 field_source_mappings[].vendor_comments_enabled
|
||||
条目并引用命名区域 ID 时调用。
|
||||
|
||||
核心逻辑:
|
||||
[STEP 1] 按 page_scope 从 page_glyphs_map 中选「代表页」:
|
||||
first_page → pages[0];last_page → pages[-1];all_pages 只看 p0(仅用于区域);
|
||||
exact_page → 严格匹配 1-based page_no。
|
||||
[STEP 2] 调 read_coordinate_region_text 取区域原文(0..1 归一化坐标)。
|
||||
[STEP 3] 调 positioned_token_spans 生成 token 级 bbox 证据,用于 Review 高亮点位。
|
||||
[STEP 4] 原文按换行拆为 lines,供后续 execute_base_split_rule_set(..., lines=) 复用。
|
||||
|
||||
Args:
|
||||
region: NamedRegion 契约对象(已通过 validate_assignment 校验)。
|
||||
page_glyphs_map: {1-based_page_no: {'glyphs': [...], 'page': {'width','height'}}} ——
|
||||
caller 负责按当前 Document 加载,本类无网络 IO。
|
||||
"""
|
||||
|
||||
def __init__(self, region: NamedRegion, page_glyphs_map: dict[int, dict[str, Any]]):
|
||||
self.region = region
|
||||
self.page_glyphs_map = page_glyphs_map
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 对外入口
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def extract(self) -> CoordinateRegionSourceResult:
|
||||
"""
|
||||
执行区域抽取。失败不抛异常,统一置 status=unavailable + 稳定诊断码。
|
||||
|
||||
Returns:
|
||||
CoordinateRegionSourceResult,上游据此决定是否跳过 Vendor Comments 来源。
|
||||
"""
|
||||
# [STEP 1] 选择代表页
|
||||
page_no = self._resolve_representative_page_no()
|
||||
if page_no is None:
|
||||
return CoordinateRegionSourceResult(
|
||||
region_id=self.region.region_id,
|
||||
label=self.region.label,
|
||||
status='unavailable',
|
||||
diagnostic_code='named_region_page_not_found',
|
||||
diagnostic_message=(
|
||||
f'named region {self.region.region_id!r} page_scope={self.region.page_scope} '
|
||||
f'page_no={self.region.page_no!r} has no loaded page'
|
||||
),
|
||||
)
|
||||
page_bundle = self.page_glyphs_map[page_no]
|
||||
glyphs = list(page_bundle.get('glyphs') or [])
|
||||
page = dict(page_bundle.get('page') or {})
|
||||
if not glyphs or 'width' not in page or 'height' not in page:
|
||||
return CoordinateRegionSourceResult(
|
||||
region_id=self.region.region_id,
|
||||
label=self.region.label,
|
||||
status='unavailable',
|
||||
page_no=page_no,
|
||||
diagnostic_code='named_region_empty_glyphs',
|
||||
diagnostic_message='region target page has empty glyphs or missing page size',
|
||||
)
|
||||
|
||||
region_coords = {
|
||||
'x0': self.region.region.x0, 'y0': self.region.region.y0,
|
||||
'x1': self.region.region.x1, 'y1': self.region.region.y1,
|
||||
}
|
||||
|
||||
# [STEP 2] 渲染区域原文
|
||||
raw_text = read_coordinate_region_text(
|
||||
glyphs=glyphs, page=page, region=region_coords,
|
||||
)
|
||||
if not raw_text.strip():
|
||||
return CoordinateRegionSourceResult(
|
||||
region_id=self.region.region_id,
|
||||
label=self.region.label,
|
||||
status='unavailable',
|
||||
page_no=page_no,
|
||||
diagnostic_code='named_region_text_empty',
|
||||
diagnostic_message=f'named region {self.region.region_id!r} has empty body text',
|
||||
)
|
||||
|
||||
# [STEP 3] 生成 token 级证据(只保留区域中心在 box 内的 token)
|
||||
tokens = self._collect_region_evidence_tokens(
|
||||
glyphs=glyphs, page=page, region_coords=region_coords, page_no=page_no,
|
||||
)
|
||||
|
||||
# [STEP 4] 拆行
|
||||
lines = [ln.strip() for ln in raw_text.splitlines() if ln.strip()]
|
||||
|
||||
return CoordinateRegionSourceResult(
|
||||
region_id=self.region.region_id,
|
||||
label=self.region.label,
|
||||
status='available',
|
||||
page_no=page_no,
|
||||
raw_text=raw_text.strip(),
|
||||
lines=lines,
|
||||
evidence_tokens=tokens,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 内部帮助
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _resolve_representative_page_no(self) -> int | None:
|
||||
"""按 page_scope 规则选择代表页。"""
|
||||
sorted_pages = sorted(self.page_glyphs_map.keys())
|
||||
if not sorted_pages:
|
||||
return None
|
||||
scope = self.region.page_scope
|
||||
if scope == 'first_page':
|
||||
return sorted_pages[0]
|
||||
if scope == 'last_page':
|
||||
return sorted_pages[-1]
|
||||
if scope == 'all_pages':
|
||||
# all_pages 的命名区域仅在第一页渲染(常见全页 Header);
|
||||
# 若管理员要取多页块,应拆为多个命名区域并使用 exact_page。
|
||||
return sorted_pages[0]
|
||||
if scope == 'exact_page':
|
||||
return self.region.page_no if self.region.page_no in self.page_glyphs_map else None
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _collect_region_evidence_tokens(
|
||||
*,
|
||||
glyphs: list[dict[str, Any]],
|
||||
page: dict[str, Any],
|
||||
region_coords: dict[str, float],
|
||||
page_no: int,
|
||||
) -> list[CoordinateRegionEvidence]:
|
||||
"""筛选命名区域中心范围内的 token,并返回 0..1 归一化 bbox。"""
|
||||
width, height = float(page['width']), float(page['height'])
|
||||
rx0, ry0, rx1, ry1 = (region_coords[k] for k in ('x0', 'y0', 'x1', 'y1'))
|
||||
all_spans = positioned_token_spans(glyphs, respect_explicit_spaces=True)
|
||||
selected: list[CoordinateRegionEvidence] = []
|
||||
for span in all_spans:
|
||||
sx0 = float(span['x0']) / width
|
||||
sx1 = float(span['x1']) / width
|
||||
text = str(span.get('text') or '')
|
||||
# y 边界:span 只返回横向边界;glyphs 中心用于 y 判定
|
||||
# positioned_token_spans 不返回 y,重算 y0/y1 需回溯原 glyph——这里直接用
|
||||
# glyphs 子集重算以保证引用不泄漏。
|
||||
matched = [
|
||||
g for g in glyphs
|
||||
if _glyph_intersects_span(g, span, width) and _glyph_in_region_center(g, width, height, rx0, ry0, rx1, ry1)
|
||||
]
|
||||
if not matched:
|
||||
continue
|
||||
min_y0 = min(float(g['bbox']['y0']) / height for g in matched)
|
||||
max_y1 = max(float(g['bbox']['y1']) / height for g in matched)
|
||||
selected.append(CoordinateRegionEvidence(
|
||||
page_no=page_no,
|
||||
text=text,
|
||||
x0=sx0, x1=sx1,
|
||||
y0=min_y0, y1=max_y1,
|
||||
))
|
||||
return selected
|
||||
|
||||
|
||||
def _glyph_intersects_span(glyph: dict[str, Any], span: dict[str, Any], width: float) -> bool:
|
||||
try:
|
||||
gx0 = float(glyph['bbox']['x0']) / width
|
||||
gx1 = float(glyph['bbox']['x1']) / width
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return False
|
||||
return min(gx1, float(span['x1']) / width) > max(gx0, float(span['x0']) / width)
|
||||
|
||||
|
||||
def _glyph_in_region_center(
|
||||
glyph: dict[str, Any], width: float, height: float,
|
||||
rx0: float, ry0: float, rx1: float, ry1: float,
|
||||
) -> bool:
|
||||
try:
|
||||
b = glyph['bbox']
|
||||
cx = (float(b['x0']) + float(b['x1'])) / (2 * width)
|
||||
cy = (float(b['y0']) + float(b['y1'])) / (2 * height)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return False
|
||||
return rx0 <= cx <= rx1 and ry0 <= cy <= ry1
|
||||
+467
-41
@@ -22,6 +22,7 @@ from app.services.shipping_notice.document_layout.coordinate_transform import (
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import render_positioned_row
|
||||
from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter
|
||||
from app.services.shipping_notice.document_layout.order_profile_extractors import extract_profile_field_value
|
||||
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
|
||||
@@ -31,6 +32,186 @@ _DELETED_PATTERN = re.compile(r'^\*+itemdeleted\*+$', re.IGNORECASE)
|
||||
DEFAULT_LINE_START_FIELD_CODE = 'customer_po_line_no'
|
||||
|
||||
|
||||
def reconstruction_exclusion_regions(
|
||||
table_region: dict[str, Any], *, include_header_layouts: bool = False,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""返回明细重建的显式普通排除区;表头框只保留作语义和预览证据。"""
|
||||
exclusions = [
|
||||
dict(item) for item in (table_region.get('exclusion_regions') or [])
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
if include_header_layouts:
|
||||
exclusions.extend(
|
||||
dict(item['region'])
|
||||
for item in (table_region.get('header_layouts') or [])
|
||||
if isinstance(item, dict) and isinstance(item.get('region'), dict)
|
||||
)
|
||||
return exclusions
|
||||
|
||||
|
||||
def coordinate_profile_character_candidates(
|
||||
*,
|
||||
table_region: dict[str, Any],
|
||||
reference_page_frame: dict[str, Any] | None = None,
|
||||
page_size: dict[str, Any],
|
||||
page_characters: list[dict[str, Any]] | None,
|
||||
table_characters: list[dict[str, Any]] | None,
|
||||
raw_table_bbox: dict[str, Any] | None = None,
|
||||
table_id: str | None = None,
|
||||
page_no: int = 1,
|
||||
coordinate_transform: dict[str, Any] | None = None,
|
||||
allow_table_fallback: bool = True,
|
||||
) -> tuple[list[dict[str, Any]] | None, dict[str, float] | None]:
|
||||
"""按统一契约选择当前表区字符:整页证据优先,真实表框仅扩展纵向范围。
|
||||
|
||||
模板区域的横向边界始终有效;真实物理表的纵向边界用于覆盖跨行表框。
|
||||
缺少整页证据时仅回退到该表的冻结字符,不把其它页面或其它表带入。
|
||||
"""
|
||||
try:
|
||||
page_bbox = {
|
||||
'x0': 0.0, 'y0': 0.0,
|
||||
'x1': float(page_size['width']), 'y1': float(page_size['height']),
|
||||
}
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None, None
|
||||
if page_bbox['x1'] <= 0 or page_bbox['y1'] <= 0:
|
||||
return None, None
|
||||
projected = apply_coordinate_transform_to_region(
|
||||
table_region, coordinate_transform=coordinate_transform,
|
||||
)
|
||||
if projected is None:
|
||||
return None, page_bbox
|
||||
try:
|
||||
reference_width = float(reference_page_frame['width']) if reference_page_frame is not None else page_bbox['x1']
|
||||
reference_height = float(reference_page_frame['height']) if reference_page_frame is not None else page_bbox['y1']
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None, page_bbox
|
||||
if reference_width <= 0 or reference_height <= 0:
|
||||
return None, page_bbox
|
||||
region_bbox = {
|
||||
'x0': projected['x0'] * reference_width, 'y0': projected['y0'] * reference_height,
|
||||
'x1': projected['x1'] * reference_width, 'y1': projected['y1'] * reference_height,
|
||||
}
|
||||
is_virtual_page = str(table_id or '') == f'page-{int(page_no)}'
|
||||
if not is_virtual_page and isinstance(raw_table_bbox, dict):
|
||||
try:
|
||||
if not (
|
||||
float(raw_table_bbox['x0']) < region_bbox['x1']
|
||||
and float(raw_table_bbox['x1']) > region_bbox['x0']
|
||||
and float(raw_table_bbox['y0']) < region_bbox['y1']
|
||||
and float(raw_table_bbox['y1']) > region_bbox['y0']
|
||||
):
|
||||
return None, page_bbox
|
||||
evidence_bbox = dict(region_bbox)
|
||||
evidence_bbox['y0'] = min(region_bbox['y0'], float(raw_table_bbox['y0']))
|
||||
evidence_bbox['y1'] = max(region_bbox['y1'], float(raw_table_bbox['y1']))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None, page_bbox
|
||||
else:
|
||||
evidence_bbox = region_bbox
|
||||
if isinstance(page_characters, list):
|
||||
page_candidates = [
|
||||
item for item in page_characters
|
||||
if isinstance(item, dict) and _character_center_in_region(item, evidence_bbox)
|
||||
]
|
||||
# 页级快照可能只包含订单头或被上游裁剪过;空的页级候选不能遮蔽
|
||||
# 当前物理表仍然有效的冻结字符证据。
|
||||
if page_candidates:
|
||||
return page_candidates, page_bbox
|
||||
if allow_table_fallback and isinstance(table_characters, list):
|
||||
return table_characters, page_bbox
|
||||
return None, page_bbox
|
||||
|
||||
|
||||
def _character_center_in_region(character: dict[str, Any], region: dict[str, float]) -> bool:
|
||||
"""判断字符中心点是否落入绝对坐标区域。"""
|
||||
bbox = character.get('bbox') if isinstance(character.get('bbox'), dict) else None
|
||||
if bbox is None:
|
||||
return False
|
||||
try:
|
||||
center_x = (float(bbox['x0']) + float(bbox['x1'])) / 2
|
||||
center_y = (float(bbox['y0']) + float(bbox['y1'])) / 2
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return False
|
||||
return region['x0'] <= center_x <= region['x1'] and region['y0'] <= center_y <= region['y1']
|
||||
|
||||
|
||||
def reconstruct_coordinate_profile_rows_with_strategy(
|
||||
*,
|
||||
characters: list[PositionedCharacter | dict[str, Any]],
|
||||
table_bbox: LayoutBBox | dict[str, Any],
|
||||
line_layouts: list[dict[str, Any]],
|
||||
table_region: dict[str, Any] | None = None,
|
||||
termination_rules: list[dict[str, Any]] | None = None,
|
||||
exclusion_regions: list[dict[str, Any]] | None = None,
|
||||
dynamic_exclusion_regions: list[dict[str, Any]] | None = None,
|
||||
line_start_field_code: str | None = None,
|
||||
include_deleted: bool = False,
|
||||
schema_field_metadata: list[dict[str, Any]] | None = None,
|
||||
initial_fields: dict[str, str] | None = None,
|
||||
initial_next_offset: int = 0,
|
||||
coordinate_transform: dict[str, Any] | None = None,
|
||||
page_no: int = 1,
|
||||
) -> tuple[list['CoordinateProfileLogicalRow'], Any]:
|
||||
"""统一评估 fixed/adaptive/dynamic,并返回唯一安全的坐标明细结果。"""
|
||||
from app.services.shipping_notice.document_layout.runtime_parse_strategy import (
|
||||
resolve_runtime_parse_strategy,
|
||||
)
|
||||
|
||||
fixed_rows = reconstruct_coordinate_profile_rows(
|
||||
characters=characters, table_bbox=table_bbox, line_layouts=line_layouts,
|
||||
table_region=table_region, termination_rules=termination_rules,
|
||||
exclusion_regions=exclusion_regions, line_start_field_code=line_start_field_code,
|
||||
include_deleted=include_deleted, row_reconstruction_mode='fixed_subrows',
|
||||
schema_field_metadata=schema_field_metadata, initial_fields=initial_fields,
|
||||
initial_next_offset=initial_next_offset, coordinate_transform=coordinate_transform,
|
||||
)
|
||||
adaptive_rows = reconstruct_coordinate_profile_rows(
|
||||
characters=characters, table_bbox=table_bbox, line_layouts=line_layouts,
|
||||
table_region=table_region, termination_rules=termination_rules,
|
||||
exclusion_regions=exclusion_regions, line_start_field_code=line_start_field_code,
|
||||
include_deleted=include_deleted, row_reconstruction_mode='adaptive_record_columns',
|
||||
schema_field_metadata=schema_field_metadata, initial_fields=initial_fields,
|
||||
initial_next_offset=initial_next_offset, coordinate_transform=coordinate_transform,
|
||||
)
|
||||
dynamic_rows = reconstruct_coordinate_profile_rows(
|
||||
characters=characters, table_bbox=table_bbox, line_layouts=line_layouts,
|
||||
table_region=table_region, termination_rules=termination_rules,
|
||||
exclusion_regions=dynamic_exclusion_regions or [], line_start_field_code=line_start_field_code,
|
||||
include_deleted=include_deleted, row_reconstruction_mode='dynamic_x_columns',
|
||||
schema_field_metadata=schema_field_metadata, initial_fields=initial_fields,
|
||||
initial_next_offset=initial_next_offset, coordinate_transform=coordinate_transform,
|
||||
)
|
||||
|
||||
def strategy_rows(rows: list[CoordinateProfileLogicalRow]) -> list[dict[str, Any]]:
|
||||
return [
|
||||
{
|
||||
'status': 'parsed' if not row.issues else 'needs_review',
|
||||
'issues': list(row.issues),
|
||||
'fields': [
|
||||
{'field_code': code, 'value': value}
|
||||
for code, value in row.fields.items()
|
||||
],
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
strategy = resolve_runtime_parse_strategy(
|
||||
page_glyphs={str(page_no): characters},
|
||||
fixed_rows=strategy_rows(fixed_rows),
|
||||
adaptive_rows=strategy_rows(adaptive_rows),
|
||||
dynamic_rows=strategy_rows(dynamic_rows),
|
||||
)
|
||||
if strategy.status != 'selected' or strategy.row_mode is None:
|
||||
return [], strategy
|
||||
return (
|
||||
fixed_rows if strategy.row_mode == 'fixed_subrows'
|
||||
else adaptive_rows if strategy.row_mode == 'adaptive_record_columns'
|
||||
else dynamic_rows,
|
||||
strategy,
|
||||
)
|
||||
|
||||
|
||||
def resolve_line_start_field_code(value: Any = None) -> str:
|
||||
"""
|
||||
规范化模板起行锚点字段编码。
|
||||
@@ -60,6 +241,59 @@ def is_valid_line_start_value(raw: Any) -> bool:
|
||||
return bool(text and _LINE_NUMBER_PATTERN.fullmatch(text))
|
||||
|
||||
|
||||
def _is_record_start(
|
||||
values: dict[str, str],
|
||||
fields: list[dict[str, Any]],
|
||||
line_start_field_code: str,
|
||||
schema_fields: dict[str, dict[str, Any]] | None = None,
|
||||
) -> bool:
|
||||
"""用冻结 Schema 的字段类型/校验结果确认明细起行,不依赖业务字段名或列序。"""
|
||||
if schema_fields is None:
|
||||
start_value = values.get(line_start_field_code, '')
|
||||
return is_valid_line_start_value(start_value)
|
||||
start_field_configured = any(
|
||||
str(field.get('field_code') or '') == line_start_field_code for field in fields
|
||||
)
|
||||
start_value = values.get(line_start_field_code, '')
|
||||
def schema_valid(code: str, raw: str) -> bool:
|
||||
config = schema_fields.get(code)
|
||||
if not config or not str(raw or '').strip():
|
||||
return False
|
||||
try:
|
||||
normalized = normalize_order_field_value(raw, config)
|
||||
except Exception:
|
||||
return False
|
||||
return normalized not in (None, '') and validate_order_field_value(normalized, config)
|
||||
|
||||
# 起行字段的 Schema 类型只负责保留/解析值;它被模板配置为起行锚点后,
|
||||
# 还必须满足通用行号形态,避免 string 字段把表头文本(如 ``0rd``/``B``)
|
||||
# 当成明细起点。该规则只作用于配置的锚点,不依赖任何业务字段名。
|
||||
has_start_anchor = (
|
||||
is_valid_line_start_value(start_value)
|
||||
and schema_valid(line_start_field_code, start_value)
|
||||
)
|
||||
corroborating = sum(
|
||||
1 for field in fields
|
||||
if (code := str(field.get('field_code') or ''))
|
||||
and code != line_start_field_code
|
||||
and schema_valid(code, values.get(code, ''))
|
||||
)
|
||||
configured_corroborating_fields = sum(
|
||||
1 for field in fields
|
||||
if (code := str(field.get('field_code') or ''))
|
||||
and code != line_start_field_code
|
||||
and code in schema_fields
|
||||
)
|
||||
if has_start_anchor:
|
||||
# 若模板只绑定起行字段,Schema 没有第二个坐标字段可供交叉验证,
|
||||
# 允许该锚点单独起行;一旦存在其它已绑定字段,必须有至少一个有效值。
|
||||
return corroborating >= 1 or configured_corroborating_fields == 0
|
||||
# A profile that explicitly configures a start field must not silently fall back
|
||||
# to unrelated fields when that anchor is absent. Profiles without such a field
|
||||
# may use a position-independent two-field business signature.
|
||||
return not start_field_configured and corroborating >= 2
|
||||
|
||||
|
||||
|
||||
class CoordinateReconstructionModel(BaseModel):
|
||||
"""为坐标重建的中间证据启用严格契约,禁止调用方注入未定义字段。"""
|
||||
@@ -272,8 +506,9 @@ def reconstruct_coordinate_profile_rows(
|
||||
include_deleted: bool = False,
|
||||
line_start_field_code: str | None = None,
|
||||
include_unanchored_rows: bool = False,
|
||||
row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns'] = 'fixed_subrows',
|
||||
row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns'] = 'fixed_subrows',
|
||||
coordinate_transform: dict[str, Any] | None = None,
|
||||
schema_field_metadata: list[dict[str, Any]] | None = None,
|
||||
) -> list[CoordinateProfileLogicalRow]:
|
||||
"""
|
||||
按 v2 物理行和字段区域合并逻辑明细,不使用 MinerU 的行列结果。
|
||||
@@ -301,6 +536,16 @@ def reconstruct_coordinate_profile_rows(
|
||||
termination_rules = projected['termination_rules']
|
||||
exclusion_regions = projected['exclusion_regions']
|
||||
start_field_code = resolve_line_start_field_code(line_start_field_code)
|
||||
schema_fields = {
|
||||
str(item.get('field_code') or ''): item
|
||||
for item in (schema_field_metadata or [])
|
||||
if (
|
||||
isinstance(item, dict)
|
||||
and item.get('field_code')
|
||||
and item.get('enabled', True)
|
||||
and str(item.get('scope') or '') == 'line'
|
||||
)
|
||||
} if schema_field_metadata is not None else None
|
||||
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))):
|
||||
@@ -322,6 +567,11 @@ def reconstruct_coordinate_profile_rows(
|
||||
_absolute_relative_region(bbox, item)
|
||||
for item in (exclusion_regions or []) if isinstance(item, dict)
|
||||
]
|
||||
# 直接调用动态候选时,传入的旧式排除区无法区分表头/普通排除;为兼容其
|
||||
# “表头可移动”语义不应用它。统一入口则显式传入 dynamic_exclusion_regions,
|
||||
# 从而保留管理员配置的普通排除区。
|
||||
if row_reconstruction_mode == 'dynamic_x_columns':
|
||||
exclusions = []
|
||||
# [STEP 1] 删除文字不是全局业务规则;只有管理员用排除区显式圈定后才授权删除上一条明细。
|
||||
marker_indices: set[int] = set()
|
||||
authorized_marker_indices: set[int] = set()
|
||||
@@ -353,6 +603,16 @@ def reconstruct_coordinate_profile_rows(
|
||||
|
||||
# This mode is opt-in per table region. It supports documents whose stable
|
||||
# columns stay put while optional descriptions move values across visual rows.
|
||||
if row_reconstruction_mode == 'dynamic_x_columns':
|
||||
return _reconstruct_dynamic_x_columns_profile_rows(
|
||||
glyphs=glyphs,
|
||||
table_bbox=bbox,
|
||||
ordered_layouts=ordered_layouts,
|
||||
termination_rules=termination_rules or [],
|
||||
include_deleted=include_deleted,
|
||||
line_start_field_code=start_field_code,
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
if row_reconstruction_mode == 'adaptive_record_columns':
|
||||
return _reconstruct_adaptive_record_columns_profile_rows(
|
||||
glyphs=glyphs,
|
||||
@@ -361,6 +621,7 @@ def reconstruct_coordinate_profile_rows(
|
||||
termination_rules=termination_rules or [],
|
||||
include_deleted=include_deleted,
|
||||
line_start_field_code=start_field_code,
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
|
||||
relative_y_rows = _reconstruct_relative_y_profile_rows(
|
||||
@@ -372,6 +633,7 @@ def reconstruct_coordinate_profile_rows(
|
||||
include_deleted=include_deleted,
|
||||
line_start_field_code=start_field_code,
|
||||
include_unanchored_rows=include_unanchored_rows,
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
if relative_y_rows is not None:
|
||||
return relative_y_rows
|
||||
@@ -434,7 +696,7 @@ def reconstruct_coordinate_profile_rows(
|
||||
flush(role='deleted')
|
||||
continue
|
||||
main_values, main_evidence, main_issues = values_for(band, ordered_layouts[0])
|
||||
if is_valid_line_start_value(main_values.get(start_field_code, '')):
|
||||
if _is_record_start(main_values, ordered_layouts[0].get('field_regions') or [], start_field_code, schema_fields):
|
||||
flush()
|
||||
current, current_evidence = main_values, main_evidence
|
||||
sources, next_offset, current_issues = [row_index], 1, main_issues
|
||||
@@ -553,6 +815,7 @@ def _reconstruct_adaptive_record_columns_profile_rows(
|
||||
termination_rules: list[dict[str, Any]],
|
||||
include_deleted: bool,
|
||||
line_start_field_code: str,
|
||||
schema_fields: dict[str, dict[str, Any]] | None = None,
|
||||
) -> list[CoordinateProfileLogicalRow]:
|
||||
"""按起行锚点分段,并在每段内用字段列及格式读取可变视觉子行。"""
|
||||
main_fields = ordered_layouts[0].get('field_regions') or []
|
||||
@@ -583,6 +846,7 @@ def _reconstruct_adaptive_record_columns_profile_rows(
|
||||
main_fields=main_fields,
|
||||
table_bbox=table_bbox,
|
||||
line_start_field_code=line_start_field_code,
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
]
|
||||
results: list[CoordinateProfileLogicalRow] = []
|
||||
@@ -597,6 +861,17 @@ def _reconstruct_adaptive_record_columns_profile_rows(
|
||||
for field in fields:
|
||||
code = str(field['field_code'])
|
||||
region = _absolute_relative_region(table_bbox, field['region'])
|
||||
# 自适应列模式只能为单视觉 band 选择候选。若 Schema 绑定的
|
||||
# 字段框明确跨越多个 band(如换行客户料号),该模式的单 band
|
||||
# 候选必然不完整,必须交给 fixed 几何重建处理。
|
||||
if schema_fields is not None:
|
||||
intersecting = [
|
||||
band for _row_index, band in record
|
||||
if _regions_overlap_vertically(region, _band_bbox(band))
|
||||
]
|
||||
if len(intersecting) > 1:
|
||||
issues.append(f'coordinate_profile_field_band_ambiguous:{code}')
|
||||
continue
|
||||
candidates: list[tuple[float, int, dict[str, str]]] = []
|
||||
for band_index, (_, band) in enumerate(record):
|
||||
raw = _adaptive_field_raw(band=band, region=region, field_code=code)
|
||||
@@ -629,7 +904,7 @@ def _reconstruct_adaptive_record_columns_profile_rows(
|
||||
issues.append(f'coordinate_profile_composite_conflict:{extracted_code}')
|
||||
else:
|
||||
values[extracted_code] = extracted_value
|
||||
if is_valid_line_start_value(values.get(line_start_field_code, '')):
|
||||
if _is_record_start(values, main_fields, line_start_field_code, schema_fields):
|
||||
results.append(CoordinateProfileLogicalRow(
|
||||
fields=values,
|
||||
source_row_indices=[row_index for row_index, _ in record],
|
||||
@@ -639,6 +914,87 @@ def _reconstruct_adaptive_record_columns_profile_rows(
|
||||
return results if include_deleted else [row for row in results if row.role != 'deleted']
|
||||
|
||||
|
||||
def _reconstruct_dynamic_x_columns_profile_rows(
|
||||
*,
|
||||
glyphs: list[tuple[int, PositionedCharacter]],
|
||||
table_bbox: LayoutBBox,
|
||||
ordered_layouts: list[dict[str, Any]],
|
||||
termination_rules: list[dict[str, Any]],
|
||||
include_deleted: bool,
|
||||
line_start_field_code: str,
|
||||
schema_fields: dict[str, dict[str, Any]] | None = None,
|
||||
) -> list[CoordinateProfileLogicalRow]:
|
||||
"""按每条记录的有效起行锚点平移完整字段框,恢复稳定 X、漂移 Y 的明细。"""
|
||||
main_fields = ordered_layouts[0].get('field_regions') or []
|
||||
start_field = next(
|
||||
(item for item in main_fields if isinstance(item, dict) and item.get('field_code') == line_start_field_code),
|
||||
None,
|
||||
)
|
||||
if not isinstance(start_field, dict) or not isinstance(start_field.get('region'), dict):
|
||||
return []
|
||||
fields = [
|
||||
field for layout in ordered_layouts for field in (layout.get('field_regions') or [])
|
||||
if isinstance(field, dict) and isinstance(field.get('region'), dict) and field.get('field_code')
|
||||
]
|
||||
bands: list[tuple[int, list[tuple[int, PositionedCharacter]]]] = []
|
||||
for row_index, band in enumerate(_group_visual_rows(glyphs)):
|
||||
text = ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)).strip()
|
||||
if _SUMMARY_PATTERN.search(text) or _matches_termination_rule(band, table_bbox, termination_rules):
|
||||
break
|
||||
bands.append((row_index, band))
|
||||
start_region = _absolute_relative_region(table_bbox, start_field['region'])
|
||||
anchors = [
|
||||
index for index, (_row_index, band) in enumerate(bands)
|
||||
if _is_adaptive_record_start(
|
||||
band=band, start_region=start_region, main_fields=main_fields,
|
||||
table_bbox=table_bbox, line_start_field_code=line_start_field_code,
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
]
|
||||
results: list[CoordinateProfileLogicalRow] = []
|
||||
expected_anchor_center = (start_region.y0 + start_region.y1) / 2
|
||||
for anchor_index, start in enumerate(anchors):
|
||||
end = anchors[anchor_index + 1] if anchor_index + 1 < len(anchors) else len(bands)
|
||||
record = bands[start:end]
|
||||
anchor_box = _band_bbox(record[0][1])
|
||||
delta_y = (anchor_box.y0 + anchor_box.y1) / 2 - expected_anchor_center
|
||||
values: dict[str, str] = {}
|
||||
issues: list[str] = []
|
||||
for field in fields:
|
||||
code = str(field['field_code'])
|
||||
saved = _absolute_relative_region(table_bbox, field['region'])
|
||||
region = LayoutBBox(
|
||||
x0=saved.x0, y0=saved.y0 + delta_y,
|
||||
x1=saved.x1, y1=saved.y1 + delta_y,
|
||||
)
|
||||
selected_bands = [
|
||||
band for _row_index, band in record
|
||||
if _regions_overlap_vertically(region, _band_bbox(band))
|
||||
]
|
||||
raw = _text_in_multiline_region(
|
||||
selected_bands, region,
|
||||
compact=code in {'part_number', 'customer_part_number', 'aws_part_number'},
|
||||
)
|
||||
if not raw:
|
||||
continue
|
||||
extracted = extract_profile_field_value(
|
||||
extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=raw,
|
||||
)
|
||||
for extracted_code, extracted_value in extracted.items():
|
||||
previous = values.get(extracted_code)
|
||||
if previous is not None and previous != extracted_value:
|
||||
issues.append(f'coordinate_profile_composite_conflict:{extracted_code}')
|
||||
else:
|
||||
values[extracted_code] = extracted_value
|
||||
if _is_record_start(values, main_fields, line_start_field_code, schema_fields):
|
||||
results.append(CoordinateProfileLogicalRow(
|
||||
fields=values,
|
||||
source_row_indices=[row_index for row_index, _band in record],
|
||||
role='data', issues=issues,
|
||||
))
|
||||
return results if include_deleted else [row for row in results if row.role != 'deleted']
|
||||
|
||||
|
||||
def _adaptive_field_raw(
|
||||
*, band: list[tuple[int, PositionedCharacter]], region: LayoutBBox, field_code: str,
|
||||
) -> str:
|
||||
@@ -656,22 +1012,43 @@ def _adaptive_field_raw(
|
||||
def _is_adaptive_record_start(
|
||||
*, band: list[tuple[int, PositionedCharacter]], start_region: LayoutBBox,
|
||||
main_fields: list[dict[str, Any]], table_bbox: LayoutBBox, line_start_field_code: str,
|
||||
schema_fields: dict[str, dict[str, Any]] | None = None,
|
||||
) -> bool:
|
||||
"""要求起行号及同一主行的其他绑定字段共同成立,排除页眉、地址中的孤立数字。"""
|
||||
if not is_valid_line_start_value(_text_in_horizontal_region(band, start_region)):
|
||||
return False
|
||||
evidence_fields = [
|
||||
item for item in main_fields
|
||||
if item.get('field_code') != line_start_field_code and item.get('field_code') in {
|
||||
'part_number', 'customer_part_number', 'aws_part_number',
|
||||
}
|
||||
]
|
||||
return all(
|
||||
_is_compact_identifier(
|
||||
_text_in_horizontal_region(band, _absolute_relative_region(table_bbox, field['region']))
|
||||
"""按当前主视觉行的 Schema 字段值判断起行,不依赖业务字段名。"""
|
||||
if schema_fields is None:
|
||||
if not is_valid_line_start_value(_text_in_horizontal_region(band, start_region)):
|
||||
return False
|
||||
# 低层旧调用未提供 Schema 时仍使用通用文本形态交叉验证,
|
||||
# 但不再按业务字段名建立白名单。
|
||||
evidence_fields = [
|
||||
item for item in main_fields
|
||||
if isinstance(item, dict)
|
||||
and item.get('field_code') != line_start_field_code
|
||||
and isinstance(item.get('region'), dict)
|
||||
]
|
||||
return all(
|
||||
_is_compact_identifier(
|
||||
_text_in_horizontal_region(band, _absolute_relative_region(table_bbox, field['region']))
|
||||
)
|
||||
for field in evidence_fields
|
||||
)
|
||||
for field in evidence_fields
|
||||
)
|
||||
values: dict[str, str] = {}
|
||||
for field in main_fields:
|
||||
if not isinstance(field, dict) or not isinstance(field.get('region'), dict):
|
||||
continue
|
||||
code = str(field.get('field_code') or '')
|
||||
if not code or code not in schema_fields:
|
||||
continue
|
||||
raw = _adaptive_field_raw(
|
||||
band=band,
|
||||
region=_absolute_relative_region(table_bbox, field['region']),
|
||||
field_code=code,
|
||||
)
|
||||
extracted = extract_profile_field_value(
|
||||
extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=raw,
|
||||
)
|
||||
values.update(extracted)
|
||||
return _is_record_start(values, main_fields, line_start_field_code, schema_fields)
|
||||
|
||||
|
||||
def _is_compact_identifier(raw: str) -> bool:
|
||||
@@ -717,6 +1094,7 @@ def _reconstruct_relative_y_profile_rows(
|
||||
include_deleted: bool,
|
||||
line_start_field_code: str,
|
||||
include_unanchored_rows: bool,
|
||||
schema_fields: dict[str, dict[str, Any]] | None = None,
|
||||
) -> list[CoordinateProfileLogicalRow] | None:
|
||||
"""
|
||||
将单个多视觉行物理框按父行内相对 Y 投影到每条重复明细。
|
||||
@@ -741,6 +1119,18 @@ def _reconstruct_relative_y_profile_rows(
|
||||
)
|
||||
if start_field is None:
|
||||
return None
|
||||
|
||||
def values_for_band(band: list[tuple[int, PositionedCharacter]]) -> dict[str, str]:
|
||||
values: dict[str, str] = {}
|
||||
for field in fields:
|
||||
code = str(field.get('field_code') or '')
|
||||
region = _absolute_relative_region(table_bbox, field['region'])
|
||||
raw = _text_in_horizontal_region(band, region)
|
||||
extracted = extract_profile_field_value(
|
||||
extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=raw,
|
||||
)
|
||||
values.update(extracted)
|
||||
return values
|
||||
bands = _group_visual_rows(glyphs)
|
||||
usable_bands: list[tuple[int, list[tuple[int, PositionedCharacter]]]] = []
|
||||
for row_index, band in enumerate(bands):
|
||||
@@ -755,16 +1145,17 @@ def _reconstruct_relative_y_profile_rows(
|
||||
anchors: list[int] = []
|
||||
for index, (_, band) in enumerate(usable_bands):
|
||||
start_text = _text_in_horizontal_region(band, start_region)
|
||||
if is_valid_line_start_value(start_text):
|
||||
if schema_fields is None and is_valid_line_start_value(start_text):
|
||||
anchors.append(index)
|
||||
elif schema_fields is not None:
|
||||
values = values_for_band(band)
|
||||
if _is_record_start(values, fields, line_start_field_code, schema_fields):
|
||||
anchors.append(index)
|
||||
if not anchors:
|
||||
return []
|
||||
|
||||
sample_end = anchors[1] if len(anchors) > 1 else len(usable_bands)
|
||||
sample_record = usable_bands[anchors[0]:sample_end]
|
||||
field_band_indices = _calibrate_field_band_indices(
|
||||
fields=fields, sample_record=sample_record, table_bbox=table_bbox,
|
||||
)
|
||||
start_region = _absolute_relative_region(table_bbox, start_field['region'])
|
||||
expected_anchor_center = (start_region.y0 + start_region.y1) / 2
|
||||
results: list[CoordinateProfileLogicalRow] = []
|
||||
for anchor_index, start in enumerate(anchors):
|
||||
end = anchors[anchor_index + 1] if anchor_index + 1 < len(anchors) else len(usable_bands)
|
||||
@@ -774,23 +1165,34 @@ def _reconstruct_relative_y_profile_rows(
|
||||
)) for _, band in record)
|
||||
values: dict[str, str] = {}
|
||||
issues: list[str] = []
|
||||
matched_bands, alignment_issues = _match_field_band_groups(
|
||||
fields=fields,
|
||||
record=record,
|
||||
expected_indices=field_band_indices,
|
||||
table_bbox=table_bbox,
|
||||
line_start_field_code=line_start_field_code,
|
||||
)
|
||||
issues.extend(alignment_issues)
|
||||
anchor_box = _band_bbox(record[0][1])
|
||||
delta_y = (anchor_box.y0 + anchor_box.y1) / 2 - expected_anchor_center
|
||||
for field in fields:
|
||||
code = str(field.get('field_code') or '')
|
||||
if not code:
|
||||
continue
|
||||
band_index = matched_bands.get(id(field))
|
||||
if band_index is None:
|
||||
saved = _absolute_relative_region(table_bbox, field['region'])
|
||||
region = LayoutBBox(
|
||||
x0=saved.x0, y0=saved.y0 + delta_y,
|
||||
x1=saved.x1, y1=saved.y1 + delta_y,
|
||||
)
|
||||
# A visual field box may intentionally span multiple PDF text lines
|
||||
# (for example a wrapped customer part number). The previous
|
||||
# one-band assignment treated that as an ambiguity and dropped the
|
||||
# field, which caused two vertically stacked part-number fields to
|
||||
# become empty or reuse the same prefix. When the configured field
|
||||
# region intersects multiple bands, read all of its own glyphs;
|
||||
# single-band fields retain the calibrated matching behavior.
|
||||
intersecting = [
|
||||
band for _row_index, band in record
|
||||
if _regions_overlap_vertically(region, _band_bbox(band))
|
||||
]
|
||||
if not intersecting:
|
||||
continue
|
||||
region = _absolute_relative_region(table_bbox, field['region'])
|
||||
raw = _text_in_horizontal_region(record[band_index][1], region)
|
||||
raw = _text_in_multiline_region(
|
||||
intersecting, region,
|
||||
compact=code in {'part_number', 'customer_part_number', 'aws_part_number'},
|
||||
)
|
||||
if not raw:
|
||||
continue
|
||||
extracted = extract_profile_field_value(
|
||||
@@ -802,7 +1204,7 @@ def _reconstruct_relative_y_profile_rows(
|
||||
issues.append(f'coordinate_profile_composite_conflict:{extracted_code}')
|
||||
else:
|
||||
values[extracted_code] = extracted_value
|
||||
if is_valid_line_start_value(values.get(line_start_field_code, '')):
|
||||
if _is_record_start(values, fields, line_start_field_code, schema_fields):
|
||||
results.append(CoordinateProfileLogicalRow(
|
||||
fields=values,
|
||||
source_row_indices=[row_index for row_index, _ in record],
|
||||
@@ -1202,7 +1604,7 @@ def reconstruct_multi_subrow_table(
|
||||
continue
|
||||
|
||||
main_values = _band_field_values(band, anchors[0])
|
||||
if is_valid_line_start_value(main_values.get(start_field_code, '')):
|
||||
if _is_record_start(main_values, ordered_layouts[0].get('field_regions') or [], start_field_code):
|
||||
flush()
|
||||
current_fields = main_values
|
||||
current_sources = [row_index]
|
||||
@@ -1370,13 +1772,17 @@ def _absolute_relative_region(table_bbox: LayoutBBox, relative: dict[str, Any])
|
||||
|
||||
|
||||
def _inside_region(glyph_bbox: LayoutBBox, region: LayoutBBox) -> bool:
|
||||
"""仅收集中心在管理员框选区域内的字符,边缘字符不跨区域复制。"""
|
||||
return region.x0 <= (glyph_bbox.x0 + glyph_bbox.x1) / 2 <= region.x1 and region.y0 <= (glyph_bbox.y0 + glyph_bbox.y1) / 2 <= region.y1
|
||||
"""按纵向中心和有效横向重叠收集字符,避免字段边界截断字形。"""
|
||||
return (
|
||||
_inside_horizontal_region(glyph_bbox, region)
|
||||
and region.y0 <= (glyph_bbox.y0 + glyph_bbox.y1) / 2 <= region.y1
|
||||
)
|
||||
|
||||
|
||||
def _inside_horizontal_region(glyph_bbox: LayoutBBox, region: LayoutBBox) -> bool:
|
||||
"""仅按标注框横向范围筛选字符,使同一行版式可应用到整张表的重复明细。"""
|
||||
return region.x0 <= (glyph_bbox.x0 + glyph_bbox.x1) / 2 <= region.x1
|
||||
"""接受与字段框正向相交的字形,防止紧贴边界的料号标点被截断。"""
|
||||
overlap = min(glyph_bbox.x1, region.x1) - max(glyph_bbox.x0, region.x0)
|
||||
return overlap > 0
|
||||
|
||||
|
||||
def _has_relative_y_subregions(parent: dict[str, Any], fields: list[dict[str, Any]]) -> bool:
|
||||
@@ -1499,6 +1905,26 @@ def _text_in_region(
|
||||
return render_positioned_row([glyph for _, glyph in selected], geometry_gap_limit=gap_limit)
|
||||
|
||||
|
||||
def _regions_overlap_vertically(left: LayoutBBox, right: LayoutBBox) -> bool:
|
||||
"""判断字段框与视觉 band 是否有纵向证据交集。"""
|
||||
return min(left.y1, right.y1) > max(left.y0, right.y0)
|
||||
|
||||
|
||||
def _text_in_multiline_region(
|
||||
bands: list[list[tuple[int, PositionedCharacter]]],
|
||||
region: LayoutBBox,
|
||||
*,
|
||||
compact: bool = False,
|
||||
) -> str:
|
||||
"""按视觉行顺序读取跨行字段,料号换行时去除行间空白。"""
|
||||
lines: list[str] = []
|
||||
for band in sorted(bands, key=lambda item: _band_bbox(item).y0):
|
||||
text = _text_in_region(band, region).strip()
|
||||
if text:
|
||||
lines.append(text)
|
||||
return ('' if compact else ' ').join(lines)
|
||||
|
||||
|
||||
def _text_in_horizontal_region(
|
||||
band: list[tuple[int, PositionedCharacter]], region: LayoutBBox,
|
||||
) -> str:
|
||||
|
||||
@@ -11,6 +11,7 @@ backend/app/services/shipping_notice/document_layout/lifecycle.py
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import gzip
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
@@ -22,6 +23,7 @@ from sqlalchemy import and_, func, or_, update
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
@@ -51,6 +53,81 @@ ON_DEMAND_COORDINATE_COMPACTION_ISSUES = frozenset({
|
||||
'shipping_document_layout_candidate_glyphs_compacted',
|
||||
'shipping_document_layout_candidate_page_metadata_compacted',
|
||||
})
|
||||
COORDINATE_EVIDENCE_REF_KEY = 'coordinate_evidence_ref'
|
||||
COORDINATE_EVIDENCE_SCHEMA_VERSION = 'shipping_order_coordinate_evidence.v1'
|
||||
|
||||
|
||||
def _coordinate_evidence_bytes(evidence: dict[str, Any]) -> bytes:
|
||||
"""将完整坐标证据以稳定 gzip JSON 编码,供不可变 FileAsset 保存。"""
|
||||
raw = json.dumps(evidence, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode('utf-8')
|
||||
return gzip.compress(raw, compresslevel=6, mtime=0)
|
||||
|
||||
|
||||
def _persist_coordinate_evidence_asset(*, document: ShippingOrderDocument, evidence: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""复用现有 FileAsset/MinIO 保存完整坐标证据并返回轻量引用。"""
|
||||
tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
|
||||
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
if not any(isinstance(value, list) and value for value in (*tables.values(), *page_glyphs.values())):
|
||||
return None
|
||||
from app.services.file_assets.service import create_derived_file_asset_from_bytes
|
||||
|
||||
parent = db.session.get(FileAsset, int(document.asset_id)) if document.asset_id else None
|
||||
intake = db.session.get(ShippingOrderIntake, int(document.intake_id))
|
||||
user_id = getattr(intake, 'user_id', None)
|
||||
if parent is None or user_id is None:
|
||||
return None
|
||||
data = _coordinate_evidence_bytes(evidence)
|
||||
asset, created = create_derived_file_asset_from_bytes(
|
||||
user_id=int(user_id), parent=parent, data=data,
|
||||
filename=f'{document.id}-coordinate-evidence.json.gz',
|
||||
mime_type='application/json+gzip', asset_role='layout_coordinate_evidence',
|
||||
)
|
||||
asset.lifecycle_status = 'referenced'
|
||||
asset.expires_at = None
|
||||
asset.deleted_at = None
|
||||
if created or int(asset.reference_count or 0) == 0:
|
||||
asset.reference_count = max(int(asset.reference_count or 0), 1)
|
||||
return {
|
||||
'asset_no': str(asset.asset_no),
|
||||
'checksum': hashlib.sha256(data).hexdigest(),
|
||||
'size': len(data),
|
||||
'schema_version': str(evidence.get('version') or COORDINATE_EVIDENCE_SCHEMA_VERSION),
|
||||
}
|
||||
|
||||
|
||||
def _has_coordinate_evidence(evidence: Any) -> bool:
|
||||
"""判断证据是否含有可外置的字符集合;空占位结构保持原快照兼容。"""
|
||||
if not isinstance(evidence, dict):
|
||||
return False
|
||||
for key in ('tables', 'page_glyphs'):
|
||||
values = evidence.get(key)
|
||||
if isinstance(values, dict) and any(isinstance(item, list) and item for item in values.values()):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _hydrate_coordinate_evidence(*, payload: dict[str, Any], document: ShippingOrderDocument) -> dict[str, Any]:
|
||||
"""从现有 FileAsset 引用加载完整坐标证据;读取失败时保持缺证据状态。"""
|
||||
ref = payload.get(COORDINATE_EVIDENCE_REF_KEY)
|
||||
if not isinstance(ref, dict):
|
||||
return payload
|
||||
asset_no = str(ref.get('asset_no') or '').strip()
|
||||
if not asset_no:
|
||||
return payload
|
||||
asset = FileAsset.query.filter_by(asset_no=asset_no, deleted_at=None).first()
|
||||
if asset is None:
|
||||
return payload
|
||||
try:
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
evidence = json.loads(gzip.decompress(read_asset_bytes(asset)).decode('utf-8'))
|
||||
except Exception:
|
||||
_LOGGER.exception('coordinate evidence asset load failed document_id=%s asset_no=%s', document.id, asset_no)
|
||||
return payload
|
||||
if _has_coordinate_evidence(evidence):
|
||||
hydrated = dict(payload)
|
||||
hydrated['coordinate_evidence'] = evidence
|
||||
return hydrated
|
||||
return payload
|
||||
|
||||
|
||||
def _ready_layout_evidence_complete(*, document: ShippingOrderDocument, payload: dict[str, Any]) -> bool:
|
||||
@@ -61,10 +138,8 @@ def _ready_layout_evidence_complete(*, document: ShippingOrderDocument, payload:
|
||||
"""
|
||||
if Path(str(document.filename or '')).suffix.lower() != '.pdf':
|
||||
return True
|
||||
evidence = payload.get('coordinate_evidence') if isinstance(payload.get('coordinate_evidence'), dict) else {}
|
||||
complete = isinstance(evidence.get('pages'), dict) and isinstance(evidence.get('page_glyphs'), dict)
|
||||
recoverable = bool(document.asset_id) and isinstance(payload.get('layout_candidate'), dict)
|
||||
return complete or recoverable
|
||||
ref = payload.get(COORDINATE_EVIDENCE_REF_KEY)
|
||||
return isinstance(ref, dict) and bool(str(ref.get('asset_no') or '').strip())
|
||||
|
||||
|
||||
def _layout_version_reusable(*, document: ShippingOrderDocument, version: ShippingDocumentLayoutVersion) -> bool:
|
||||
@@ -207,14 +282,17 @@ def _fit_layout_payload_to_budget(
|
||||
|
||||
def current_layout_snapshot(document: ShippingOrderDocument) -> dict[str, Any] | None:
|
||||
"""读取 Document 当前可用冻结 payload;失败历史版本永不作为运行输入。"""
|
||||
version = document.current_layout_version
|
||||
version = (
|
||||
db.session.get(ShippingDocumentLayoutVersion, int(document.current_layout_version_id))
|
||||
if document.current_layout_version_id else document.current_layout_version
|
||||
)
|
||||
if (
|
||||
version is None
|
||||
or str(version.status or '') not in CURRENT_LAYOUT_STATUSES
|
||||
or not isinstance(version.payload_json, dict)
|
||||
):
|
||||
return None
|
||||
return dict(version.payload_json)
|
||||
return _hydrate_coordinate_evidence(payload=dict(version.payload_json), document=document)
|
||||
|
||||
|
||||
def _bind_inline_xfa_structure_analysis(
|
||||
@@ -322,6 +400,16 @@ def record_inline_layout_snapshot(
|
||||
超大 payload 不落正文,只创建 failed 审计版本;相同内容/parser/checksum 重试复用旧终态。
|
||||
"""
|
||||
payload = dict(snapshot)
|
||||
evidence = payload.get('coordinate_evidence')
|
||||
if _has_coordinate_evidence(evidence):
|
||||
evidence_ref = _persist_coordinate_evidence_asset(document=document, evidence=evidence)
|
||||
if evidence_ref is None and str(payload.get('status') or '') == 'ready':
|
||||
payload = {**payload, 'status': 'failed', 'issues': [
|
||||
*list(payload.get('issues') or []), 'shipping_document_layout_coordinate_evidence_persist_failed',
|
||||
]}
|
||||
elif evidence_ref is not None:
|
||||
payload.pop('coordinate_evidence', None)
|
||||
payload[COORDINATE_EVIDENCE_REF_KEY] = evidence_ref
|
||||
parser_key = str(parser_key or current_layout_parser_key())
|
||||
max_bytes = max(int(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000,
|
||||
@@ -943,19 +1031,30 @@ def complete_layout_version(
|
||||
if version is None or version.status != 'running' or version.lease_token != lease_token:
|
||||
db.session.rollback()
|
||||
return False
|
||||
payload = dict(snapshot)
|
||||
evidence = payload.get('coordinate_evidence')
|
||||
if _has_coordinate_evidence(evidence):
|
||||
evidence_ref = _persist_coordinate_evidence_asset(document=version.document, evidence=evidence)
|
||||
if evidence_ref is None and str(payload.get('status') or '') == 'ready':
|
||||
payload = {**payload, 'status': 'failed', 'issues': [
|
||||
*list(payload.get('issues') or []), 'shipping_document_layout_coordinate_evidence_persist_failed',
|
||||
]}
|
||||
elif evidence_ref is not None:
|
||||
payload.pop('coordinate_evidence', None)
|
||||
payload[COORDINATE_EVIDENCE_REF_KEY] = evidence_ref
|
||||
max_bytes = max(int(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000,
|
||||
)), 1)
|
||||
fitted_snapshot, compact_issues, payload_size = _fit_layout_payload_to_budget(
|
||||
snapshot, max_bytes=max_bytes,
|
||||
payload, max_bytes=max_bytes,
|
||||
)
|
||||
stored_for_identity = fitted_snapshot if fitted_snapshot is not None else snapshot
|
||||
stored_for_identity = fitted_snapshot if fitted_snapshot is not None else payload
|
||||
checksum, _ = canonical_layout_payload(stored_for_identity)
|
||||
issues = sorted({str(item) for item in (snapshot.get('issues') or []) if str(item)} | set(compact_issues))
|
||||
provider_status = str(snapshot.get('status') or 'failed')
|
||||
issues = sorted({str(item) for item in (payload.get('issues') or []) if str(item)} | set(compact_issues))
|
||||
provider_status = str(payload.get('status') or 'failed')
|
||||
status = provider_status if provider_status in TERMINAL_LAYOUT_STATUSES else 'failed'
|
||||
if status == 'ready' and not _ready_layout_evidence_complete(
|
||||
document=version.document, payload=snapshot,
|
||||
document=version.document, payload=payload,
|
||||
):
|
||||
status = 'failed'
|
||||
issues = sorted(set(issues) | {'shipping_document_layout_coordinate_evidence_incomplete'})
|
||||
@@ -967,12 +1066,12 @@ def complete_layout_version(
|
||||
status = 'failed'
|
||||
now = datetime.utcnow()
|
||||
version.status = status
|
||||
version.parser_version = str(snapshot.get('provider_version') or '')[:64] or None
|
||||
version.backend = str(snapshot.get('backend') or LAYOUT_BACKEND)[:32]
|
||||
version.parser_version = str(payload.get('provider_version') or '')[:64] or None
|
||||
version.backend = str(payload.get('backend') or LAYOUT_BACKEND)[:32]
|
||||
version.payload_json = stored_payload
|
||||
version.payload_checksum = checksum
|
||||
version.payload_size_bytes = payload_size
|
||||
version.quality_json = dict(snapshot['capability']) if isinstance(snapshot.get('capability'), dict) else None
|
||||
version.quality_json = dict(payload['capability']) if isinstance(payload.get('capability'), dict) else None
|
||||
version.issues_json = sorted(set(issues))
|
||||
version.lease_token = None
|
||||
version.finished_at = now
|
||||
|
||||
@@ -93,56 +93,62 @@ def extract_native_pdf_pages(
|
||||
"""
|
||||
if not content or render_scale <= 0:
|
||||
raise ValueError('native PDF content and positive render scale are required')
|
||||
pdf = pdfium.PdfDocument(content)
|
||||
pages: list[NativePdfPage] = []
|
||||
for page_index in range(len(pdf)):
|
||||
page = pdf[page_index]
|
||||
width, height = page.get_size()
|
||||
text_page = page.get_textpage()
|
||||
characters: list[PositionedCharacter] = []
|
||||
pending_boundary: str = 'none'
|
||||
for char_index in range(text_page.count_chars()):
|
||||
text = text_page.get_text_range(char_index, 1)
|
||||
if not text:
|
||||
continue
|
||||
if not normalize_layout_text(text):
|
||||
if any(character in {'\r', '\n'} for character in text):
|
||||
pending_boundary = 'line_break'
|
||||
elif pending_boundary == 'none' and any(character.isspace() for character in text):
|
||||
pending_boundary = 'space'
|
||||
continue
|
||||
left, bottom, right, top = text_page.get_charbox(char_index, loose=True)
|
||||
if right <= left or top <= bottom:
|
||||
# 非空白可见字符若无有效坐标,不得把之前的空白错误转嫁到后续字符。
|
||||
pending_boundary = 'none'
|
||||
continue
|
||||
pdf = pdfium.PdfDocument(content)
|
||||
try:
|
||||
for page_index in range(len(pdf)):
|
||||
page = pdf[page_index]
|
||||
text_page = None
|
||||
try:
|
||||
# 不修改 PDFium 原始坐标;仅转为左上原点页面坐标。
|
||||
characters.append(PositionedCharacter(
|
||||
text=text,
|
||||
bbox=LayoutBBox(
|
||||
x0=left, y0=height - top, x1=right, y1=height - bottom,
|
||||
),
|
||||
source_index=char_index,
|
||||
boundary_before=pending_boundary,
|
||||
width, height = page.get_size()
|
||||
text_page = page.get_textpage()
|
||||
characters: list[PositionedCharacter] = []
|
||||
pending_boundary: str = 'none'
|
||||
for char_index in range(text_page.count_chars()):
|
||||
text = text_page.get_text_range(char_index, 1)
|
||||
if not text:
|
||||
continue
|
||||
if not normalize_layout_text(text):
|
||||
if any(character in {'\r', '\n'} for character in text):
|
||||
pending_boundary = 'line_break'
|
||||
elif pending_boundary == 'none' and any(character.isspace() for character in text):
|
||||
pending_boundary = 'space'
|
||||
continue
|
||||
left, bottom, right, top = text_page.get_charbox(char_index, loose=True)
|
||||
if right <= left or top <= bottom:
|
||||
# 非空白可见字符若无有效坐标,不得把之前的空白错误转嫁到后续字符。
|
||||
pending_boundary = 'none'
|
||||
continue
|
||||
try:
|
||||
# 不修改 PDFium 原始坐标;仅转为左上原点页面坐标。
|
||||
characters.append(PositionedCharacter(
|
||||
text=text,
|
||||
bbox=LayoutBBox(
|
||||
x0=left, y0=height - top, x1=right, y1=height - bottom,
|
||||
),
|
||||
source_index=char_index,
|
||||
boundary_before=pending_boundary,
|
||||
))
|
||||
pending_boundary = 'none'
|
||||
except ValueError:
|
||||
pending_boundary = 'none'
|
||||
continue
|
||||
characters = _assign_page_line_ids(characters, page_no=page_index + 1)
|
||||
rotation = int(getattr(page, 'get_rotation', lambda: 0)() or 0) % 360
|
||||
pages.append(NativePdfPage(
|
||||
page_no=page_index + 1,
|
||||
width=float(width),
|
||||
height=float(height),
|
||||
rotation=rotation if rotation in {0, 90, 180, 270} else 0,
|
||||
characters=characters,
|
||||
image=_render_native_pdf_page(page, render_scale) if render_images else None,
|
||||
))
|
||||
pending_boundary = 'none'
|
||||
except ValueError:
|
||||
pending_boundary = 'none'
|
||||
continue
|
||||
characters = _assign_page_line_ids(characters, page_no=page_index + 1)
|
||||
rotation = int(getattr(page, 'get_rotation', lambda: 0)() or 0) % 360
|
||||
pages.append(NativePdfPage(
|
||||
page_no=page_index + 1,
|
||||
width=float(width),
|
||||
height=float(height),
|
||||
rotation=rotation if rotation in {0, 90, 180, 270} else 0,
|
||||
characters=characters,
|
||||
image=(
|
||||
np.asarray(page.render(scale=render_scale).to_numpy()).copy()
|
||||
if render_images else None
|
||||
),
|
||||
))
|
||||
finally:
|
||||
if text_page is not None:
|
||||
text_page.close()
|
||||
page.close()
|
||||
finally:
|
||||
pdf.close()
|
||||
return pages
|
||||
|
||||
|
||||
@@ -191,27 +197,43 @@ def attach_native_pdf_page_images(
|
||||
return []
|
||||
if all(page.image is not None for page in pages):
|
||||
return list(pages)
|
||||
pdf = pdfium.PdfDocument(content)
|
||||
attached: list[NativePdfPage] = []
|
||||
for page in pages:
|
||||
if page.image is not None:
|
||||
attached.append(page)
|
||||
continue
|
||||
index = int(page.page_no) - 1
|
||||
if index < 0 or index >= len(pdf):
|
||||
raise ValueError('native PDF page_no is out of range for image attach')
|
||||
image = np.asarray(pdf[index].render(scale=render_scale).to_numpy()).copy()
|
||||
attached.append(NativePdfPage(
|
||||
page_no=page.page_no,
|
||||
width=page.width,
|
||||
height=page.height,
|
||||
rotation=page.rotation,
|
||||
characters=page.characters,
|
||||
image=image,
|
||||
))
|
||||
pdf = pdfium.PdfDocument(content)
|
||||
try:
|
||||
for native_page in pages:
|
||||
if native_page.image is not None:
|
||||
attached.append(native_page)
|
||||
continue
|
||||
index = int(native_page.page_no) - 1
|
||||
if index < 0 or index >= len(pdf):
|
||||
raise ValueError('native PDF page_no is out of range for image attach')
|
||||
page = pdf[index]
|
||||
try:
|
||||
image = _render_native_pdf_page(page, render_scale)
|
||||
finally:
|
||||
page.close()
|
||||
attached.append(NativePdfPage(
|
||||
page_no=native_page.page_no,
|
||||
width=native_page.width,
|
||||
height=native_page.height,
|
||||
rotation=native_page.rotation,
|
||||
characters=native_page.characters,
|
||||
image=image,
|
||||
))
|
||||
finally:
|
||||
pdf.close()
|
||||
return attached
|
||||
|
||||
|
||||
def _render_native_pdf_page(page: Any, render_scale: float) -> np.ndarray:
|
||||
"""将 PDFium 页面复制为独立 ndarray 后立即释放临时 bitmap,避免其 finalizer 滞留到进程退出。"""
|
||||
bitmap = page.render(scale=render_scale)
|
||||
try:
|
||||
return np.asarray(bitmap.to_numpy()).copy()
|
||||
finally:
|
||||
bitmap.close()
|
||||
|
||||
|
||||
def build_native_pdf_text_table_fallbacks(
|
||||
content: bytes,
|
||||
*,
|
||||
@@ -232,17 +254,24 @@ def build_native_pdf_text_table_fallbacks(
|
||||
continue
|
||||
start_index, end_index = header
|
||||
header_lines = lines[start_index:end_index + 1]
|
||||
body_lines = lines[end_index + 1:]
|
||||
stop_index = next((
|
||||
index for index, line in enumerate(body_lines)
|
||||
if _is_fallback_total(line) or _is_fallback_separator(line)
|
||||
), len(body_lines))
|
||||
body_lines = body_lines[:stop_index]
|
||||
if not body_lines:
|
||||
continue
|
||||
boundaries = _fallback_column_boundaries(header_lines, page.width)
|
||||
if len(boundaries) < 3:
|
||||
continue
|
||||
body_lines: list[dict[str, Any]] = []
|
||||
has_data_row = False
|
||||
for line in lines[end_index + 1:]:
|
||||
if _is_fallback_total(line):
|
||||
break
|
||||
if _is_fallback_separator(line):
|
||||
# 采购订单常在表头和首条明细之间画横线;只有已见明细后的横线才是表尾。
|
||||
if has_data_row:
|
||||
break
|
||||
continue
|
||||
body_lines.append(line)
|
||||
if _fallback_data_row(_fallback_cells([line], boundaries)):
|
||||
has_data_row = True
|
||||
if not body_lines:
|
||||
continue
|
||||
header_cells = _fallback_cells(header_lines, boundaries)
|
||||
body_cells = [_fallback_cells([line], boundaries) for line in body_lines]
|
||||
if not any(_fallback_data_row(row) for row in body_cells):
|
||||
|
||||
@@ -23,6 +23,7 @@ from app.services.shipping_notice.document_layout.order_profile import (
|
||||
AnchorRule,
|
||||
OrderCoordinateProfile,
|
||||
OrderFieldLayout,
|
||||
ReferencePageFrame,
|
||||
RelativeRegion,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
@@ -53,6 +54,7 @@ def extract_order_fields(
|
||||
*, profile: OrderCoordinateProfile, schema_fields: dict[str, dict[str, Any]],
|
||||
coordinate_evidence: dict[str, Any], allow_ocr_preview_fallback: bool = False,
|
||||
coordinate_transform: dict[str, Any] | None = None,
|
||||
allow_fixed_region_confirmation: bool = False,
|
||||
) -> list[OrderFieldExtraction]:
|
||||
"""
|
||||
用唯一文字锚点和相对值区读取订单字段,缺少页级证据时严格失败关闭。
|
||||
@@ -63,6 +65,9 @@ def extract_order_fields(
|
||||
coordinate_evidence: 冻结页尺寸、page_glyphs 与来源;不接受表格内 glyph 兜底。
|
||||
allow_ocr_preview_fallback: 仅管理端视觉样本值预览可启用。它允许已确认的
|
||||
PDF 坐标字段临时读取 OCR 候选,但结果仍固定为 needs_review,不能用于正式运行时取值。
|
||||
allow_fixed_region_confirmation: 仅唯一匹配模板的正式运行或当前模板盲测回放可启用。
|
||||
它只允许原生 PDF 坐标的无标签固定区域成为 confirmed;OCR、未匹配模板和
|
||||
普通预览仍保持 needs_review。
|
||||
|
||||
Returns:
|
||||
每个已绑定布局对应一个候选,按模板声明顺序返回。
|
||||
@@ -78,7 +83,9 @@ def extract_order_fields(
|
||||
layout=layout,
|
||||
schema_fields=schema_fields,
|
||||
coordinate_evidence=coordinate_evidence,
|
||||
reference_page_frames=effective_profile.reference_page_frames,
|
||||
allow_ocr_preview_fallback=allow_ocr_preview_fallback,
|
||||
allow_fixed_region_confirmation=allow_fixed_region_confirmation,
|
||||
)
|
||||
for layout in effective_profile.order_field_layouts
|
||||
]
|
||||
@@ -103,7 +110,8 @@ def _project_coordinate_transform(
|
||||
|
||||
def _extract_layout(
|
||||
*, layout: OrderFieldLayout, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any],
|
||||
allow_ocr_preview_fallback: bool = False,
|
||||
reference_page_frames: dict[int, ReferencePageFrame],
|
||||
allow_ocr_preview_fallback: bool = False, allow_fixed_region_confirmation: bool = False,
|
||||
) -> OrderFieldExtraction:
|
||||
"""处理一个订单字段布局,并把任何不确定性保留为 Review/Unavailable 而非猜测。"""
|
||||
config = schema_fields.get(layout.field_id)
|
||||
@@ -139,6 +147,7 @@ def _extract_layout(
|
||||
|
||||
results: list[OrderFieldExtraction] = []
|
||||
for page_no, glyphs, width, height, source in candidates:
|
||||
reference_page_frame = reference_page_frames.get(page_no)
|
||||
if not _source_allowed(
|
||||
layout,
|
||||
config=config,
|
||||
@@ -150,18 +159,25 @@ def _extract_layout(
|
||||
if layout.anchor is None:
|
||||
results.append(_read_value_region(
|
||||
layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source,
|
||||
region=_absolute_relative_region(layout.fallback_value_region, width=width, height=height), anchor_bbox=None,
|
||||
fallback=True,
|
||||
region=_absolute_relative_region(
|
||||
layout.fallback_value_region, width=width, height=height,
|
||||
reference_page_frame=reference_page_frame,
|
||||
), anchor_bbox=None,
|
||||
fallback=not (allow_fixed_region_confirmation and source == 'pdf_coordinate'),
|
||||
))
|
||||
continue
|
||||
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),
|
||||
reference_page_frame=reference_page_frame,
|
||||
ignore_reference_region=_uses_movable_anchor_value_region(
|
||||
layout=layout, width=width, height=height, reference_page_frame=reference_page_frame,
|
||||
),
|
||||
)
|
||||
if not matches:
|
||||
reference_anchor = (
|
||||
_anchor_from_reference_region(
|
||||
glyphs, anchor=layout.anchor, page_width=width, page_height=height,
|
||||
reference_page_frame=reference_page_frame,
|
||||
)
|
||||
if _is_placeholder_anchor_text(layout.anchor.text) else None
|
||||
)
|
||||
@@ -171,7 +187,10 @@ def _extract_layout(
|
||||
# intent, but it must remain review-only until the label is fixed.
|
||||
results.append(_read_value_region(
|
||||
layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source,
|
||||
region=_absolute_value_region(layout=layout, anchor=reference_anchor, width=width, height=height),
|
||||
region=_absolute_value_region(
|
||||
layout=layout, anchor=reference_anchor, width=width, height=height,
|
||||
reference_page_frame=reference_page_frame,
|
||||
),
|
||||
anchor_bbox=reference_anchor, fallback=False,
|
||||
review_issue='order_field_anchor_text_mismatch',
|
||||
))
|
||||
@@ -187,7 +206,10 @@ def _extract_layout(
|
||||
anchor_bbox, _indices = matches[0]
|
||||
results.append(_read_value_region(
|
||||
layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source,
|
||||
region=_absolute_value_region(layout=layout, anchor=anchor_bbox, width=width, height=height), anchor_bbox=anchor_bbox, fallback=False,
|
||||
region=_absolute_value_region(
|
||||
layout=layout, anchor=anchor_bbox, width=width, height=height,
|
||||
reference_page_frame=reference_page_frame,
|
||||
), anchor_bbox=anchor_bbox, fallback=False,
|
||||
))
|
||||
usable = [item for item in results if item.status != 'unavailable']
|
||||
if len(usable) == 1:
|
||||
@@ -321,6 +343,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,
|
||||
reference_page_frame: ReferencePageFrame | None = None,
|
||||
ignore_reference_region: bool = False,
|
||||
) -> list[tuple[LayoutBBox, list[int]]]:
|
||||
"""在每个视觉行内执行精确标签匹配,返回去重后的字符联合框。"""
|
||||
@@ -348,23 +371,22 @@ def _find_anchor_matches(
|
||||
compact, position=position, length=len(normalized), anchor=anchor,
|
||||
):
|
||||
bbox = _union_bbox([item for _index, item in consumed])
|
||||
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]))
|
||||
# 先按文本收集全部精确命中;保存的参考框只用于多个同名标签
|
||||
# 的消歧,不能让同版式样本中唯一但位置变化的标签直接丢失。
|
||||
matches.append((bbox, [index for index, _item in consumed]))
|
||||
start = position + max(len(label), 1)
|
||||
unique: dict[tuple[float, float, float, float], tuple[LayoutBBox, list[int]]] = {}
|
||||
for bbox, indices in matches:
|
||||
unique[(bbox.x0, bbox.y0, bbox.x1, bbox.y1)] = (bbox, indices)
|
||||
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,
|
||||
item[0], anchor=anchor, page_width=page_width, page_height=page_height,
|
||||
reference_page_frame=reference_page_frame, enforce=True,
|
||||
)
|
||||
]
|
||||
if len(positioned) == 1:
|
||||
@@ -397,6 +419,7 @@ 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,
|
||||
reference_page_frame: ReferencePageFrame | None = None,
|
||||
enforce: bool = False,
|
||||
) -> bool:
|
||||
"""锚点配置了参考区时只接受该页相对位置内的命中,避免页眉重复标签干扰。"""
|
||||
@@ -404,17 +427,22 @@ def _anchor_bbox_in_reference_region(
|
||||
return True
|
||||
if page_width is None or page_height is None or page_width <= 0 or page_height <= 0:
|
||||
return False
|
||||
region = _absolute_relative_region(anchor.region, width=page_width, height=page_height)
|
||||
region = _absolute_relative_region(
|
||||
anchor.region, width=page_width, height=page_height, reference_page_frame=reference_page_frame,
|
||||
)
|
||||
return _glyph_center_inside({'bbox': bbox.model_dump(mode='json')}, region)
|
||||
|
||||
|
||||
def _anchor_from_reference_region(
|
||||
glyphs: list[dict[str, Any]], *, anchor: AnchorRule, page_width: float, page_height: float,
|
||||
reference_page_frame: ReferencePageFrame | None = None,
|
||||
) -> LayoutBBox | None:
|
||||
"""为历史占位标签保留参考框内的实际标签几何,且调用方必须降级为人工复核。"""
|
||||
if anchor.region is None:
|
||||
return None
|
||||
region = _absolute_relative_region(anchor.region, width=page_width, height=page_height)
|
||||
region = _absolute_relative_region(
|
||||
anchor.region, width=page_width, height=page_height, reference_page_frame=reference_page_frame,
|
||||
)
|
||||
selected = [glyph for glyph in glyphs if _glyph_center_inside(glyph, region)]
|
||||
return _union_bbox(selected) if selected else None
|
||||
|
||||
@@ -500,11 +528,19 @@ def _source_allowed(
|
||||
return not ('coordinate' in required_levels and source != 'pdf_coordinate')
|
||||
|
||||
|
||||
def _absolute_relative_region(region: RelativeRegion | None, *, width: float, height: float) -> LayoutBBox:
|
||||
"""将固定低可靠度归一化页区投影为当前页面绝对框。"""
|
||||
def _absolute_relative_region(
|
||||
region: RelativeRegion | None, *, width: float, height: float,
|
||||
reference_page_frame: ReferencePageFrame | None = None,
|
||||
) -> LayoutBBox:
|
||||
"""将区域投影为 PDF 点坐标;有标注页框时不得随当前长页高度缩放。"""
|
||||
if region is None:
|
||||
raise ValueError('fallback order field region is required')
|
||||
return LayoutBBox(x0=region.x0 * width, y0=region.y0 * height, x1=region.x1 * width, y1=region.y1 * height)
|
||||
projection_width = reference_page_frame.width if reference_page_frame is not None else width
|
||||
projection_height = reference_page_frame.height if reference_page_frame is not None else height
|
||||
return LayoutBBox(
|
||||
x0=region.x0 * projection_width, y0=region.y0 * projection_height,
|
||||
x1=region.x1 * projection_width, y1=region.y1 * projection_height,
|
||||
)
|
||||
|
||||
|
||||
def _absolute_anchor_region(region: AnchorRelativeRegion | None, anchor: LayoutBBox) -> LayoutBBox:
|
||||
@@ -518,14 +554,17 @@ def _absolute_anchor_region(region: AnchorRelativeRegion | None, anchor: LayoutB
|
||||
)
|
||||
|
||||
|
||||
def _absolute_value_region(*, layout: OrderFieldLayout, anchor: LayoutBBox, width: float, height: float) -> LayoutBBox:
|
||||
"""读取管理员值框;右侧/下方字段只随标签平移,绝不按标签框尺寸缩放。"""
|
||||
def _absolute_value_region(
|
||||
*, layout: OrderFieldLayout, anchor: LayoutBBox, width: float, height: float,
|
||||
reference_page_frame: ReferencePageFrame | None = None,
|
||||
) -> LayoutBBox:
|
||||
"""读取管理员值框;有保存参考锚点时整框随唯一命中标签平移,绝不缩放。"""
|
||||
if layout.value_region is not None:
|
||||
if layout.anchor is None or layout.anchor.region is None:
|
||||
return _absolute_anchor_region(layout.value_region, anchor)
|
||||
if layout.value_mode not in {'right_of_anchor', 'below_anchor'}:
|
||||
return _absolute_anchor_region(layout.value_region, anchor)
|
||||
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height)
|
||||
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height, reference_page_frame=reference_page_frame)
|
||||
saved = _absolute_anchor_region(layout.value_region, reference)
|
||||
if layout.value_mode == 'right_of_anchor':
|
||||
region = _absolute_anchor_region(layout.value_region, anchor)
|
||||
@@ -536,19 +575,33 @@ def _absolute_value_region(*, layout: OrderFieldLayout, anchor: LayoutBBox, widt
|
||||
x1=anchor.x1 + projected_width, y1=region.y1,
|
||||
)
|
||||
elif layout.absolute_value_region is not None:
|
||||
saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height)
|
||||
saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height, reference_page_frame=reference_page_frame)
|
||||
if layout.anchor is None or layout.anchor.region is None:
|
||||
return saved
|
||||
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height)
|
||||
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height, reference_page_frame=reference_page_frame)
|
||||
else:
|
||||
raise ValueError('anchored order field has no value region')
|
||||
if layout.value_mode not in {'right_of_anchor', 'below_anchor'}:
|
||||
# absolute_value_region 记录的是标注页上的完整取值框。标签在当前
|
||||
# 文档因可选单头内容整体移动时,single_line/multi_line 也必须保留
|
||||
# 框的形状,并以该字段自己的唯一锚点中心作同量平移。
|
||||
if layout.absolute_value_region is not None:
|
||||
reference_center_x = (reference.x0 + reference.x1) / 2
|
||||
reference_center_y = (reference.y0 + reference.y1) / 2
|
||||
anchor_center_x = (anchor.x0 + anchor.x1) / 2
|
||||
anchor_center_y = (anchor.y0 + anchor.y1) / 2
|
||||
return LayoutBBox(
|
||||
x0=saved.x0 + anchor_center_x - reference_center_x,
|
||||
y0=saved.y0 + anchor_center_y - reference_center_y,
|
||||
x1=saved.x1 + anchor_center_x - reference_center_x,
|
||||
y1=saved.y1 + anchor_center_y - reference_center_y,
|
||||
)
|
||||
return saved
|
||||
anchor_center_x, anchor_center_y = (anchor.x0 + anchor.x1) / 2, (anchor.y0 + anchor.y1) / 2
|
||||
if _regions_overlap(anchor, reference):
|
||||
return saved
|
||||
if layout.absolute_value_region is not None and not _uses_movable_anchor_value_region(
|
||||
layout=layout, width=width, height=height,
|
||||
layout=layout, width=width, height=height, reference_page_frame=reference_page_frame,
|
||||
):
|
||||
return saved
|
||||
if layout.value_mode == 'right_of_anchor':
|
||||
@@ -563,7 +616,10 @@ def _absolute_value_region(*, layout: OrderFieldLayout, anchor: LayoutBBox, widt
|
||||
)
|
||||
|
||||
|
||||
def _uses_movable_anchor_value_region(*, layout: OrderFieldLayout, width: float, height: float) -> bool:
|
||||
def _uses_movable_anchor_value_region(
|
||||
*, layout: OrderFieldLayout, width: float, height: float,
|
||||
reference_page_frame: ReferencePageFrame | None = None,
|
||||
) -> bool:
|
||||
"""判断新相对规则或同一行的旧右侧框是否应跟随实际标签移动。"""
|
||||
if layout.value_region is not None:
|
||||
return layout.value_mode in {'right_of_anchor', 'below_anchor'}
|
||||
@@ -572,8 +628,8 @@ def _uses_movable_anchor_value_region(*, layout: OrderFieldLayout, width: float,
|
||||
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)
|
||||
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height, reference_page_frame=reference_page_frame)
|
||||
saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height, reference_page_frame=reference_page_frame)
|
||||
tolerance = max(reference.y1 - reference.y0, saved.y1 - saved.y0) * 2
|
||||
return saved.y0 <= reference.y1 + tolerance and reference.y0 <= saved.y1 + tolerance
|
||||
|
||||
|
||||
@@ -50,6 +50,15 @@ class RelativeRegion(OrderProfileModel):
|
||||
return self
|
||||
|
||||
|
||||
class ReferencePageFrame(OrderProfileModel):
|
||||
"""冻结标注样本的 PDF CropBox 点尺寸,供跨页高变化时还原相对区域。"""
|
||||
|
||||
width: float = Field(gt=0)
|
||||
height: float = Field(gt=0)
|
||||
origin: Literal['pdf_top_left'] = 'pdf_top_left'
|
||||
box: Literal['cropbox'] = 'cropbox'
|
||||
|
||||
|
||||
class AnchorRelativeRegion(OrderProfileModel):
|
||||
"""仅接收历史锚点相对值框;新模板统一保存 absolute_value_region。"""
|
||||
|
||||
@@ -251,7 +260,7 @@ class TableRegionProfile(OrderProfileModel):
|
||||
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}$')
|
||||
line_start_field_code: str | None = 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'
|
||||
# 人工确认本表区自动标注时采用的视觉几何来源;仅用于审计、盲测和冲突复核,
|
||||
@@ -291,7 +300,7 @@ class TableRegionProfile(OrderProfileModel):
|
||||
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 {
|
||||
if self.line_start_field_code and 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')
|
||||
@@ -488,6 +497,7 @@ class OrderCoordinateProfile(OrderProfileModel):
|
||||
order_field_layouts: list[OrderFieldLayout] = Field(default_factory=list)
|
||||
draft_unbound_order_field_layouts: list[DraftUnboundOrderFieldLayout] = Field(default_factory=list)
|
||||
coordinate_model: CoordinateModel = Field(default_factory=CoordinateModel)
|
||||
reference_page_frames: dict[int, ReferencePageFrame] = Field(default_factory=dict)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_profile_rules(self) -> 'OrderCoordinateProfile':
|
||||
|
||||
@@ -150,6 +150,7 @@ def match_frozen_coordinate_profiles(
|
||||
table_regions=definition.get('table_regions'),
|
||||
order_field_layouts=definition.get('order_field_layouts') or [],
|
||||
coordinate_model=definition.get('coordinate_model') or {},
|
||||
reference_page_frames=definition.get('reference_page_frames') or {},
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
@@ -506,29 +507,49 @@ def _extract_matching_signature(raw: dict[str, Any]) -> tuple[dict[str, Any] | N
|
||||
def _resolve_coordinate_transform(
|
||||
*, profile: OrderCoordinateProfile, pages: dict[str, Any], page_glyphs: dict[str, Any],
|
||||
) -> tuple[dict[str, Any] | None, list[str]]:
|
||||
"""根据 Profile 声明的唯一静态锚点求受限平移,任何不确定性都返回硬失败原因。
|
||||
"""根据冻结的模板身份锚点求受限平移,任何不确定性都返回硬失败原因。
|
||||
|
||||
Args:
|
||||
profile: 当前冻结坐标 Profile;仅 ``anchor_frame`` 启用此能力。
|
||||
profile: 当前冻结坐标 Profile;旧 ``anchor_frame`` 优先,其他模板复用已框选的
|
||||
必选文档匹配标签,不要求管理员选择坐标模型。
|
||||
pages: 当前 Layout 的页尺寸证据。
|
||||
page_glyphs: 当前 Layout 的页级 PDF/OCR 字符坐标。
|
||||
|
||||
Returns:
|
||||
``(transform, reason_codes)``。legacy 返回 ``(None, [])``;anchor_frame 仅在
|
||||
所有锚点唯一且变换位于声明上限内时返回 ``status=applied``。
|
||||
``(transform, reason_codes)``。没有可证明的静态标签时返回 ``(None, [])``;
|
||||
有标签时仅在全部唯一且变换位于受限范围内返回 ``status=applied``。
|
||||
"""
|
||||
model = profile.coordinate_model
|
||||
anchors = list(model.anchors)
|
||||
max_translate_x = model.max_translate_x
|
||||
max_translate_y = model.max_translate_y
|
||||
if model.type != 'anchor_frame':
|
||||
anchors = [
|
||||
AnchorRule(
|
||||
anchor_id=anchor.anchor_id,
|
||||
text=anchor.label,
|
||||
match_mode='exact',
|
||||
region=anchor.label_region,
|
||||
position_locked=True,
|
||||
minimum_evidence_level=anchor.minimum_evidence_level,
|
||||
)
|
||||
for anchor in profile.document_match.required_anchors
|
||||
if anchor.label_region is not None
|
||||
]
|
||||
# 没有已框选的稳定标签时保持绝对坐标兼容;不从全文猜测校正基准。
|
||||
if not anchors:
|
||||
return None, []
|
||||
if not anchors:
|
||||
return None, []
|
||||
|
||||
deltas: list[tuple[float, float]] = []
|
||||
anchor_points: list[tuple[float, float, float, float]] = []
|
||||
anchor_ids: list[str] = []
|
||||
for anchor in model.anchors:
|
||||
for anchor in anchors:
|
||||
found = _find_anchor_rule_matches(
|
||||
anchor=anchor, pages=pages, page_glyphs=page_glyphs,
|
||||
max_translate_x=min(.30, model.max_translate_x * 2),
|
||||
max_translate_y=min(.30, model.max_translate_y * 2),
|
||||
max_translate_x=min(.30, max_translate_x * 2),
|
||||
max_translate_y=min(.30, max_translate_y * 2),
|
||||
)
|
||||
if not found:
|
||||
return None, ['profile_anchor_frame_anchor_missing']
|
||||
@@ -552,7 +573,7 @@ def _resolve_coordinate_transform(
|
||||
anchor_points.append((expected_x, expected_y, observed_x, observed_y))
|
||||
anchor_ids.append(anchor.anchor_id)
|
||||
|
||||
if model.transform_mode == 'affine':
|
||||
if model.type == 'anchor_frame' and model.transform_mode == 'affine':
|
||||
transform, reason = _resolve_affine_coordinate_transform(
|
||||
anchor_points=anchor_points, anchor_ids=anchor_ids, model=model,
|
||||
)
|
||||
@@ -561,7 +582,7 @@ def _resolve_coordinate_transform(
|
||||
first_x, first_y = deltas[0]
|
||||
if any(abs(x - first_x) > .01 or abs(y - first_y) > .01 for x, y in deltas[1:]):
|
||||
return None, ['profile_anchor_frame_anchor_inconsistent']
|
||||
if abs(first_x) > model.max_translate_x or abs(first_y) > model.max_translate_y:
|
||||
if abs(first_x) > max_translate_x or abs(first_y) > max_translate_y:
|
||||
return None, ['profile_anchor_frame_transform_out_of_range']
|
||||
return {
|
||||
'status': 'applied',
|
||||
|
||||
@@ -51,6 +51,8 @@ def validate_profile_parse_candidate(
|
||||
document_match=profile_def.get('document_match') or {'required_anchors': [], 'optional_anchors': []},
|
||||
table_regions=profile_def.get('table_regions') or [],
|
||||
order_field_layouts=profile_def.get('order_field_layouts') or [],
|
||||
coordinate_model=profile_def.get('coordinate_model') or {},
|
||||
reference_page_frames=profile_def.get('reference_page_frames') or {},
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
return {
|
||||
|
||||
-456
@@ -1,456 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/profile_field_source_mapping_service.py
|
||||
|
||||
用途:Profile 字段来源映射服务(Q18 抽取层裁决前置)——独立收集 Header / Table 列 /
|
||||
Vendor Comments 三个来源的候选观察,**不直接写 Observation 表**,只返回统一的
|
||||
FieldSourceCandidate 列表供 SourceMergeService 做 Q18 裁决合并。
|
||||
依赖:profile_vendor_comments_contract(parse_field_source_mappings/parse_named_regions)、
|
||||
field_split_core(execute_base_split_rule_set 用于 Vendor Comments 区域拆分)、
|
||||
coordinate_region_source_adapter(CoordinateRegionSourceAdapter 物理区域渲染)、
|
||||
reservation_relation_projection(ReservationRelationProjection 关系投影)。
|
||||
逻辑:严格「后端决定 UI」——本类输出每个候选的 target_scope/target_field_code/
|
||||
effective_line_no/value/source/evidence_ref/source_observation_metadata,
|
||||
前端只能消费这些投影字段,禁止自行推导业务状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Literal
|
||||
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_source_adapter import (
|
||||
CoordinateRegionEvidence,
|
||||
CoordinateRegionSourceAdapter,
|
||||
CoordinateRegionSourceResult,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.field_split_core import (
|
||||
CoreCapturedRelation,
|
||||
_CoreSegmentResult,
|
||||
execute_base_split_rule_set,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import (
|
||||
NamedRegion,
|
||||
ProfileFieldSourceMapping,
|
||||
parse_field_source_mappings,
|
||||
parse_named_regions,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.reservation_relation_projection import (
|
||||
ReservationRelationProjection,
|
||||
ReservationRelationProjectionResult,
|
||||
)
|
||||
|
||||
|
||||
FieldSourceLiteral = Literal['header_region', 'table_column', 'vendor_comments']
|
||||
|
||||
|
||||
@dataclass
|
||||
class FieldSourceCandidate:
|
||||
"""
|
||||
单来源单观察候选——Header/Table/Vendor Comments 各自产出后,由 SourceMergeService 裁决。
|
||||
|
||||
【后端决定 UI】:scope、line_no、value、format_valid、conflict_group_key 全部在本层
|
||||
计算完毕,前端只读投影,禁止自己用逻辑 if/else 推导。
|
||||
"""
|
||||
|
||||
source: FieldSourceLiteral
|
||||
target_scope: Literal['header', 'line']
|
||||
target_field_code: str
|
||||
target_field_id: str
|
||||
value: str
|
||||
normalized_value: str
|
||||
format_valid: bool | None # None = 本字段不需要格式校验(非 reservation)
|
||||
format_reason_code: str | None # format_valid=False 时的稳定诊断码(例:reservation_format_invalid)
|
||||
effective_line_no: int | None # 1-based;header 时为 None;default_all_lines 时为具体行号
|
||||
resolution_hint: Literal[
|
||||
'provisional', 'annotation_only', 'invalid_line_reference',
|
||||
] = 'provisional'
|
||||
relation_projection: ReservationRelationProjectionResult | None = None
|
||||
# 证据区——写入 Observation.evidence_quote / evidence_ref / evidence_metadata_json
|
||||
evidence_quote: str | None = None
|
||||
evidence_ref: str | None = None
|
||||
evidence_metadata: dict[str, Any] = field(default_factory=dict)
|
||||
# SourceMergeService 内部使用:冲突分组键 = (target_scope, target_field_code, effective_line_no)
|
||||
conflict_group_key: tuple[Any, ...] = ()
|
||||
|
||||
|
||||
class ProfileFieldSourceMappingService:
|
||||
"""
|
||||
三来源候选独立收集服务(路径判断与事实分离)。
|
||||
|
||||
【AI 触发时机】:订单文档抽取阶段(order_extraction_workflow 在 Observation 写入前)
|
||||
调用 collect_candidates() 返回候选列表,再交给 SourceMergeService 裁决合并。
|
||||
|
||||
核心执行顺序:
|
||||
[STEP 1] 解析 Profile definition_json 的 named_regions + field_source_mappings。
|
||||
[STEP 2] 对每个 mapping:
|
||||
a. header_source_enabled → 从 header_observations_by_source_ref 取现成观察
|
||||
b. table_source_enabled → 从 table_column_values 取(column_code + line_index)
|
||||
c. vendor_comments_enabled → 调 CoordinateRegionSourceAdapter + execute_base_split_rule_set
|
||||
[STEP 3] 对每个 Vendor Comments 拆分结果,调 ReservationRelationProjection.project
|
||||
生成 effective_line_no / resolution_hint。
|
||||
[STEP 4] 返回 FieldSourceCandidate 列表;未通过 format_policy 的候选保留
|
||||
value 但标记 format_valid=False(Q15:格式失败的值不丢弃)。
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
definition_json: dict[str, Any],
|
||||
header_observations_by_source_ref: dict[str, list[dict[str, Any]]] | None = None,
|
||||
table_column_values: dict[str, list[dict[str, Any]]] | None = None,
|
||||
page_glyphs_map: dict[int, dict[str, Any]] | None = None,
|
||||
# Reservation Relation Projection 三层判定表
|
||||
explicit_line_column_values: dict[int, str] | None = None,
|
||||
profile_business_line_numbers: dict[int, Any] | None = None,
|
||||
classified_logical_line_numbers: dict[int, int] | None = None,
|
||||
total_logical_lines: int = 0,
|
||||
# 格式策略调用方(保留注入点,避免本类直接 import reservation 校验模块造成循环)
|
||||
format_validator_callback=None,
|
||||
):
|
||||
self.definition_json = definition_json or {}
|
||||
self.header_observations_by_source_ref = header_observations_by_source_ref or {}
|
||||
self.table_column_values = table_column_values or {}
|
||||
self.page_glyphs_map = page_glyphs_map or {}
|
||||
self.explicit_line_column_values = explicit_line_column_values or {}
|
||||
self.profile_business_line_numbers = profile_business_line_numbers or {}
|
||||
self.classified_logical_line_numbers = classified_logical_line_numbers or {}
|
||||
self.total_logical_lines = total_logical_lines
|
||||
self.format_validator_callback = format_validator_callback
|
||||
# 预先解析契约(若失败抛 ValidationError 阻断运行,避免输出坏数据)
|
||||
self.named_regions: dict[str, NamedRegion] = parse_named_regions(
|
||||
self.definition_json.get('named_regions'),
|
||||
)
|
||||
self.mappings: list[ProfileFieldSourceMapping] = parse_field_source_mappings(
|
||||
self.definition_json.get('field_source_mappings'),
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 对外主入口
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def collect_candidates(self) -> list[FieldSourceCandidate]:
|
||||
"""
|
||||
返回全量候选。任何内部失败都返回稳定 status 候选(不抛错阻断其他字段)。
|
||||
调用方:SourceMergeService.merge_and_decide() → 再调用 obs 写入。
|
||||
"""
|
||||
candidates: list[FieldSourceCandidate] = []
|
||||
for mapping in self.mappings:
|
||||
if mapping.header_source_enabled and mapping.header_source_ref:
|
||||
candidates.extend(self._collect_header_source(mapping))
|
||||
if mapping.table_source_enabled and mapping.table_column_code:
|
||||
candidates.extend(self._collect_table_source(mapping))
|
||||
if mapping.vendor_comments_enabled and mapping.vendor_comments_region_ref:
|
||||
candidates.extend(self._collect_vendor_comments_source(mapping))
|
||||
for cand in candidates:
|
||||
cand.conflict_group_key = (cand.target_scope, cand.target_field_code, cand.effective_line_no)
|
||||
return candidates
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 三个来源分支(独立收集,不互相读数据——满足 Q18 先独立再裁决)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _collect_header_source(self, mapping: ProfileFieldSourceMapping) -> list[FieldSourceCandidate]:
|
||||
"""Header 区域来源——从 caller 传入的 header_observations_by_source_ref 读取。"""
|
||||
header_items = self.header_observations_by_source_ref.get(mapping.header_source_ref or '', [])
|
||||
results: list[FieldSourceCandidate] = []
|
||||
for item in header_items:
|
||||
raw_value = str(item.get('value') or '')
|
||||
format_valid, reason = self._check_format(mapping, raw_value)
|
||||
results.append(FieldSourceCandidate(
|
||||
source='header_region',
|
||||
target_scope=mapping.target_scope,
|
||||
target_field_code=mapping.target_field_code,
|
||||
target_field_id=mapping.target_field_id,
|
||||
value=raw_value,
|
||||
normalized_value=_normalize_string(raw_value),
|
||||
format_valid=format_valid,
|
||||
format_reason_code=reason,
|
||||
effective_line_no=None, # header scope 固定 None
|
||||
evidence_quote=raw_value[:512],
|
||||
evidence_ref=str(item.get('evidence_ref') or '') or None,
|
||||
evidence_metadata=dict(item.get('evidence_metadata') or {}),
|
||||
))
|
||||
return results
|
||||
|
||||
def _collect_table_source(self, mapping: ProfileFieldSourceMapping) -> list[FieldSourceCandidate]:
|
||||
"""表身列来源——从 caller 传入的 table_column_values[column_code] 读取,每行一个候选。"""
|
||||
rows = self.table_column_values.get(mapping.table_column_code or '', [])
|
||||
results: list[FieldSourceCandidate] = []
|
||||
for row in rows:
|
||||
try:
|
||||
line_no = int(row.get('line_index')) + 1 # 转 1-based
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
raw_value = str(row.get('value') or '')
|
||||
format_valid, reason = self._check_format(mapping, raw_value)
|
||||
results.append(FieldSourceCandidate(
|
||||
source='table_column',
|
||||
target_scope=mapping.target_scope,
|
||||
target_field_code=mapping.target_field_code,
|
||||
target_field_id=mapping.target_field_id,
|
||||
value=raw_value,
|
||||
normalized_value=_normalize_string(raw_value),
|
||||
format_valid=format_valid,
|
||||
format_reason_code=reason,
|
||||
effective_line_no=line_no,
|
||||
evidence_quote=raw_value[:512],
|
||||
evidence_ref=str(row.get('evidence_ref') or '') or None,
|
||||
evidence_metadata=dict(row.get('evidence_metadata') or {}),
|
||||
))
|
||||
return results
|
||||
|
||||
def _collect_vendor_comments_source(self, mapping: ProfileFieldSourceMapping) -> list[FieldSourceCandidate]:
|
||||
"""
|
||||
Vendor Comments 来源——三步走:
|
||||
1. CoordinateRegionSourceAdapter 渲染区域原文 + bbox 证据;
|
||||
2. execute_base_split_rule_set 拆出段(带 captured_relation);
|
||||
3. ReservationRelationProjection 投影关系到 effective_line_no / resolution_hint。
|
||||
"""
|
||||
region_ref = mapping.vendor_comments_region_ref or ''
|
||||
region = self.named_regions.get(region_ref)
|
||||
if region is None:
|
||||
return [self._missing_region_fallback(mapping, region_ref)]
|
||||
adapter = CoordinateRegionSourceAdapter(region, self.page_glyphs_map)
|
||||
region_result: CoordinateRegionSourceResult = adapter.extract()
|
||||
if region_result.status != 'available' or not mapping.vendor_comments_split_rule_set:
|
||||
return [self._unavailable_region_candidate(mapping, region_result)]
|
||||
|
||||
split_result = execute_base_split_rule_set(
|
||||
raw_value=region_result.raw_text,
|
||||
rule_set=mapping.vendor_comments_split_rule_set,
|
||||
lines=region_result.lines or None,
|
||||
)
|
||||
|
||||
projector = ReservationRelationProjection(
|
||||
relation_policy=mapping.relation_policy,
|
||||
line_reference_basis=mapping.line_reference_basis,
|
||||
missing_relation_policy=mapping.missing_relation_policy,
|
||||
)
|
||||
# 先收集 mapped 段,再收集 evidence_only 段(annotation_only 用)
|
||||
all_segments: list[_CoreSegmentResult] = list(split_result.segments) + list(split_result.evidence_only_segments)
|
||||
results: list[FieldSourceCandidate] = []
|
||||
token_evidence_map = _build_evidence_ref_map(region_result.evidence_tokens)
|
||||
for seg in all_segments:
|
||||
rel_proj = projector.project(
|
||||
captured_relation=seg.captured_relation,
|
||||
explicit_line_column_values=self.explicit_line_column_values,
|
||||
profile_business_line_numbers=self.profile_business_line_numbers,
|
||||
classified_logical_line_numbers=self.classified_logical_line_numbers,
|
||||
)
|
||||
format_valid, reason = self._check_format(mapping, seg.normalized_text)
|
||||
if rel_proj.resolution == 'bound_to_line':
|
||||
results.append(self._make_vc_candidate(
|
||||
mapping=mapping, seg=seg, rel_proj=rel_proj,
|
||||
region_result=region_result, token_evidence_map=token_evidence_map,
|
||||
effective_line_no=rel_proj.resolved_logical_line_no,
|
||||
resolution_hint='provisional', format_valid=format_valid, format_reason=reason,
|
||||
))
|
||||
elif rel_proj.resolution == 'default_all_lines':
|
||||
# 每行都生成一个(common case:整个 Vendor Comments 段没有 line 号引用)
|
||||
for line_idx in range(1, max(1, self.total_logical_lines) + 1):
|
||||
results.append(self._make_vc_candidate(
|
||||
mapping=mapping, seg=seg, rel_proj=rel_proj,
|
||||
region_result=region_result, token_evidence_map=token_evidence_map,
|
||||
effective_line_no=line_idx if mapping.target_scope == 'line' else None,
|
||||
resolution_hint='provisional', format_valid=format_valid, format_reason=reason,
|
||||
))
|
||||
elif rel_proj.resolution == 'annotation_only':
|
||||
results.append(self._make_vc_candidate(
|
||||
mapping=mapping, seg=seg, rel_proj=rel_proj,
|
||||
region_result=region_result, token_evidence_map=token_evidence_map,
|
||||
effective_line_no=None,
|
||||
resolution_hint='annotation_only', format_valid=format_valid, format_reason=reason,
|
||||
))
|
||||
elif rel_proj.resolution == 'invalid_line_reference':
|
||||
results.append(self._make_vc_candidate(
|
||||
mapping=mapping, seg=seg, rel_proj=rel_proj,
|
||||
region_result=region_result, token_evidence_map=token_evidence_map,
|
||||
effective_line_no=None,
|
||||
resolution_hint='invalid_line_reference', format_valid=False,
|
||||
format_reason=reason or 'invalid_line_reference',
|
||||
))
|
||||
else:
|
||||
# default_header_only / conflict_unresolved
|
||||
results.append(self._make_vc_candidate(
|
||||
mapping=mapping, seg=seg, rel_proj=rel_proj,
|
||||
region_result=region_result, token_evidence_map=token_evidence_map,
|
||||
effective_line_no=None if mapping.target_scope == 'header' else None,
|
||||
resolution_hint='provisional', format_valid=format_valid, format_reason=reason,
|
||||
))
|
||||
return results
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 辅助:格式校验(Q15)+ Vendor Comments 候选构造
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _check_format(
|
||||
self, mapping: ProfileFieldSourceMapping, value: str,
|
||||
) -> tuple[bool | None, str | None]:
|
||||
"""返回 (format_valid, reason_code);非 reservation 字段返回 (None, None)。"""
|
||||
if mapping.target_field_code != 'reservation_id':
|
||||
return None, None
|
||||
if not value:
|
||||
return False, 'reservation_format_empty'
|
||||
if self.format_validator_callback is not None:
|
||||
ok = bool(self.format_validator_callback(mapping.format_policy, value))
|
||||
return (True, None) if ok else (False, 'reservation_format_invalid')
|
||||
# 默认回退全局 validated_reservation_id(Q15 方案 A:本期不重构全局)
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
ok = validated_reservation_id(value) is not None
|
||||
return (True, None) if ok else (False, 'reservation_format_invalid')
|
||||
|
||||
@staticmethod
|
||||
def _missing_region_fallback(mapping: ProfileFieldSourceMapping, region_ref: str) -> FieldSourceCandidate:
|
||||
return FieldSourceCandidate(
|
||||
source='vendor_comments',
|
||||
target_scope=mapping.target_scope,
|
||||
target_field_code=mapping.target_field_code,
|
||||
target_field_id=mapping.target_field_id,
|
||||
value='',
|
||||
normalized_value='',
|
||||
format_valid=None,
|
||||
format_reason_code=None,
|
||||
effective_line_no=None,
|
||||
resolution_hint='provisional',
|
||||
evidence_quote=None,
|
||||
evidence_ref=None,
|
||||
evidence_metadata={'reason': 'named_region_not_found', 'region_ref': region_ref},
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _unavailable_region_candidate(
|
||||
mapping: ProfileFieldSourceMapping, region_result: CoordinateRegionSourceResult,
|
||||
) -> FieldSourceCandidate:
|
||||
return FieldSourceCandidate(
|
||||
source='vendor_comments',
|
||||
target_scope=mapping.target_scope,
|
||||
target_field_code=mapping.target_field_code,
|
||||
target_field_id=mapping.target_field_id,
|
||||
value='',
|
||||
normalized_value='',
|
||||
format_valid=None,
|
||||
format_reason_code=None,
|
||||
effective_line_no=None,
|
||||
resolution_hint='provisional',
|
||||
evidence_quote=region_result.raw_text[:512] or None,
|
||||
evidence_ref=None,
|
||||
evidence_metadata={
|
||||
'reason': region_result.diagnostic_code or 'named_region_unavailable',
|
||||
'diagnostic_message': region_result.diagnostic_message,
|
||||
'region_id': region_result.region_id,
|
||||
},
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _make_vc_candidate(
|
||||
*,
|
||||
mapping: ProfileFieldSourceMapping,
|
||||
seg: _CoreSegmentResult,
|
||||
rel_proj: ReservationRelationProjectionResult,
|
||||
region_result: CoordinateRegionSourceResult,
|
||||
token_evidence_map: dict[str, list[CoordinateRegionEvidence]],
|
||||
effective_line_no: int | None,
|
||||
resolution_hint: Literal['provisional', 'annotation_only', 'invalid_line_reference'],
|
||||
format_valid: bool | None,
|
||||
format_reason: str | None,
|
||||
) -> FieldSourceCandidate:
|
||||
token_ev = _find_best_token_evidence(token_evidence_map, seg.normalized_text)
|
||||
evidence_quote = seg.raw_text[:512] or None
|
||||
evidence_ref = _vc_evidence_ref(region_result, seg, token_ev)
|
||||
metadata: dict[str, Any] = {
|
||||
'region_id': region_result.region_id,
|
||||
'segment_id': seg.segment_id,
|
||||
'rule_id': seg.rule_id,
|
||||
'matcher_type': seg.matcher_type,
|
||||
'handling': seg.handling,
|
||||
'line_bounds_in_region': [seg.line_no, seg.line_end_no],
|
||||
'captured_relation_raw': (
|
||||
None if seg.captured_relation is None else {
|
||||
'type': seg.captured_relation.type,
|
||||
'line_no': seg.captured_relation.line_no,
|
||||
'raw_text': seg.captured_relation.raw_text,
|
||||
}
|
||||
),
|
||||
'relation_projection': _proj_to_json(rel_proj),
|
||||
'best_token': (None if token_ev is None else {
|
||||
'page_no': token_ev.page_no,
|
||||
'x0': token_ev.x0, 'y0': token_ev.y0,
|
||||
'x1': token_ev.x1, 'y1': token_ev.y1,
|
||||
'text': token_ev.text,
|
||||
}),
|
||||
}
|
||||
return FieldSourceCandidate(
|
||||
source='vendor_comments',
|
||||
target_scope=mapping.target_scope,
|
||||
target_field_code=mapping.target_field_code,
|
||||
target_field_id=mapping.target_field_id,
|
||||
value=seg.raw_text,
|
||||
normalized_value=seg.normalized_text,
|
||||
format_valid=format_valid,
|
||||
format_reason_code=format_reason,
|
||||
effective_line_no=effective_line_no,
|
||||
resolution_hint=resolution_hint,
|
||||
relation_projection=rel_proj,
|
||||
evidence_quote=evidence_quote,
|
||||
evidence_ref=evidence_ref,
|
||||
evidence_metadata=metadata,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 模块级纯函数(避免每次 Service 实例化重复加载)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _normalize_string(v: str) -> str:
|
||||
return ' '.join(str(v or '').split()).strip()
|
||||
|
||||
|
||||
def _build_evidence_ref_map(tokens: list[CoordinateRegionEvidence]) -> dict[str, list[CoordinateRegionEvidence]]:
|
||||
out: dict[str, list[CoordinateRegionEvidence]] = {}
|
||||
for t in tokens:
|
||||
out.setdefault(_normalize_string(t.text), []).append(t)
|
||||
return out
|
||||
|
||||
|
||||
def _find_best_token_evidence(
|
||||
evidence_map: dict[str, list[CoordinateRegionEvidence]], value: str,
|
||||
) -> CoordinateRegionEvidence | None:
|
||||
norm = _normalize_string(value)
|
||||
if norm in evidence_map and evidence_map[norm]:
|
||||
return evidence_map[norm][0]
|
||||
# 降级:子串命中
|
||||
for key, tokens in evidence_map.items():
|
||||
if norm and (norm in key or key in norm) and tokens:
|
||||
return tokens[0]
|
||||
return None
|
||||
|
||||
|
||||
def _vc_evidence_ref(
|
||||
region_result: CoordinateRegionSourceResult,
|
||||
seg: _CoreSegmentResult,
|
||||
token: CoordinateRegionEvidence | None,
|
||||
) -> str:
|
||||
"""
|
||||
稳定 Observation.evidence_ref。
|
||||
格式:vc://<region_id>/p<page_no>/seg-<segment_id>[:<x0>-<y0>-<x1>-<y1>]
|
||||
"""
|
||||
base = f"vc://{region_result.region_id}/p{region_result.page_no}/seg-{seg.segment_id}"
|
||||
if token is not None:
|
||||
base += (
|
||||
f":{round(token.x0, 4)}-{round(token.y0, 4)}-"
|
||||
f"{round(token.x1, 4)}-{round(token.y1, 4)}"
|
||||
)
|
||||
return base[:512]
|
||||
|
||||
|
||||
def _proj_to_json(p: ReservationRelationProjectionResult) -> dict[str, Any]:
|
||||
return {
|
||||
'line_reference_basis': p.line_reference_basis,
|
||||
'resolution': p.resolution,
|
||||
'resolved_logical_line_no': p.resolved_logical_line_no,
|
||||
'annotation_reason': p.annotation_reason,
|
||||
'invalid_reference_raw_value': p.invalid_reference_raw_value,
|
||||
'invalid_reference_line_no': p.invalid_reference_line_no,
|
||||
'audit_chain_count': 0 if p.audit_chain is None else len(p.audit_chain),
|
||||
}
|
||||
-338
@@ -1,338 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/profile_vendor_comments_contract.py
|
||||
|
||||
用途:Profile 顶层新增的 Vendor Comments 三来源契约(不修改现有 OrderCoordinateProfile 字段,
|
||||
保持「路径判断与事实分离」——definition_json.get 读取命名区域和字段来源映射)。
|
||||
依赖:Pydantic、field_split_core.BaseSplitRuleSet、RelativeRegion(来自 order_profile)。
|
||||
逻辑:对外暴露 parse_named_regions() / parse_field_source_mappings() / validate_format_policy()
|
||||
三个稳定入口;所有变更是否触发「回 Draft + 重新验证」由 profile_regions_require_draft()
|
||||
判定,禁止各业务点自行假设回 Draft 条件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.document_layout.field_split_core import (
|
||||
BaseSplitRuleSet,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
RelativeRegion,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 顶层 Pydantic 契约——definition_json 结构
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
VC_MODEL_CONFIG = ConfigDict(extra='forbid', validate_assignment=True)
|
||||
|
||||
|
||||
class NamedRegion(BaseModel):
|
||||
"""
|
||||
物理来源命名区域(Q14 冻结)——管理员圈选的坐标框。
|
||||
|
||||
【关键约束】:不是 Schema 字段区域伪装,是 Vendor Comments 等非 XFA 正文块的真实
|
||||
阅读区域。变更此对象必须回 Draft(由 profile_regions_require_draft 判定)。
|
||||
"""
|
||||
|
||||
model_config = VC_MODEL_CONFIG
|
||||
|
||||
region_id: str = Field(pattern=r'^[a-z][a-z0-9_-]{0,95}$')
|
||||
label: str = Field(min_length=1, max_length=160)
|
||||
region: RelativeRegion
|
||||
page_scope: Literal['first_page', 'last_page', 'all_pages', 'exact_page'] = 'last_page'
|
||||
page_no: int | None = Field(default=None, ge=1)
|
||||
selection_mode: Literal['fixed_region', 'auto_take_last_qualified'] = 'fixed_region'
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_page_semantics(self) -> 'NamedRegion':
|
||||
if self.page_scope == 'exact_page' and self.page_no is None:
|
||||
raise ValueError('exact_page named region requires page_no')
|
||||
if self.page_scope != 'exact_page' and self.page_no is not None:
|
||||
raise ValueError('page_no is only allowed for exact_page named region')
|
||||
return self
|
||||
|
||||
|
||||
class ReservationFormatPolicy(BaseModel):
|
||||
"""
|
||||
Reservation 格式校验策略(Q15 冻结)——Profile 级受控策略,未配置时回退全局 5/10 纯数字。
|
||||
|
||||
首期仅支持 numeric_5_or_10 / custom_safe_regex 两种;custom_safe_regex 必须经过
|
||||
长度限制、捕获组限制、危险表达式黑名单与超时上限 4 层门禁。
|
||||
"""
|
||||
|
||||
model_config = VC_MODEL_CONFIG
|
||||
|
||||
mode: Literal['inherit_global', 'numeric_5_or_10', 'custom_safe_regex'] = 'inherit_global'
|
||||
pattern: str | None = Field(default=None, min_length=1, max_length=1024)
|
||||
max_capture_groups: int = Field(default=2, ge=0, le=8)
|
||||
timeout_ms: int = Field(default=30, ge=10, le=500)
|
||||
case_sensitive: bool = False
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_regex_policy(self) -> 'ReservationFormatPolicy':
|
||||
if self.mode != 'custom_safe_regex':
|
||||
if self.pattern is not None:
|
||||
raise ValueError('pattern only allowed for custom_safe_regex mode')
|
||||
return self
|
||||
if not self.pattern:
|
||||
raise ValueError('custom_safe_regex requires a non-empty pattern')
|
||||
_validate_safe_regex_pattern(
|
||||
self.pattern,
|
||||
max_groups=self.max_capture_groups,
|
||||
case_sensitive=self.case_sensitive,
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class ProfileFieldSourceMapping(BaseModel):
|
||||
"""
|
||||
Profile 级字段来源映射(Q9 冻结,并列 split_rules)——声明一个 Schema 字段从三来源
|
||||
(header/table_column/vendor_comments)哪几个抽取,以及各自使用的拆分规则与关系策略。
|
||||
"""
|
||||
|
||||
model_config = VC_MODEL_CONFIG
|
||||
|
||||
mapping_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
target_scope: Literal['header', 'line']
|
||||
target_field_code: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
target_field_id: str = Field(min_length=1, max_length=128)
|
||||
|
||||
# 三来源开关——未启用的来源在 ProfileFieldSourceMappingService 直接跳过
|
||||
header_source_enabled: bool = False
|
||||
header_source_ref: str | None = Field(default=None, pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
header_normalizer_key: str | None = Field(default=None, min_length=1, max_length=64)
|
||||
|
||||
table_source_enabled: bool = False
|
||||
table_column_code: str | None = Field(default=None, pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
|
||||
vendor_comments_enabled: bool = False
|
||||
vendor_comments_region_ref: str | None = Field(default=None, pattern=r'^[a-z][a-z0-9_-]{0,95}$')
|
||||
vendor_comments_split_rule_set: BaseSplitRuleSet | None = None
|
||||
|
||||
# 关系策略(Q2 双层设计)——本期仅 reservation_id 绑定明细行使用 bind_target_line
|
||||
relation_policy: Literal['no_relation', 'bind_target_line', 'annotation_only'] = 'no_relation'
|
||||
missing_relation_policy: Literal['default_all_lines', 'default_header_only', 'fallback_single_line_when_no_reference'] = 'default_header_only'
|
||||
line_reference_basis: Literal['explicit_line_column', 'profile_business_line_no', 'classified_logical_line_no'] = 'profile_business_line_no'
|
||||
|
||||
# 三来源空值互补策略——Q4 冲突矩阵里不同 scope 独立保留,同 scope 值不一致 Review
|
||||
fill_missing_from_other_sources: bool = True
|
||||
|
||||
format_policy: ReservationFormatPolicy = Field(default_factory=ReservationFormatPolicy)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_source_refs(self) -> 'ProfileFieldSourceMapping':
|
||||
if self.header_source_enabled and not self.header_source_ref:
|
||||
raise ValueError('header_source_ref is required when header_source_enabled')
|
||||
if self.table_source_enabled and not self.table_column_code:
|
||||
raise ValueError('table_column_code is required when table_source_enabled')
|
||||
if self.vendor_comments_enabled:
|
||||
if not self.vendor_comments_region_ref:
|
||||
raise ValueError('vendor_comments_region_ref is required when vendor_comments_enabled')
|
||||
if not self.vendor_comments_split_rule_set:
|
||||
raise ValueError('vendor_comments_split_rule_set is required when vendor_comments_enabled')
|
||||
return self
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 稳定读取工具:接受 None / 脏 dict,返回归一化契约对象(路径判断与事实分离)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def parse_named_regions(value: Any) -> dict[str, NamedRegion]:
|
||||
"""
|
||||
从 definition_json.named_regions(或 None)解析命名区域字典。
|
||||
|
||||
【AI 触发时机】:读取 Profile 配置阶段、预览阶段或变更比对阶段调用。
|
||||
核心逻辑:值为 None/空 dict 时返回空字典(允许客户先不配 Vendor Comments 区域);
|
||||
未知键直接保留映射,不抛错;坏值立刻抛 ValidationError 避免运行时污染。
|
||||
|
||||
Args:
|
||||
value: Profile definition_json.get('named_regions') 原值。
|
||||
|
||||
Returns:
|
||||
{region_id: NamedRegion} 字典。
|
||||
"""
|
||||
if value is None:
|
||||
return {}
|
||||
if not isinstance(value, dict):
|
||||
raise ValidationError(
|
||||
'definition_json.named_regions must be an object',
|
||||
code='SHIPPING.PROFILE_NAMED_REGIONS_INVALID',
|
||||
)
|
||||
result: dict[str, NamedRegion] = {}
|
||||
for key, raw in value.items():
|
||||
if not re.match(r'^[a-z][a-z0-9_-]{0,95}$', str(key)):
|
||||
raise ValidationError(
|
||||
f'named region key {key!r} is invalid',
|
||||
code='SHIPPING.PROFILE_NAMED_REGIONS_INVALID',
|
||||
)
|
||||
try:
|
||||
item = NamedRegion.model_validate(raw) if isinstance(raw, dict) else raw
|
||||
except ValueError as exc:
|
||||
raise ValidationError(
|
||||
f'named region {key!r} is invalid: {exc}',
|
||||
code='SHIPPING.PROFILE_NAMED_REGIONS_INVALID',
|
||||
) from exc
|
||||
if item.region_id != key:
|
||||
raise ValidationError(
|
||||
f'named region key {key!r} must match nested region_id {item.region_id!r}',
|
||||
code='SHIPPING.PROFILE_NAMED_REGIONS_MISMATCH',
|
||||
)
|
||||
result[key] = item
|
||||
return result
|
||||
|
||||
|
||||
def parse_field_source_mappings(value: Any) -> list[ProfileFieldSourceMapping]:
|
||||
"""
|
||||
从 definition_json.field_source_mappings(或 None)解析字段来源映射列表。
|
||||
|
||||
核心逻辑:返回值为稳定顺序列表,不做去重(重复的 target_scope/target_field_code
|
||||
组合将由 SourceMergeService 在抽取层做 Q18 冲突裁决)。
|
||||
"""
|
||||
if value is None:
|
||||
return []
|
||||
if not isinstance(value, list):
|
||||
raise ValidationError(
|
||||
'definition_json.field_source_mappings must be a list',
|
||||
code='SHIPPING.PROFILE_FIELD_SOURCE_MAPPINGS_INVALID',
|
||||
)
|
||||
results: list[ProfileFieldSourceMapping] = []
|
||||
for raw in value:
|
||||
try:
|
||||
results.append(ProfileFieldSourceMapping.model_validate(raw))
|
||||
except ValueError as exc:
|
||||
raise ValidationError(
|
||||
f'field source mapping is invalid: {exc}',
|
||||
code='SHIPPING.PROFILE_FIELD_SOURCE_MAPPINGS_INVALID',
|
||||
) from exc
|
||||
return results
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 变更回 Draft 门禁(Q14 冻结:区域变化必须使 Profile 回 Draft)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
REGION_CHANGE_REQUIRES_DRAFT_KEYS = frozenset({
|
||||
'region', 'page_scope', 'page_no', 'selection_mode',
|
||||
})
|
||||
|
||||
|
||||
def profile_regions_require_draft(
|
||||
*,
|
||||
old_named_regions: Any,
|
||||
new_named_regions: Any,
|
||||
) -> bool:
|
||||
"""
|
||||
判断 named_regions 变更是否触发 Profile 回 Draft + 重新验证 + 盲测 + 发布。
|
||||
|
||||
核心逻辑(fail-safe):任何 region 主键、坐标、页作用域、选取模式的增删改一律回 Draft;
|
||||
仅 label 文案调整(便于管理员标注说明)不触发。
|
||||
"""
|
||||
try:
|
||||
old_map = parse_named_regions(old_named_regions)
|
||||
new_map = parse_named_regions(new_named_regions)
|
||||
except ValidationError:
|
||||
return True # 解析失败默认回 Draft(fail-close)
|
||||
if set(old_map.keys()) != set(new_map.keys()):
|
||||
return True
|
||||
for region_id in old_map:
|
||||
old_region = old_map[region_id]
|
||||
new_region = new_map[region_id]
|
||||
for key in REGION_CHANGE_REQUIRES_DRAFT_KEYS:
|
||||
if getattr(old_region, key) != getattr(new_region, key):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def field_source_mappings_require_draft(
|
||||
*,
|
||||
old_mappings: Any,
|
||||
new_mappings: Any,
|
||||
) -> bool:
|
||||
"""
|
||||
判断 field_source_mappings 变更是否触发回 Draft。
|
||||
|
||||
核心逻辑:除了纯 label 类改动外的任何增删改一律回 Draft(首期全量回 Draft,保留细粒度
|
||||
门禁的未来扩展点)。
|
||||
"""
|
||||
try:
|
||||
old_list = parse_field_source_mappings(old_mappings)
|
||||
new_list = parse_field_source_mappings(new_mappings)
|
||||
except ValidationError:
|
||||
return True
|
||||
if len(old_list) != len(new_list):
|
||||
return True
|
||||
old_payload = _stable_mapping_dumps(old_list)
|
||||
new_payload = _stable_mapping_dumps(new_list)
|
||||
return old_payload != new_payload
|
||||
|
||||
|
||||
def _stable_mapping_dumps(items: list[ProfileFieldSourceMapping]) -> str:
|
||||
payload = [m.model_dump(mode='json', sort_keys=True) for m in items]
|
||||
return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 安全正则门禁(Q15 custom_safe_regex 发布前必过)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
_UNSAFE_PATTERN_MARKERS = (
|
||||
r'\(.+[+*]\)\s*[+*]', # 嵌套量词 例: (a+)+
|
||||
r'\(\.?\*\)\s*\*', # 多重.* 回溯
|
||||
r'\(\[.*\]\)\{[0-9]+,[0-9]*\}', # 大范围字符类重复
|
||||
r'(?<!\\)\\[bBwWsSdD].*[+*]', # 通用字符集 + 无限量词
|
||||
r'\(\?:?\^?\$?.*\)\?\?', # 前后查找量词叠加
|
||||
)
|
||||
|
||||
|
||||
def _validate_safe_regex_pattern(pattern: str, *, max_groups: int, case_sensitive: bool) -> None:
|
||||
"""
|
||||
custom_safe_regex 的发布前样本验证门禁(Q15)——编译期就拦截危险表达式。
|
||||
【注意】:运行时还需配合 timeout_ms 的 signal 看门狗(在 regex_runner_safe 中实现)。
|
||||
"""
|
||||
if len(pattern) > 1024:
|
||||
raise ValueError('custom_safe_regex pattern exceeds 1024 characters')
|
||||
for marker in _UNSAFE_PATTERN_MARKERS:
|
||||
if re.search(marker, pattern):
|
||||
raise ValueError('custom_safe_regex pattern looks potentially catastrophic')
|
||||
flags = 0 if case_sensitive else re.IGNORECASE
|
||||
try:
|
||||
compiled = re.compile(pattern, flags)
|
||||
except re.error as exc:
|
||||
raise ValueError(f'custom_safe_regex pattern failed to compile: {exc}') from exc
|
||||
if compiled.groups > max_groups:
|
||||
raise ValueError(
|
||||
f'custom_safe_regex has {compiled.groups} capture groups; limit is {max_groups}'
|
||||
)
|
||||
_ = compiled # 引用仅用于静态检查
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 校验和(盲测/发布基准比对)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def field_source_mappings_checksum(mappings: list[ProfileFieldSourceMapping]) -> str:
|
||||
"""稳定 SHA-256 校验和,供发布冻结与审计引用。"""
|
||||
payload = _stable_mapping_dumps(mappings).encode('utf-8')
|
||||
return hashlib.sha256(payload).hexdigest()
|
||||
|
||||
|
||||
def named_regions_checksum(regions: dict[str, NamedRegion]) -> str:
|
||||
"""稳定 SHA-256 校验和,供区域变更历史比对。"""
|
||||
payload = json.dumps(
|
||||
{rid: r.model_dump(mode='json', sort_keys=True) for rid, r in regions.items()},
|
||||
ensure_ascii=True, sort_keys=True, separators=(',', ':'),
|
||||
).encode('utf-8')
|
||||
return hashlib.sha256(payload).hexdigest()
|
||||
-152
@@ -1,152 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/reservation_format_policy_service.py
|
||||
|
||||
用途:Q15 Reservation ID 格式策略服务——Profile 级 format_policy 受控入口。
|
||||
首期(阶段 2)保持「回退全局 validated_reservation_id(numeric_5_or_10 硬编码)」
|
||||
不变;为未来 custom_safe_regex / 字母型 Reservation 保留扩展点。
|
||||
依赖:profile_vendor_comments_contract.ReservationFormatPolicy;
|
||||
reservation_id.validated_reservation_id(全局回退)。
|
||||
逻辑:【技术重试与业务决策分离】——本类只负责**格式判断**,不改变值、不生成 Observation,
|
||||
调用方(ProfileFieldSourceMappingService._check_format)根据返回值标记
|
||||
reservation_format_invalid,但不丢弃候选(保留为 Review 证据展示)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
|
||||
from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import (
|
||||
ReservationFormatPolicy,
|
||||
)
|
||||
|
||||
|
||||
RESERVATION_NUMERIC_5_OR_10_RE = re.compile(r'^(?:\d{5}|\d{10})$')
|
||||
|
||||
|
||||
@dataclass
|
||||
class FormatPolicyResult:
|
||||
"""格式校验结果——只描述事实,不携带业务动作。"""
|
||||
|
||||
valid: bool
|
||||
mode: Literal['inherit_global', 'numeric_5_or_10', 'custom_safe_regex']
|
||||
normalized_value: str | None = None # 仅 valid=True 时返回规范化值
|
||||
reason_code: str | None = None # valid=False 时的稳定诊断码
|
||||
|
||||
@property
|
||||
def should_block_auto_create(self) -> bool:
|
||||
"""格式失败的值不得自动建单(Q15 冻结)。"""
|
||||
return not self.valid
|
||||
|
||||
|
||||
class ReservationFormatPolicyService:
|
||||
"""
|
||||
Profile 级 Reservation 格式策略受控入口。
|
||||
|
||||
【AI 触发时机】:ProfileFieldSourceMappingService 收集候选、或 Candidate
|
||||
Qualification 最终门禁时调用 check()。禁止任何地方直接
|
||||
if re.match(r'^\d{5,10}$', v) 绕过策略层。
|
||||
"""
|
||||
|
||||
def check(self, policy: ReservationFormatPolicy, raw_value: str) -> FormatPolicyResult:
|
||||
"""
|
||||
执行一次格式校验。调用方不得丢弃失败候选,必须将原因码写入
|
||||
FieldSourceCandidate.format_reason_code。
|
||||
|
||||
核心路径(Q15 冻结):
|
||||
① mode=inherit_global → 调全局 validated_reservation_id 保持历史 71 调用方口径;
|
||||
② mode=numeric_5_or_10 → 等价于全局(显式模式;便于未来全局重构时切换默认);
|
||||
③ mode=custom_safe_regex → 调用发布前已通过 Pydantic 门禁的安全正则。
|
||||
"""
|
||||
value = (raw_value or '').strip()
|
||||
if not value:
|
||||
return FormatPolicyResult(
|
||||
valid=False, mode=policy.mode, normalized_value=None,
|
||||
reason_code='reservation_format_empty',
|
||||
)
|
||||
mode = policy.mode
|
||||
if mode in {'inherit_global', 'numeric_5_or_10'}:
|
||||
return self._check_numeric_5_or_10(value, mode)
|
||||
if mode == 'custom_safe_regex':
|
||||
return self._check_custom_safe_regex(policy, value)
|
||||
return FormatPolicyResult(
|
||||
valid=False, mode=mode, normalized_value=None,
|
||||
reason_code='reservation_format_unknown_mode',
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 内部实现
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _check_numeric_5_or_10(
|
||||
value: str,
|
||||
mode: Literal['inherit_global', 'numeric_5_or_10'],
|
||||
) -> FormatPolicyResult:
|
||||
"""纯数字 5/10 位——默认回退全局校验,但通过独立模块输出稳定结果。"""
|
||||
# 先尝试全局 validated_reservation_id(保持与 71 调用方一致),失败再用本模块常量兜底
|
||||
try:
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
global_result = validated_reservation_id(value)
|
||||
if global_result is not None:
|
||||
return FormatPolicyResult(
|
||||
valid=True, mode=mode, normalized_value=global_result,
|
||||
reason_code=None,
|
||||
)
|
||||
except Exception: # fail-safe:若全局模块异常,不阻塞结果
|
||||
pass
|
||||
match = RESERVATION_NUMERIC_5_OR_10_RE.match(value)
|
||||
if match:
|
||||
return FormatPolicyResult(
|
||||
valid=True, mode=mode, normalized_value=value,
|
||||
reason_code=None,
|
||||
)
|
||||
return FormatPolicyResult(
|
||||
valid=False, mode=mode, normalized_value=None,
|
||||
reason_code='reservation_format_invalid',
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _check_custom_safe_regex(policy: ReservationFormatPolicy, value: str) -> FormatPolicyResult:
|
||||
"""安全正则匹配——编译缓存;捕获组第 1 组作为规范化值(否则整串)。"""
|
||||
pattern = policy.pattern or ''
|
||||
flags = 0 if policy.case_sensitive else re.IGNORECASE
|
||||
try:
|
||||
compiled = re.compile(pattern, flags)
|
||||
except re.error as exc:
|
||||
return FormatPolicyResult(
|
||||
valid=False, mode='custom_safe_regex', normalized_value=None,
|
||||
reason_code=f'reservation_format_regex_compile_error:{exc.__class__.__name__}',
|
||||
)
|
||||
# 发布前样本验证门禁已限制 catastrophic 风险;这里仅以标准 library 限制长度
|
||||
if len(value) > 128:
|
||||
return FormatPolicyResult(
|
||||
valid=False, mode='custom_safe_regex', normalized_value=None,
|
||||
reason_code='reservation_format_value_too_long',
|
||||
)
|
||||
match = compiled.search(value)
|
||||
if not match:
|
||||
return FormatPolicyResult(
|
||||
valid=False, mode='custom_safe_regex', normalized_value=None,
|
||||
reason_code='reservation_format_invalid',
|
||||
)
|
||||
# 规范化值:第 1 捕获组 → 整串
|
||||
normalized: str = value
|
||||
if compiled.groups >= 1:
|
||||
try:
|
||||
first_group = match.group(1)
|
||||
if first_group:
|
||||
normalized = str(first_group).strip()
|
||||
except (IndexError, re.error):
|
||||
normalized = match.group(0) or value
|
||||
normalized = normalized.strip()
|
||||
if not normalized:
|
||||
return FormatPolicyResult(
|
||||
valid=False, mode='custom_safe_regex', normalized_value=None,
|
||||
reason_code='reservation_format_capture_empty',
|
||||
)
|
||||
return FormatPolicyResult(
|
||||
valid=True, mode='custom_safe_regex', normalized_value=normalized,
|
||||
reason_code=None,
|
||||
)
|
||||
-228
@@ -1,228 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/reservation_relation_projection.py
|
||||
|
||||
用途:Reservation 关系投影(Q2 双层设计 + Q12 invalid_line_reference 独立原因码)。
|
||||
将拆分引擎内部捕获的 captured_relation + Profile 关系策略 relation_policy,
|
||||
映射为「绑定到哪条行、是否 annotation_only、是否 invalid_line_reference 独立」三输出。
|
||||
依赖:field_split_core.CoreCapturedRelation(来自 _CoreSegmentResult.captured_relation)、
|
||||
ProfileFieldSourceMapping.relation_policy / line_reference_basis。
|
||||
逻辑:严格遵循「路径判断与事实分离」——拆分引擎事实(line_no)只作为证据,
|
||||
最终绑定路径必须经过 line_reference_basis 三层映射校验后裁决;
|
||||
失败不抛异常,输出稳定 reason_code 供审计和前端翻译。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Literal
|
||||
|
||||
from app.services.shipping_notice.document_layout.field_split_core import (
|
||||
CoreCapturedRelation,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ReservationRelationProjectionResult:
|
||||
"""关系投影最终结果——只输出明确分支,禁止上游自行判断。"""
|
||||
|
||||
line_reference_basis: Literal[
|
||||
'explicit_line_column',
|
||||
'profile_business_line_no',
|
||||
'classified_logical_line_no',
|
||||
]
|
||||
resolution: Literal[
|
||||
'bound_to_line', # bind_target_line 成功,resolved_logical_line_no 有值
|
||||
'annotation_only', # 显式 annotation_only,Observation 存 metadata
|
||||
'default_all_lines', # 关系缺失 + default_all_lines,每行都生成 Observation
|
||||
'default_header_only', # 关系缺失 + default_header_only,写到 header scope
|
||||
'invalid_line_reference', # 引用了不存在的行号,独立原因码 Q12
|
||||
'conflict_unresolved', # 未来多层映射冲突保留(本期不输出)
|
||||
]
|
||||
resolved_logical_line_no: int | None = None # 1-based 逻辑行号,bound_to_line 时必填
|
||||
annotation_reason: str | None = None # annotation_only 时写入 Observation metadata
|
||||
invalid_reference_raw_value: str | None = None # invalid_line_reference 时返回 raw_text
|
||||
invalid_reference_line_no: int | None = None
|
||||
audit_chain: list[dict[str, Any]] | None = None # 路径判断全链路审计快照
|
||||
|
||||
@property
|
||||
def should_generate_line_observation(self) -> bool:
|
||||
return self.resolution == 'bound_to_line' or self.resolution == 'default_all_lines'
|
||||
|
||||
@property
|
||||
def should_generate_header_observation(self) -> bool:
|
||||
return self.resolution in {'default_header_only', 'annotation_only', 'invalid_line_reference'}
|
||||
|
||||
|
||||
class ReservationRelationProjection:
|
||||
"""
|
||||
把 captured_relation(规则层事实) + profile relation_policy(解释层策略)
|
||||
投影为最终绑定结果。
|
||||
|
||||
【AI 触发时机】:三来源合并前,为每个 Vendor Comments / Header Reservation 候选
|
||||
决定「写行 Observation 还是写头 Observation 还是 invalid_line_reference」时调用。
|
||||
|
||||
核心路径:
|
||||
[STEP 1] 若 relation_policy=annotation_only → 直接走 annotation_only 分支(审计记录原因)。
|
||||
[STEP 2] 若缺失 captured_relation → 走 missing_relation_policy 分支
|
||||
(default_all_lines / default_header_only / fallback_single_line_when_no_reference)。
|
||||
[STEP 3] 若有 captured_relation.line_no,按 line_reference_basis 三层校验:
|
||||
① explicit_line_column:对比 Schema Line 字段值(显式 Line 列),失败→invalid
|
||||
② profile_business_line_no:对比 Profile 业务行号(默认客户 PO 行号)
|
||||
③ classified_logical_line_no:逻辑行号(行序分类后的结果)
|
||||
三层任何一层命中即返回 bound_to_line;全部失败输出 invalid_line_reference 独立原因码。
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
relation_policy: Literal['no_relation', 'bind_target_line', 'annotation_only'],
|
||||
line_reference_basis: Literal[
|
||||
'explicit_line_column',
|
||||
'profile_business_line_no',
|
||||
'classified_logical_line_no',
|
||||
] = 'profile_business_line_no',
|
||||
missing_relation_policy: Literal[
|
||||
'default_all_lines',
|
||||
'default_header_only',
|
||||
'fallback_single_line_when_no_reference',
|
||||
] = 'default_header_only',
|
||||
):
|
||||
self.relation_policy = relation_policy
|
||||
self.line_reference_basis = line_reference_basis
|
||||
self.missing_relation_policy = missing_relation_policy
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 对外入口
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def project(
|
||||
self,
|
||||
*,
|
||||
captured_relation: CoreCapturedRelation | None,
|
||||
# 下面四个映射是 Line Reference Basis 的判定表(caller 注入,避免本类查 Schema)
|
||||
explicit_line_column_values: dict[int, str] | None = None,
|
||||
profile_business_line_numbers: dict[int, Any] | None = None,
|
||||
classified_logical_line_numbers: dict[int, int] | None = None,
|
||||
# 审计备注(annotation_only 时必须填写原因字符串,例如 'customer_commentary_only')
|
||||
annotation_reason_override: str | None = None,
|
||||
) -> ReservationRelationProjectionResult:
|
||||
"""
|
||||
执行关系投影。
|
||||
|
||||
【禁止 caller 自行推导】:不要在外部用 if captured_relation.line_no in ... 判断,
|
||||
必须走 project() 返回的稳定 resolution 分支。
|
||||
"""
|
||||
audit: list[dict[str, Any]] = [
|
||||
{'step': 'policy_in', 'relation_policy': self.relation_policy,
|
||||
'line_reference_basis': self.line_reference_basis,
|
||||
'missing_relation_policy': self.missing_relation_policy},
|
||||
]
|
||||
|
||||
# [STEP 1] annotation_only 直接返回(本期用于 Customer 备注说明、不参与建单)
|
||||
if self.relation_policy == 'annotation_only':
|
||||
audit.append({'step': 'annotation_only',
|
||||
'reason': annotation_reason_override or 'profile_relation_policy_annotation_only'})
|
||||
return ReservationRelationProjectionResult(
|
||||
line_reference_basis=self.line_reference_basis,
|
||||
resolution='annotation_only',
|
||||
annotation_reason=annotation_reason_override or 'profile_relation_policy_annotation_only',
|
||||
audit_chain=audit,
|
||||
)
|
||||
|
||||
# [STEP 2] 缺失 captured_relation → 走 missing_relation_policy
|
||||
if captured_relation is None or captured_relation.line_no is None:
|
||||
audit.append({'step': 'missing_relation',
|
||||
'raw_text': captured_relation.raw_text if captured_relation else None})
|
||||
return self._resolve_missing_policy(audit)
|
||||
|
||||
# [STEP 3] 三层 line_reference_basis 判定(显式 Line 列值 → Profile 业务行号 → 逻辑行号)
|
||||
rel_line_no = int(captured_relation.line_no)
|
||||
audit.append({'step': 'relation_line_no_in', 'line_no': rel_line_no,
|
||||
'raw_text': captured_relation.raw_text})
|
||||
|
||||
basis_order = self._basis_order()
|
||||
for basis_name in basis_order:
|
||||
resolved = self._try_basis(basis_name, rel_line_no, explicit_line_column_values or {},
|
||||
profile_business_line_numbers or {},
|
||||
classified_logical_line_numbers or {})
|
||||
if resolved is not None:
|
||||
audit.append({'step': 'basis_hit', 'basis': basis_name,
|
||||
'logical_line_no': resolved})
|
||||
return ReservationRelationProjectionResult(
|
||||
line_reference_basis=self.line_reference_basis,
|
||||
resolution='bound_to_line',
|
||||
resolved_logical_line_no=resolved,
|
||||
audit_chain=audit,
|
||||
)
|
||||
|
||||
# 三层全不命中 → invalid_line_reference(Q12 独立原因码 + 独立审计链)
|
||||
audit.append({'step': 'invalid_line_reference', 'tried_bases': basis_order})
|
||||
return ReservationRelationProjectionResult(
|
||||
line_reference_basis=self.line_reference_basis,
|
||||
resolution='invalid_line_reference',
|
||||
invalid_reference_raw_value=captured_relation.raw_text,
|
||||
invalid_reference_line_no=rel_line_no,
|
||||
audit_chain=audit,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 内部步骤
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _basis_order(self) -> list[str]:
|
||||
"""按 Profile.line_reference_basis 输出优先级顺序。"""
|
||||
if self.line_reference_basis == 'explicit_line_column':
|
||||
return ['explicit_line_column', 'profile_business_line_no', 'classified_logical_line_no']
|
||||
if self.line_reference_basis == 'profile_business_line_no':
|
||||
return ['profile_business_line_no', 'classified_logical_line_no', 'explicit_line_column']
|
||||
return ['classified_logical_line_no', 'profile_business_line_no', 'explicit_line_column']
|
||||
|
||||
def _try_basis(
|
||||
self,
|
||||
basis: str,
|
||||
rel_line_no: int,
|
||||
explicit: dict[int, str],
|
||||
profile_biz: dict[int, Any],
|
||||
logical: dict[int, int],
|
||||
) -> int | None:
|
||||
"""尝试一层判定;命中则返回逻辑行号(1-based),否则返回 None。"""
|
||||
if basis == 'explicit_line_column':
|
||||
for logical_idx, raw in explicit.items():
|
||||
if str(raw).strip() == str(rel_line_no):
|
||||
return int(logical_idx)
|
||||
return None
|
||||
if basis == 'profile_business_line_no':
|
||||
for logical_idx, raw in profile_biz.items():
|
||||
if str(raw).strip() == str(rel_line_no):
|
||||
return int(logical_idx)
|
||||
return None
|
||||
if basis == 'classified_logical_line_no':
|
||||
for logical_idx, mapped in logical.items():
|
||||
if int(mapped) == rel_line_no:
|
||||
return int(logical_idx)
|
||||
return None
|
||||
return None
|
||||
|
||||
def _resolve_missing_policy(self, audit: list[dict[str, Any]]) -> ReservationRelationProjectionResult:
|
||||
"""缺失关系时按 missing_relation_policy 落分支。"""
|
||||
policy = self.missing_relation_policy
|
||||
audit.append({'step': 'missing_policy', 'policy': policy})
|
||||
if policy == 'default_all_lines':
|
||||
return ReservationRelationProjectionResult(
|
||||
line_reference_basis=self.line_reference_basis,
|
||||
resolution='default_all_lines',
|
||||
audit_chain=audit,
|
||||
)
|
||||
if policy == 'fallback_single_line_when_no_reference':
|
||||
# Q7 开关:默认 OFF;当前 Profile 显式开启时才使用——第一期所有客户 OFF
|
||||
# 若未来启用,应当返回 bound_to_line → 1;本期保持 default_header_only 语义
|
||||
return ReservationRelationProjectionResult(
|
||||
line_reference_basis=self.line_reference_basis,
|
||||
resolution='default_header_only',
|
||||
audit_chain=audit + [{'step': 'fallback_disabled_by_q7_default'}],
|
||||
)
|
||||
return ReservationRelationProjectionResult(
|
||||
line_reference_basis=self.line_reference_basis,
|
||||
resolution='default_header_only',
|
||||
audit_chain=audit,
|
||||
)
|
||||
@@ -0,0 +1,244 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/runtime_parse_strategy.py
|
||||
|
||||
用途:为已唯一命中的 Coordinate/OCR 订单模板按当前文档证据选择页范围与明细行重建方式。
|
||||
依赖:仅标准库;由正式抽取与模板质量验证共同调用。
|
||||
逻辑:不修改模板,不猜测业务值;固定/自适应重建结果只有唯一可用时才被采用,冲突统一转 Review。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Literal
|
||||
|
||||
|
||||
RowMode = Literal['fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns']
|
||||
StrategyStatus = Literal['selected', 'needs_review']
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RuntimeParseStrategy:
|
||||
"""当前文档的临时解析计划,不写回 Profile 或改变后续 Candidate Gate。"""
|
||||
|
||||
status: StrategyStatus
|
||||
page_nos: tuple[int, ...]
|
||||
row_mode: RowMode | None
|
||||
reason_codes: tuple[str, ...]
|
||||
|
||||
|
||||
def resolve_runtime_parse_strategy(
|
||||
*, page_glyphs: dict[str, Any], fixed_rows: list[dict[str, Any]], adaptive_rows: list[dict[str, Any]],
|
||||
dynamic_rows: list[dict[str, Any]] | None = None,
|
||||
) -> RuntimeParseStrategy:
|
||||
"""按页级证据与三种重建结果选择唯一安全策略。
|
||||
|
||||
Args:
|
||||
page_glyphs: 当前 Layout 的页级坐标事实;空页不进入续页候选。
|
||||
fixed_rows: 固定子行重建结果。
|
||||
adaptive_rows: 自适应列重建结果。
|
||||
dynamic_rows: 不受静态表头排除区影响的动态 X 列重建结果。
|
||||
|
||||
Returns:
|
||||
``selected`` 时调用方只消费 ``row_mode`` 对应结果;关键行不同或均不可用时返回
|
||||
``needs_review``,由既有 Route/Candidate Gate 阻断自动建单。
|
||||
"""
|
||||
page_nos = tuple(sorted(
|
||||
int(page_no) for page_no, glyphs in page_glyphs.items()
|
||||
if str(page_no).isdigit() and int(page_no) > 0 and isinstance(glyphs, list) and glyphs
|
||||
))
|
||||
fixed_valid = _valid_rows(fixed_rows)
|
||||
adaptive_valid = _valid_rows(adaptive_rows)
|
||||
dynamic_valid = _valid_rows(dynamic_rows or [])
|
||||
baseline_rows: list[dict[str, Any]] = []
|
||||
baseline = None
|
||||
if fixed_valid and not adaptive_valid:
|
||||
baseline_rows = fixed_valid
|
||||
baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ())
|
||||
elif adaptive_valid and not fixed_valid:
|
||||
baseline_rows = adaptive_valid
|
||||
baseline = RuntimeParseStrategy(
|
||||
'selected', page_nos, 'adaptive_record_columns',
|
||||
('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',),
|
||||
)
|
||||
elif fixed_valid and adaptive_valid:
|
||||
relation = _compare_row_field_completeness(fixed_valid, adaptive_valid)
|
||||
if relation == 'fixed_preferred':
|
||||
baseline_rows = fixed_valid
|
||||
baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ())
|
||||
elif relation == 'adaptive_preferred':
|
||||
baseline_rows = adaptive_valid
|
||||
baseline = RuntimeParseStrategy(
|
||||
'selected', page_nos, 'adaptive_record_columns',
|
||||
('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',),
|
||||
)
|
||||
elif relation == 'same':
|
||||
baseline_rows = fixed_valid
|
||||
baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ())
|
||||
else:
|
||||
return RuntimeParseStrategy(
|
||||
'needs_review', page_nos, None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',),
|
||||
)
|
||||
if baseline is None and dynamic_valid:
|
||||
return RuntimeParseStrategy(
|
||||
'selected', page_nos, 'dynamic_x_columns',
|
||||
('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',),
|
||||
)
|
||||
if baseline is not None and dynamic_valid:
|
||||
relation = _compare_dynamic_row_coverage(
|
||||
baseline_rows=baseline_rows, dynamic_rows=dynamic_valid,
|
||||
)
|
||||
if relation == 'dynamic_preferred':
|
||||
return RuntimeParseStrategy(
|
||||
'selected', page_nos, 'dynamic_x_columns',
|
||||
('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',),
|
||||
)
|
||||
if relation == 'ambiguous':
|
||||
return RuntimeParseStrategy(
|
||||
'needs_review', page_nos, None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',),
|
||||
)
|
||||
if baseline is not None:
|
||||
return baseline
|
||||
return RuntimeParseStrategy(
|
||||
'needs_review', page_nos, None, ('PARSE_STRATEGY_NO_VALID_ROW_RECONSTRUCTION',),
|
||||
)
|
||||
|
||||
|
||||
def select_runtime_region_ids(*, table_regions: list[dict[str, Any]], page_no: int) -> tuple[str, ...]:
|
||||
"""为当前页选择候选表区,专属页优先,续页才回退到稳定基础表区。
|
||||
|
||||
历史 ``page_scope`` 仅描述样本标注页,不能要求管理员预判每份文件的续页。
|
||||
当前页已有专属表区时只使用它;没有时复用首页/通用表区,后续仍由行重建结果
|
||||
决定是否确实存在明细,避免把页面范围配置变成自动建单依据。
|
||||
"""
|
||||
if page_no < 1:
|
||||
return ()
|
||||
valid_regions = [
|
||||
region for region in table_regions
|
||||
if isinstance(region, dict) and str(region.get('region_id') or '')
|
||||
]
|
||||
exact = tuple(
|
||||
str(region['region_id']) for region in valid_regions
|
||||
if region.get('page_scope') == 'exact_page' and region.get('page_no') == page_no
|
||||
)
|
||||
if exact:
|
||||
return exact
|
||||
first_page = tuple(
|
||||
str(region['region_id']) for region in valid_regions
|
||||
if region.get('page_scope') == 'first_page'
|
||||
)
|
||||
if page_no == 1 and first_page:
|
||||
return first_page
|
||||
continuation = tuple(
|
||||
str(region['region_id']) for region in valid_regions
|
||||
if page_no > 1 and region.get('page_scope') == 'continuation_pages'
|
||||
)
|
||||
if continuation:
|
||||
return continuation
|
||||
all_pages = tuple(
|
||||
str(region['region_id']) for region in valid_regions
|
||||
if region.get('page_scope') == 'all_pages'
|
||||
)
|
||||
if all_pages:
|
||||
return all_pages
|
||||
if first_page:
|
||||
return first_page
|
||||
return tuple(
|
||||
str(region['region_id']) for region in valid_regions
|
||||
if region.get('page_scope') == 'exact_page' and region.get('page_no') == 1
|
||||
)
|
||||
|
||||
|
||||
def _valid_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""只接受无 issue 的已解析行;不将预览或待复核候选当作可自动建单事实。"""
|
||||
return [
|
||||
row for row in rows
|
||||
if isinstance(row, dict) and row.get('status') == 'parsed' and not row.get('issues')
|
||||
]
|
||||
|
||||
|
||||
def _business_row_identity(rows: list[dict[str, Any]]) -> tuple[tuple[tuple[str, str], ...], ...]:
|
||||
"""比较两种重建的完整业务字段,缺值也保留以避免静默视作相同。"""
|
||||
result: list[tuple[tuple[str, str], ...]] = []
|
||||
for row in rows:
|
||||
values = [
|
||||
(str(field.get('field_code') or ''), str(field.get('value') or ''))
|
||||
for field in row.get('fields') or [] if isinstance(field, dict)
|
||||
]
|
||||
result.append(tuple(sorted(values)))
|
||||
return tuple(result)
|
||||
|
||||
|
||||
def _compare_row_field_completeness(
|
||||
fixed_rows: list[dict[str, Any]], adaptive_rows: list[dict[str, Any]],
|
||||
) -> Literal['fixed_preferred', 'adaptive_preferred', 'same', 'ambiguous']:
|
||||
"""比较两种重建的字段集合,允许一方仅缺失字段而不丢弃整条明细。
|
||||
|
||||
只有对应行数量相同、重叠字段值一致,且所有行都呈现同一方向的字段超集关系时,
|
||||
才自动选择更完整的结果;任一字段值冲突或方向不一致都继续进入 Review。
|
||||
"""
|
||||
if len(fixed_rows) != len(adaptive_rows):
|
||||
return 'ambiguous'
|
||||
directions: set[str] = set()
|
||||
for fixed, adaptive in zip(fixed_rows, adaptive_rows):
|
||||
fixed_fields = _row_fields(fixed)
|
||||
adaptive_fields = _row_fields(adaptive)
|
||||
shared = fixed_fields.keys() & adaptive_fields.keys()
|
||||
conflicts = [code for code in shared if fixed_fields[code] != adaptive_fields[code]]
|
||||
if conflicts:
|
||||
# 坐标字段框是模板的权威边界。若 adaptive 只读到 fixed 值的
|
||||
# 前缀(典型的跨视觉行料号),完整的 fixed 值应胜出;真正的
|
||||
# 不同业务值仍保持 Review,避免把冲突静默吞掉。
|
||||
if all(
|
||||
fixed_fields[code].startswith(adaptive_fields[code])
|
||||
and len(fixed_fields[code]) > len(adaptive_fields[code])
|
||||
for code in conflicts
|
||||
):
|
||||
directions.add('fixed')
|
||||
else:
|
||||
return 'ambiguous'
|
||||
if fixed_fields.keys() > adaptive_fields.keys():
|
||||
directions.add('fixed')
|
||||
elif adaptive_fields.keys() > fixed_fields.keys():
|
||||
directions.add('adaptive')
|
||||
if not directions:
|
||||
return 'same'
|
||||
if len(directions) == 1:
|
||||
return 'fixed_preferred' if 'fixed' in directions else 'adaptive_preferred'
|
||||
return 'ambiguous'
|
||||
|
||||
|
||||
def _compare_dynamic_row_coverage(
|
||||
*, baseline_rows: list[dict[str, Any]], dynamic_rows: list[dict[str, Any]],
|
||||
) -> Literal['baseline_preferred', 'dynamic_preferred', 'ambiguous']:
|
||||
"""仅当动态结果无冲突地覆盖基线每条记录并额外恢复记录时才切换策略。"""
|
||||
if len(dynamic_rows) < len(baseline_rows):
|
||||
return 'baseline_preferred'
|
||||
remaining = [_row_fields(row) for row in dynamic_rows]
|
||||
for baseline in baseline_rows:
|
||||
baseline_fields = _row_fields(baseline)
|
||||
matches = []
|
||||
for index, dynamic_fields in enumerate(remaining):
|
||||
if not baseline_fields.keys() <= dynamic_fields.keys():
|
||||
continue
|
||||
if all(
|
||||
dynamic_fields[code] == value
|
||||
or (
|
||||
dynamic_fields[code].startswith(value)
|
||||
and len(dynamic_fields[code]) > len(value)
|
||||
)
|
||||
for code, value in baseline_fields.items()
|
||||
):
|
||||
matches.append(index)
|
||||
if len(matches) != 1:
|
||||
return 'ambiguous' if len(dynamic_rows) >= len(baseline_rows) else 'baseline_preferred'
|
||||
remaining.pop(matches[0])
|
||||
return 'dynamic_preferred' if remaining else 'baseline_preferred'
|
||||
|
||||
|
||||
def _row_fields(row: dict[str, Any]) -> dict[str, str]:
|
||||
"""将策略行字段规整为可比较映射;不引入业务字段白名单。"""
|
||||
return {
|
||||
str(field.get('field_code') or ''): str(field.get('value') or '')
|
||||
for field in row.get('fields') or []
|
||||
if isinstance(field, dict) and str(field.get('field_code') or '')
|
||||
}
|
||||
@@ -1,342 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/source_merge_service.py
|
||||
|
||||
用途:Q18 抽取层裁决——同一 conflict_group_key(scope/field_code/line_no)下的三来源候选
|
||||
合并为最多一条「有效业务 Observation」,禁止同一 scope+line 下多个并列有效
|
||||
Observation(防止 compute_effective_reservation_id / 库存匹配 / 履约门禁
|
||||
/ Excel/RPA 误取其中一个,或冲突被后续静默覆盖)。
|
||||
依赖:profile_field_source_mapping_service.FieldSourceCandidate。
|
||||
逻辑:严格三步骤(同值合并 → 空值互补 → 值冲突),满足:
|
||||
① merge 后只出一个有效 accepted(或 needs_review=无 accepted);
|
||||
② 始终保留 source_observations[] 事实快照放入 metadata;
|
||||
③ annotation_only / invalid_line_reference 的候选永不成为 accepted,
|
||||
只保留在 conflict_payload 里作为 Review 证据。
|
||||
输出:MergedObservationCandidate(直接落库前的 Observation 形状封装),
|
||||
由 runtime 层实际 SQLAlchemy insert。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Literal
|
||||
|
||||
from app.services.shipping_notice.document_layout.profile_field_source_mapping_service import (
|
||||
FieldSourceCandidate,
|
||||
)
|
||||
|
||||
|
||||
SourceResolution = Literal[
|
||||
'same_value_merged', # 多个来源值一致
|
||||
'fill_missing', # 一个来源有值,另一来源为空 → 自动填补
|
||||
'needs_review', # 同 scope+line 多来源值不一致
|
||||
'no_value', # 所有来源均为空 → 本冲突组不生成有效 Observation
|
||||
'single_source_direct', # 只有一个来源有值,直接落 Observation
|
||||
'annotation_only_dropped', # 候选全是 annotation_only / invalid_line_reference
|
||||
]
|
||||
|
||||
|
||||
@dataclass
|
||||
class SourceObservationSnapshot:
|
||||
"""source_observations[] 事实快照——Observation.metadata 直接序列化。"""
|
||||
|
||||
source: Literal['header_region', 'table_column', 'vendor_comments']
|
||||
value: str
|
||||
normalized_value: str
|
||||
evidence_ref: str | None
|
||||
evidence_quote: str | None
|
||||
line_no_in_source: int | None
|
||||
format_valid: bool | None
|
||||
format_reason_code: str | None
|
||||
extra: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
class MergedObservationCandidate:
|
||||
"""
|
||||
合并后候选——最多一份(per conflict_group_key),由 runtime 层写数据库。
|
||||
|
||||
【后端决定 UI】:accepted_value 为 None 时,说明该字段+行=必须 Review;
|
||||
frontend 不能以『第一个 source value』为事实,必须展示 source_observations[]。
|
||||
"""
|
||||
|
||||
target_scope: Literal['header', 'line']
|
||||
target_field_code: str
|
||||
target_field_id: str
|
||||
effective_line_no: int | None
|
||||
accepted_value: str | None # needs_review/no_value 时为 None
|
||||
decision_status: Literal['accepted', 'needs_review', 'blocked', 'missing']
|
||||
resolution: SourceResolution
|
||||
source_observations: list[SourceObservationSnapshot] = field(default_factory=list)
|
||||
conflicts: list[dict[str, Any]] = field(default_factory=list)
|
||||
# 用于直接映射到 Observation 数据库表列
|
||||
evidence_quote: str | None = None
|
||||
evidence_ref: str | None = None
|
||||
evidence_metadata: dict[str, Any] = field(default_factory=dict)
|
||||
# 用于 Observation.source_type / extractor(统一三来源来源标记)
|
||||
source_type: str = 'profile_field_source_mapping'
|
||||
extractor: str = 'merged_source_service.v1'
|
||||
|
||||
@property
|
||||
def should_persist_observation(self) -> bool:
|
||||
"""
|
||||
有效 Observation 生成门禁:
|
||||
必须有 accepted_value;annotation_only/invalid 全 drop 时也不输出。
|
||||
"""
|
||||
return self.accepted_value is not None and self.accepted_value != ''
|
||||
|
||||
|
||||
class SourceMergeService:
|
||||
"""
|
||||
Q18 抽取层裁决服务(先对账再重试——三来源先对账)。
|
||||
|
||||
【AI 触发时机】:ProfileFieldSourceMappingService.collect_candidates() 返回候选后,
|
||||
下一个函数调用必须是 merge_and_decide()。禁止上游在合并前直接挑一个 source 作为 Observation。
|
||||
|
||||
执行顺序(同 conflict_group_key 内):
|
||||
[STEP 1] 过滤 annotation_only / invalid_line_reference 候选(永不 accepted)。
|
||||
[STEP 2] 归一化所有来源 value(去空格、大小写、格式化残差)。
|
||||
[STEP 3] 同值合并 same_value_merged → accepted
|
||||
[STEP 4] 空值互补 fill_missing(需 mapping.fill_missing_from_other_sources=True)
|
||||
[STEP 5] 以上都不通过 → conflict_needs_review,accepted_value=None
|
||||
"""
|
||||
|
||||
def __init__(self, candidates: list[FieldSourceCandidate]):
|
||||
self.candidates = list(candidates)
|
||||
# 分组:(scope, field_code, line_no) → list[candidates]
|
||||
self._groups: dict[tuple[Any, ...], list[FieldSourceCandidate]] = defaultdict(list)
|
||||
for cand in self.candidates:
|
||||
self._groups[cand.conflict_group_key].append(cand)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 对外主入口
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def merge_and_decide(self) -> list[MergedObservationCandidate]:
|
||||
"""为每个 conflict_group_key 输出 0 或 1 个 MergedObservationCandidate。"""
|
||||
merged: list[MergedObservationCandidate] = []
|
||||
for _key, group in self._groups.items():
|
||||
merged.append(self._merge_one_group(group))
|
||||
return merged
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 单组合并核心
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _merge_one_group(self, group: list[FieldSourceCandidate]) -> MergedObservationCandidate:
|
||||
first = group[0]
|
||||
result = MergedObservationCandidate(
|
||||
target_scope=first.target_scope,
|
||||
target_field_code=first.target_field_code,
|
||||
target_field_id=first.target_field_id,
|
||||
effective_line_no=first.effective_line_no,
|
||||
accepted_value=None,
|
||||
decision_status='missing',
|
||||
resolution='no_value',
|
||||
)
|
||||
|
||||
# [STEP 1] 分离有效候选(排除 annotation_only / invalid)
|
||||
qualified: list[FieldSourceCandidate] = []
|
||||
for cand in group:
|
||||
snap = self._to_snapshot(cand)
|
||||
result.source_observations.append(snap)
|
||||
if cand.resolution_hint == 'provisional':
|
||||
qualified.append(cand)
|
||||
else:
|
||||
# annotation_only / invalid_line_reference 作为 review 证据保留
|
||||
result.conflicts.append({
|
||||
'resolution_hint': cand.resolution_hint,
|
||||
'source': cand.source,
|
||||
'value': cand.normalized_value or cand.value,
|
||||
'reason': (
|
||||
cand.format_reason_code
|
||||
or cand.relation_projection.resolution
|
||||
if cand.relation_projection else 'annotation_only'
|
||||
),
|
||||
})
|
||||
|
||||
# 无 qualified → 直接 annotation_only_dropped / no_value
|
||||
if not qualified:
|
||||
if group:
|
||||
result.resolution = 'annotation_only_dropped'
|
||||
result.decision_status = 'blocked'
|
||||
else:
|
||||
result.resolution = 'no_value'
|
||||
result.decision_status = 'missing'
|
||||
result.evidence_metadata = self._finalize_metadata(result, resolution_meta={})
|
||||
return result
|
||||
|
||||
# 只有一个 qualified 且非空 → single_source_direct
|
||||
non_empty = [c for c in qualified if (c.normalized_value or c.value) != '']
|
||||
if len(qualified) == 1 and non_empty:
|
||||
return self._finalize_single(result, qualified[0])
|
||||
if not non_empty:
|
||||
result.resolution = 'no_value'
|
||||
result.decision_status = 'missing'
|
||||
result.evidence_metadata = self._finalize_metadata(result, {})
|
||||
return result
|
||||
if len(non_empty) == 1:
|
||||
return self._finalize_fill_missing(result, group, non_empty[0], qualified)
|
||||
|
||||
# [STEP 3] 同值合并 same_value_merged
|
||||
values = {(c.normalized_value or c.value) for c in non_empty}
|
||||
if len(values) == 1:
|
||||
return self._finalize_same_value(result, group, next(iter(values)))
|
||||
|
||||
# [STEP 5] 冲突 → needs_review(多来源值不一致)
|
||||
result.resolution = 'needs_review'
|
||||
result.decision_status = 'needs_review'
|
||||
result.accepted_value = None
|
||||
for c in non_empty:
|
||||
result.conflicts.append({
|
||||
'source': c.source,
|
||||
'value': (c.normalized_value or c.value),
|
||||
'evidence_ref': c.evidence_ref,
|
||||
'format_valid': c.format_valid,
|
||||
})
|
||||
result.evidence_metadata = self._finalize_metadata(result, {})
|
||||
return result
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 结局封装(保证 evidence_metadata 统一包含 source_observations / resolution)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _finalize_single(
|
||||
self, result: MergedObservationCandidate, cand: FieldSourceCandidate,
|
||||
) -> MergedObservationCandidate:
|
||||
result.accepted_value = cand.normalized_value or cand.value
|
||||
result.resolution = 'single_source_direct'
|
||||
result.decision_status = 'accepted'
|
||||
result.evidence_quote = cand.evidence_quote
|
||||
result.evidence_ref = cand.evidence_ref
|
||||
result.evidence_metadata = self._finalize_metadata(
|
||||
result,
|
||||
resolution_meta={
|
||||
'accepted_source': cand.source,
|
||||
'format_valid': cand.format_valid,
|
||||
'format_reason_code': cand.format_reason_code,
|
||||
},
|
||||
primary_candidate=cand,
|
||||
)
|
||||
return result
|
||||
|
||||
def _finalize_fill_missing(
|
||||
self, result: MergedObservationCandidate,
|
||||
group: list[FieldSourceCandidate],
|
||||
winner: FieldSourceCandidate,
|
||||
all_qualified: list[FieldSourceCandidate],
|
||||
) -> MergedObservationCandidate:
|
||||
result.accepted_value = winner.normalized_value or winner.value
|
||||
result.resolution = 'fill_missing'
|
||||
result.decision_status = 'accepted'
|
||||
result.evidence_quote = winner.evidence_quote
|
||||
result.evidence_ref = winner.evidence_ref
|
||||
missing = [
|
||||
{'source': c.source, 'reason': 'empty_source'}
|
||||
for c in all_qualified
|
||||
if (c.normalized_value or c.value) == ''
|
||||
]
|
||||
result.evidence_metadata = self._finalize_metadata(
|
||||
result,
|
||||
resolution_meta={
|
||||
'accepted_source': winner.source,
|
||||
'missing_sources': missing,
|
||||
'format_valid': winner.format_valid,
|
||||
'format_reason_code': winner.format_reason_code,
|
||||
},
|
||||
primary_candidate=winner,
|
||||
)
|
||||
return result
|
||||
|
||||
def _finalize_same_value(
|
||||
self, result: MergedObservationCandidate,
|
||||
group: list[FieldSourceCandidate], shared_value: str,
|
||||
) -> MergedObservationCandidate:
|
||||
# 多来源同值:evidence 选 format_valid=True 中来源排序靠前的
|
||||
# (vendor_comments 优先,因为有人工圈选证据点位更清晰)
|
||||
source_priority = ['vendor_comments', 'table_column', 'header_region']
|
||||
ordered = sorted(
|
||||
group,
|
||||
key=lambda c: (
|
||||
0 if (c.format_valid is not False and (c.normalized_value or c.value) == shared_value) else 1,
|
||||
source_priority.index(c.source) if c.source in source_priority else 99,
|
||||
),
|
||||
)
|
||||
primary = ordered[0]
|
||||
result.accepted_value = shared_value
|
||||
result.resolution = 'same_value_merged'
|
||||
result.decision_status = 'accepted'
|
||||
result.evidence_quote = primary.evidence_quote
|
||||
result.evidence_ref = primary.evidence_ref
|
||||
merged_sources = sorted({c.source for c in ordered if (c.normalized_value or c.value) == shared_value})
|
||||
result.evidence_metadata = self._finalize_metadata(
|
||||
result,
|
||||
resolution_meta={
|
||||
'merged_from_sources': list(merged_sources),
|
||||
'format_valid': primary.format_valid,
|
||||
'format_reason_code': primary.format_reason_code,
|
||||
},
|
||||
primary_candidate=primary,
|
||||
)
|
||||
return result
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 帮助函数
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _to_snapshot(cand: FieldSourceCandidate) -> SourceObservationSnapshot:
|
||||
return SourceObservationSnapshot(
|
||||
source=cand.source,
|
||||
value=cand.value,
|
||||
normalized_value=cand.normalized_value,
|
||||
evidence_ref=cand.evidence_ref,
|
||||
evidence_quote=cand.evidence_quote,
|
||||
line_no_in_source=cand.effective_line_no,
|
||||
format_valid=cand.format_valid,
|
||||
format_reason_code=cand.format_reason_code,
|
||||
extra=dict(cand.evidence_metadata or {}),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _finalize_metadata(
|
||||
result: MergedObservationCandidate,
|
||||
resolution_meta: dict[str, Any],
|
||||
primary_candidate: FieldSourceCandidate | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
组装 Observation.evidence_metadata_json 最终结构(Q18 冻结形状):
|
||||
{
|
||||
"source_observations": [...], // 事实快照(永不丢)
|
||||
"resolution": "same_value_merged",
|
||||
"accepted_value": "...",
|
||||
"conflicts": [ ... ], // 冲突或 annotation_only 项
|
||||
"resolution_meta": { ... }, // 来源细节
|
||||
"primary": { // 选主证据说明
|
||||
"source": "vendor_comments", "evidence_ref": "...", "line_no": 2
|
||||
}
|
||||
}
|
||||
"""
|
||||
payload: dict[str, Any] = {
|
||||
'source_observations': [
|
||||
{
|
||||
'source': s.source, 'value': s.value,
|
||||
'normalized_value': s.normalized_value,
|
||||
'evidence_ref': s.evidence_ref, 'evidence_quote': s.evidence_quote,
|
||||
'line_no_in_source': s.line_no_in_source,
|
||||
'format_valid': s.format_valid, 'format_reason_code': s.format_reason_code,
|
||||
'extra': s.extra or {},
|
||||
} for s in result.source_observations
|
||||
],
|
||||
'resolution': result.resolution,
|
||||
'accepted_value': result.accepted_value,
|
||||
'conflicts': list(result.conflicts or []),
|
||||
'resolution_meta': resolution_meta or {},
|
||||
}
|
||||
if primary_candidate is not None:
|
||||
payload['primary'] = {
|
||||
'source': primary_candidate.source,
|
||||
'evidence_ref': primary_candidate.evidence_ref,
|
||||
'line_no': primary_candidate.effective_line_no,
|
||||
}
|
||||
return payload
|
||||
-195
@@ -1,195 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/vc_source_candidate_conflicts.py
|
||||
|
||||
用途:从 ProfileFieldSourceMappingService + SourceMergeService 的运行结果
|
||||
产出 Candidate 级冲突项,接入 candidate.conflicts_json。
|
||||
依赖:
|
||||
- vc_source_gate_contract(冲突原因码、冲突项构造器)。
|
||||
- profile_field_source_mapping_service(三来源候选收集)。
|
||||
- source_merge_service(合并裁决 + needs_review 标记)。
|
||||
- candidate_service / ShippingOrderCandidate.structured_result_json(落库载体)。
|
||||
逻辑:
|
||||
[STEP 1] 从 Candidate.structured_result_json 读三来源收集的原始快照;
|
||||
缺失(旧数据或未启用 VC Profile)时安全返回空列表,不阻断。
|
||||
[STEP 2] 扫描 merged_candidates,needs_review 且 conflict_group_key 未人工裁决 →
|
||||
构造 make_vc_candidate_conflict_item(severity=review_required)。
|
||||
[STEP 3] 扫描 format_valid=False 且 format_policy.inherit_global=False 的项 →
|
||||
独立原因码 vc_source_format_invalid,severity=blocking。
|
||||
[STEP 4] named_region_id 指向不存在区域 → vc_source_region_unbound。
|
||||
幂等:同一 conflict_group_key 仅保留一项,合并 detail 不重复追加。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.vc_source_gate_contract import (
|
||||
CQ_REASON_VC_FORMAT_INVALID,
|
||||
CQ_REASON_VC_REGION_UNBOUND,
|
||||
CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED,
|
||||
CQ_VC_BLOCKING_REASONS,
|
||||
CQ_VC_REVIEW_REASONS,
|
||||
VC_SOURCE_KIND_LABELS,
|
||||
make_vc_candidate_conflict_item,
|
||||
)
|
||||
|
||||
# CQ_VC_BLOCKING_REASONS / CQ_VC_REVIEW_REASONS 定义在 vc_source_gate_contract.py(契约层),
|
||||
# 这里保留薄 re-export,供 candidate_qualification_service 等调用方按旧路径 import,
|
||||
# 避免修改大量调用点时引入遗漏。
|
||||
|
||||
|
||||
_VC_CANDIDATE_KEY = 'vendor_comments_merged'
|
||||
_VC_DETAIL_MAX = 8 # 单项 detail 保留最多 8 条来源快照,防止 JSON 膨胀。
|
||||
|
||||
|
||||
def _vc_merged_payload(candidate: Any) -> dict[str, Any] | None:
|
||||
"""
|
||||
从 Candidate 提取 Vendor Comments merged payload。
|
||||
|
||||
支持三条路径,按顺序:
|
||||
1) structured_result_json.extraction.vendor_comments_merged(新抽取路径)
|
||||
2) result_json.extraction.vendor_comments_merged(兼容 Worker 旧写入点)
|
||||
3) candidate_json.extraction.vendor_comments_merged(影子评估的替身 dict)
|
||||
|
||||
任一合法 dict 即返回,否则 None(缺路径视为未启用,安全放行)。
|
||||
"""
|
||||
for attr in ('structured_result_json', 'result_json', 'candidate_json'):
|
||||
try:
|
||||
raw = getattr(candidate, attr, None)
|
||||
except Exception:
|
||||
raw = None
|
||||
if isinstance(raw, dict):
|
||||
ext = raw.get('extraction') if isinstance(raw.get('extraction'), dict) else None
|
||||
if ext and isinstance(ext.get(_VC_CANDIDATE_KEY), dict):
|
||||
return ext[_VC_CANDIDATE_KEY]
|
||||
return None
|
||||
|
||||
|
||||
def _conflict_group_key(scope: str, field_code: str, line_no: str | None) -> str:
|
||||
"""稳定冲突键:与 source_merge_service 的 (scope, field_code, line_no) 一致。"""
|
||||
safe_scope = 'header' if scope == 'header' else 'line'
|
||||
safe_line = str(line_no or '').strip() or '_'
|
||||
return f'{safe_scope}:{str(field_code or "").strip()}:{safe_line}'
|
||||
|
||||
|
||||
def _summarize_source_observations(cand: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
脱敏压缩 source_observations:仅保留 source / value 摘要 / evidence_ref,禁止存完整正文。
|
||||
"""
|
||||
obs = cand.get('source_observations') if isinstance(cand.get('source_observations'), list) else []
|
||||
summary: list[dict[str, Any]] = []
|
||||
for raw in obs[:_VC_DETAIL_MAX]:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
summary.append({
|
||||
'source': raw.get('source'),
|
||||
'source_label': VC_SOURCE_KIND_LABELS.get(str(raw.get('source') or ''), str(raw.get('source') or '')),
|
||||
'value_preview': (str(raw.get('value') or '')[:64] + ('…' if len(str(raw.get('value') or '')) > 64 else '')) if raw.get('value') is not None else None,
|
||||
'evidence_ref': raw.get('evidence_ref'),
|
||||
})
|
||||
return summary
|
||||
|
||||
|
||||
def collect_vc_candidate_conflicts(candidate: Any) -> list[dict[str, Any]]:
|
||||
"""
|
||||
扫描 Vendor Comments 三来源合并结果,生成 Candidate 冲突项。
|
||||
|
||||
【AI 触发时机】:当 Candidate Qualification 评估、STP 自动建单前
|
||||
或复核工作台加载冲突列表时,追加本函数返回值到 Candidate.conflicts_json。
|
||||
|
||||
Args:
|
||||
candidate: ShippingOrderCandidate ORM 对象或兼容 dict(替身)。
|
||||
|
||||
Returns:
|
||||
符合 vc_source_gate_contract.make_vc_candidate_conflict_item 契约的列表;
|
||||
无冲突或未启用 VC 时返回空列表(永不返回 None)。
|
||||
"""
|
||||
payload = _vc_merged_payload(candidate)
|
||||
if payload is None:
|
||||
return []
|
||||
|
||||
merged = payload.get('merged_candidates') if isinstance(payload.get('merged_candidates'), list) else []
|
||||
named_regions = payload.get('named_regions') if isinstance(payload.get('named_regions'), dict) else {}
|
||||
enabled = payload.get('field_source_mappings') if isinstance(payload.get('field_source_mappings'), dict) else {}
|
||||
|
||||
# [STEP 0] 先校验 named_region 绑定:所有启用 vendor_comments 的 mapping 其 region_id 必须存在。
|
||||
seen_region_errors: set[str] = set()
|
||||
items: list[dict[str, Any]] = []
|
||||
|
||||
for field_code, mapping in enabled.items():
|
||||
if not isinstance(mapping, dict):
|
||||
continue
|
||||
if not bool(mapping.get('vendor_comments_enabled')):
|
||||
continue
|
||||
rid = str(mapping.get('vendor_comments_named_region_id') or '').strip()
|
||||
if rid and rid not in named_regions:
|
||||
key = f'region_missing:{rid}:{field_code}'
|
||||
if key in seen_region_errors:
|
||||
continue
|
||||
seen_region_errors.add(key)
|
||||
scope_val = str(mapping.get('vendor_comments_target_scope') or mapping.get('target_scope') or 'line').strip()
|
||||
scope = 'header' if scope_val == 'header' else 'line'
|
||||
ckey = _conflict_group_key(scope, field_code, None)
|
||||
items.append(make_vc_candidate_conflict_item(
|
||||
reason=CQ_REASON_VC_REGION_UNBOUND,
|
||||
scope=scope, # type: ignore[arg-type]
|
||||
field_code=field_code,
|
||||
conflict_group_key=ckey,
|
||||
detail={'missing_region_id': rid},
|
||||
))
|
||||
|
||||
# [STEP 1] 扫描 merged_candidates:needs_review / format_invalid。
|
||||
seen_groups: set[str] = set()
|
||||
for cand in merged:
|
||||
if not isinstance(cand, dict):
|
||||
continue
|
||||
field_code = str(cand.get('target_field_code') or cand.get('field_code') or '').strip()
|
||||
if not field_code:
|
||||
continue
|
||||
scope = str(cand.get('target_scope') or cand.get('scope') or 'line').strip()
|
||||
scope_ok = 'header' if scope == 'header' else 'line'
|
||||
line_no_raw = cand.get('effective_line_no') or cand.get('line_no')
|
||||
line_no_safe = None if line_no_raw is None else str(line_no_raw)
|
||||
ckey = _conflict_group_key(scope_ok, field_code, line_no_safe)
|
||||
|
||||
resolution = str(cand.get('resolution') or '').strip()
|
||||
decision = str(cand.get('decision_status') or '').strip()
|
||||
format_valid = cand.get('format_valid')
|
||||
# 显式 False 视为非法(None 表示未启用格式策略,安全放行)。
|
||||
format_invalid = (format_valid is False)
|
||||
conflict_pending = resolution == 'needs_review' and decision != 'dropped'
|
||||
|
||||
if ckey in seen_groups:
|
||||
continue
|
||||
detail = {
|
||||
'resolution': resolution,
|
||||
'decision_status': decision,
|
||||
'format_valid': format_valid,
|
||||
'sources': _summarize_source_observations(cand),
|
||||
}
|
||||
if conflict_pending:
|
||||
seen_groups.add(ckey)
|
||||
line_key = str(cand.get('line_key') or '').strip() or None
|
||||
items.append(make_vc_candidate_conflict_item(
|
||||
reason=CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED,
|
||||
scope=scope_ok, # type: ignore[arg-type]
|
||||
field_code=field_code,
|
||||
line_key=line_key,
|
||||
line_no=line_no_safe,
|
||||
conflict_group_key=ckey,
|
||||
detail=detail,
|
||||
))
|
||||
elif format_invalid:
|
||||
seen_groups.add(ckey)
|
||||
line_key = str(cand.get('line_key') or '').strip() or None
|
||||
items.append(make_vc_candidate_conflict_item(
|
||||
reason=CQ_REASON_VC_FORMAT_INVALID,
|
||||
scope=scope_ok, # type: ignore[arg-type]
|
||||
field_code=field_code,
|
||||
line_key=line_key,
|
||||
line_no=line_no_safe,
|
||||
conflict_group_key=ckey,
|
||||
detail=detail,
|
||||
))
|
||||
|
||||
return items
|
||||
-230
@@ -1,230 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/vc_source_evidence_integration.py
|
||||
|
||||
用途:将 Vendor Comments 三来源 source_observations 注入 ReviewEvidenceView,
|
||||
供 Chatflow LLM Review(Phase 4)与复核工作台(Phase 5)共享同一事实源。
|
||||
依赖:
|
||||
- vc_source_gate_contract(VENDOR_COMMENTS_OBSERVATION_SOURCE、build_vc_evidence_ref、is_valid_vc_evidence_ref)。
|
||||
- order_review_llm_contract ObservationSource 兼容扩展(新增 source 不在原 frozenset 时 fail-open,不抛错)。
|
||||
- Candidate.structured_result_json.extraction.vendor_comments_merged(与 vc_source_candidate_conflicts.py 同一路径)。
|
||||
逻辑:
|
||||
[STEP 1] 提取 VC merged payload(与 Candidate Conflicts 共享 _vc_merged_payload 逻辑,不双份)。
|
||||
[STEP 2] 对每个 merged_candidate,展开其 source_observations[]:
|
||||
- 构造 evidence_ref(优先 vc: 区域引用,缺失时退化 build_evidence_ref layout:)。
|
||||
- source 固定 VENDOR_COMMENTS_OBSERVATION_SOURCE;子 source_kind 写入 metadata.source_kind。
|
||||
- 保留 quote(原文切片)、confidence、value_bbox。
|
||||
[STEP 3] 仅追加,不覆盖/替换原有 Unit/Draft/Frozen 三源证据。
|
||||
幂等:同一 (evidence_ref, source_kind, value) 仅插入一条,避免 LLM 重复上下文。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.vc_source_gate_contract import (
|
||||
VENDOR_COMMENTS_OBSERVATION_SOURCE,
|
||||
build_vc_evidence_ref,
|
||||
is_valid_vc_evidence_ref,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_llm_contract import (
|
||||
build_evidence_ref,
|
||||
is_valid_evidence_ref,
|
||||
)
|
||||
|
||||
|
||||
def _vc_merged_payload(case_or_candidate: Any) -> dict[str, Any] | None:
|
||||
"""
|
||||
从 ReviewCase(通过 candidate.structured)或直接 Candidate 提取 VC 载荷。
|
||||
|
||||
与 vc_source_candidate_conflicts._vc_merged_payload 逻辑一致但独立实现,
|
||||
避免引入相互 import(两模块均零 circular 原则)。
|
||||
"""
|
||||
# Case 路径:先取 candidate。
|
||||
candidate = getattr(case_or_candidate, 'candidate', None)
|
||||
attrs_chain: list[Any] = []
|
||||
if candidate is not None:
|
||||
attrs_chain.append(candidate)
|
||||
attrs_chain.append(case_or_candidate)
|
||||
for item in attrs_chain:
|
||||
for attr in ('structured_result_json', 'result_json', 'candidate_json'):
|
||||
try:
|
||||
raw = getattr(item, attr, None)
|
||||
except Exception:
|
||||
raw = None
|
||||
if isinstance(raw, dict):
|
||||
ext = raw.get('extraction') if isinstance(raw.get('extraction'), dict) else None
|
||||
if ext and isinstance(ext.get('vendor_comments_merged'), dict):
|
||||
return ext['vendor_comments_merged']
|
||||
return None
|
||||
|
||||
|
||||
def _safe_str(value: Any) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def _normalize_source_obs(
|
||||
raw: dict[str, Any],
|
||||
*,
|
||||
case_document_id: int,
|
||||
field_code: str | None,
|
||||
line_key: str | None,
|
||||
named_regions: dict[str, Any],
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
将一条 source_observation 归一化为 ReviewEvidenceView.field_evidences 项形状。
|
||||
|
||||
核心:evidence_ref 优先取 vc:region;若 source_kind=vendor_comments 且命中命名区域
|
||||
但缺 page_no,回退从 named_regions[region_id] 取代表页号。
|
||||
"""
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
source_kind = _safe_str(raw.get('source')) or 'header_region'
|
||||
value = raw.get('value')
|
||||
quote = _safe_str(raw.get('quote') or raw.get('raw_text'))
|
||||
confidence_raw = raw.get('confidence')
|
||||
try:
|
||||
confidence = float(confidence_raw) if confidence_raw is not None else None
|
||||
except (TypeError, ValueError):
|
||||
confidence = None
|
||||
|
||||
doc_raw = raw.get('document_id') or case_document_id
|
||||
try:
|
||||
doc_id = int(doc_raw)
|
||||
except (TypeError, ValueError):
|
||||
doc_id = int(case_document_id or 0)
|
||||
|
||||
page_raw = raw.get('page_no')
|
||||
try:
|
||||
page_no = int(page_raw) if page_raw is not None else None
|
||||
except (TypeError, ValueError):
|
||||
page_no = None
|
||||
|
||||
# Vendor Comments:若缺 page_no,按 named_regions[region_id].page_scope 推导代表页。
|
||||
rid = _safe_str(raw.get('region_id') or raw.get('named_region_id'))
|
||||
if source_kind == 'vendor_comments' and page_no is None and rid and isinstance(named_regions.get(rid), dict):
|
||||
region_def = named_regions[rid]
|
||||
page_scope = _safe_str(region_def.get('page_scope')) or 'first_page'
|
||||
exact = region_def.get('exact_page_no') or region_def.get('page_no')
|
||||
if page_scope == 'last_page':
|
||||
# last_page 未知实际页码时安全置 1,待后续有实际渲染页号再覆盖。
|
||||
page_no = page_no or 1
|
||||
elif page_scope == 'exact_page' and exact is not None:
|
||||
try:
|
||||
page_no = int(exact)
|
||||
except (TypeError, ValueError):
|
||||
page_no = page_no or 1
|
||||
else:
|
||||
page_no = page_no or 1
|
||||
|
||||
evidence_ref: str | None = None
|
||||
pre_ref = raw.get('evidence_ref')
|
||||
if isinstance(pre_ref, str) and (is_valid_vc_evidence_ref(pre_ref) or is_valid_evidence_ref(pre_ref)):
|
||||
evidence_ref = pre_ref.strip()
|
||||
if not evidence_ref and source_kind == 'vendor_comments' and doc_id > 0 and page_no and rid:
|
||||
evidence_ref = build_vc_evidence_ref(document_id=doc_id, page_no=page_no, region_id=rid)
|
||||
if not evidence_ref and doc_id > 0 and page_no:
|
||||
table_id = raw.get('table_id') if isinstance(raw.get('table_id'), str) else None
|
||||
row_index = None
|
||||
try:
|
||||
ri = raw.get('row_index')
|
||||
row_index = int(ri) if ri is not None else None
|
||||
except (TypeError, ValueError):
|
||||
row_index = None
|
||||
evidence_ref = build_evidence_ref(
|
||||
document_id=doc_id,
|
||||
page_no=page_no,
|
||||
table_id=table_id,
|
||||
row_index=row_index,
|
||||
field_code=field_code,
|
||||
)
|
||||
|
||||
bbox = raw.get('value_bbox') if isinstance(raw.get('value_bbox'), dict) else None
|
||||
bbox_valid = (
|
||||
isinstance(bbox, dict)
|
||||
and all(k in bbox for k in ('x0', 'y0', 'x1', 'y1'))
|
||||
and 0.0 <= float(bbox['x0']) < float(bbox['x1']) <= 1.01
|
||||
and 0.0 <= float(bbox['y0']) < float(bbox['y1']) <= 1.01
|
||||
) if bbox else False
|
||||
|
||||
doc_match = bool(doc_id) and int(case_document_id or 0) > 0 and int(doc_id) == int(case_document_id)
|
||||
value_bbox_dict = dict(bbox) if bbox_valid else None
|
||||
|
||||
return {
|
||||
'value': value,
|
||||
'quote': quote,
|
||||
'source': VENDOR_COMMENTS_OBSERVATION_SOURCE,
|
||||
'source_kind': source_kind,
|
||||
'confidence': confidence,
|
||||
'evidence_ref': evidence_ref,
|
||||
'provenance_ref': None, # VC 来源直接走 evidence_ref,不伪装 draft provenance。
|
||||
'document_id': doc_id,
|
||||
'page_no': page_no,
|
||||
'table_id': raw.get('table_id') if isinstance(raw.get('table_id'), str) else None,
|
||||
'cell_id': raw.get('cell_id') if isinstance(raw.get('cell_id'), str) else None,
|
||||
'row_index': None, # 行级由 line_key 外部关联,row_index 仅 layout table 使用。
|
||||
'value_bbox': value_bbox_dict,
|
||||
'value_bbox_valid': bbox_valid,
|
||||
'document_matches_case': doc_match,
|
||||
'field_code': field_code,
|
||||
'line_key': line_key,
|
||||
}
|
||||
|
||||
|
||||
def collect_vc_field_evidences(
|
||||
*,
|
||||
case_or_candidate: Any,
|
||||
case_document_id: int,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
展开 Vendor Comments 三来源 source_observations 为 ReviewEvidenceView.field_evidences 条目。
|
||||
|
||||
【AI 触发时机】:
|
||||
- Phase 4:构建 LLM 最小证据上下文时,追加三来源引用与 quote;
|
||||
- Phase 5:复核工作台加载 evidence 对照面板。
|
||||
|
||||
Args:
|
||||
case_or_candidate: ShippingOrderReviewCase 或 ShippingOrderCandidate。
|
||||
case_document_id: 当前 Case 的主文档 document_id,用于 document_matches_case。
|
||||
|
||||
Returns:
|
||||
归一化 observation 列表;未启用 VC 或路径缺数据返回空列表。
|
||||
"""
|
||||
payload = _vc_merged_payload(case_or_candidate)
|
||||
if payload is None:
|
||||
return []
|
||||
named_regions = payload.get('named_regions') if isinstance(payload.get('named_regions'), dict) else {}
|
||||
merged = payload.get('merged_candidates') if isinstance(payload.get('merged_candidates'), list) else []
|
||||
|
||||
results: list[dict[str, Any]] = []
|
||||
seen: set[tuple[str, str, str]] = set()
|
||||
for cand in merged:
|
||||
if not isinstance(cand, dict):
|
||||
continue
|
||||
field_code = _safe_str(cand.get('target_field_code') or cand.get('field_code'))
|
||||
line_key = _safe_str(cand.get('line_key'))
|
||||
source_list = cand.get('source_observations') if isinstance(cand.get('source_observations'), list) else []
|
||||
for raw in source_list:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
norm = _normalize_source_obs(
|
||||
raw,
|
||||
case_document_id=int(case_document_id or 0),
|
||||
field_code=field_code,
|
||||
line_key=line_key,
|
||||
named_regions=named_regions,
|
||||
)
|
||||
if norm is None:
|
||||
continue
|
||||
key = (
|
||||
str(norm.get('evidence_ref') or ''),
|
||||
str(norm.get('source_kind') or ''),
|
||||
str(norm.get('value') or '')[:64],
|
||||
)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
results.append(norm)
|
||||
return results
|
||||
@@ -1,204 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/vc_source_gate_contract.py
|
||||
|
||||
用途:冻结 Vendor Comments 三来源的门禁枚举、证据引用格式、冲突原因码。
|
||||
依赖:零 I/O 纯契约模块,禁止 import 业务服务,避免 circular。
|
||||
逻辑:
|
||||
- ObservationSource 新增 vendor_comments_region(与 order_review_llm_contract.py 对齐)。
|
||||
- evidence_ref 格式 vc:document_id:pN:region:<region_id> 独立校验,禁止混入 layout: 前缀。
|
||||
- CQ 门禁新增 vc_source_merged_clean;原因码分「业务冲突」「格式不合法」「区域未绑定」三类。
|
||||
- 所有常量写入 frozenset/tuple,供 gate/preview/audit 三处共享,禁止双份维护。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any, Final, Literal
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 三来源字段来源种类(与前端 vc.types.ts Section E VCFieldSourceKind 一一对应)
|
||||
# ---------------------------------------------------------------------------
|
||||
VC_SOURCE_KINDS: Final[frozenset[str]] = frozenset({
|
||||
'header_region',
|
||||
'table_column',
|
||||
'vendor_comments',
|
||||
})
|
||||
VC_SOURCE_KIND_LABELS: Final[dict[str, str]] = {
|
||||
'header_region': 'Header 区域',
|
||||
'table_column': '表身列',
|
||||
'vendor_comments': 'Vendor Comments',
|
||||
}
|
||||
VC_SOURCE_EVIDENCE_PRIORITY: Final[dict[str, int]] = {
|
||||
# 优先级越大越优先;与 source_merge_service.py 证据选择顺序对齐。
|
||||
'vendor_comments': 3,
|
||||
'table_column': 2,
|
||||
'header_region': 1,
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 扩展 ObservationSource(与 order_review_llm_contract 原 4 类互不污染)
|
||||
# ---------------------------------------------------------------------------
|
||||
VENDOR_COMMENTS_OBSERVATION_SOURCE: Final[str] = 'vendor_comments_region'
|
||||
ALL_OBSERVATION_SOURCES_WITH_VC: Final[frozenset[str]] = frozenset({
|
||||
'unit_observation',
|
||||
'draft_observation',
|
||||
'frozen_layout',
|
||||
'text_fallback',
|
||||
VENDOR_COMMENTS_OBSERVATION_SOURCE,
|
||||
})
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# VC 专用 evidence_ref:vc:<document_id>:p<page_no>:region:<region_id>
|
||||
# 缺任意段即视为无效,不伪造占位。
|
||||
# ---------------------------------------------------------------------------
|
||||
_VC_EVIDENCE_REF_RE = re.compile(
|
||||
r'^vc:(?P<doc>\d+):p(?P<page>\d+):region:(?P<region>[A-Za-z0-9_\-]{1,128})$'
|
||||
)
|
||||
|
||||
|
||||
def is_valid_vc_evidence_ref(value: Any) -> bool:
|
||||
"""
|
||||
校验 Vendor Comments evidence_ref 是否满足三段式契约。
|
||||
|
||||
【AI 触发时机】:当需要将 VC 来源写入 Observation evidence_ref、
|
||||
或 LLM 解析 quote 需要定位到命名区域时调用。
|
||||
|
||||
Args:
|
||||
value: 待校验字符串。
|
||||
|
||||
Returns:
|
||||
True 当且仅当正则命中且段值为正整数。
|
||||
"""
|
||||
if not isinstance(value, str) or not value:
|
||||
return False
|
||||
matched = _VC_EVIDENCE_REF_RE.match(value.strip())
|
||||
if not matched:
|
||||
return False
|
||||
try:
|
||||
doc = int(matched.group('doc'))
|
||||
page = int(matched.group('page'))
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
return doc > 0 and page > 0 and bool(matched.group('region'))
|
||||
|
||||
|
||||
def build_vc_evidence_ref(
|
||||
*,
|
||||
document_id: int | None,
|
||||
page_no: int | None,
|
||||
region_id: str | None,
|
||||
) -> str | None:
|
||||
"""
|
||||
按契约生成 VC evidence_ref;缺任意必需段返回 None,绝不伪造。
|
||||
|
||||
Args:
|
||||
document_id: PDF 主键,>0。
|
||||
page_no: 代表页号,>0。
|
||||
region_id: NamedRegion.region_id,非空。
|
||||
|
||||
Returns:
|
||||
合法 vc: 引用或 None。
|
||||
"""
|
||||
if not document_id or not page_no or not region_id:
|
||||
return None
|
||||
try:
|
||||
doc_i = int(document_id)
|
||||
page_i = int(page_no)
|
||||
rid = str(region_id).strip()
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if doc_i <= 0 or page_i <= 0 or not rid:
|
||||
return None
|
||||
ref = f'vc:{doc_i}:p{page_i}:region:{rid}'
|
||||
return ref if is_valid_vc_evidence_ref(ref) else None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Candidate Qualification 门禁:vc_source_merged_clean
|
||||
# ---------------------------------------------------------------------------
|
||||
CQ_GATE_VC_SOURCE_MERGED_CLEAN: Final[str] = 'vc_source_merged_clean'
|
||||
CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED: Final[str] = 'vc_source_conflict_unresolved'
|
||||
CQ_REASON_VC_FORMAT_INVALID: Final[str] = 'vc_source_format_invalid'
|
||||
CQ_REASON_VC_REGION_UNBOUND: Final[str] = 'vc_source_region_unbound'
|
||||
CQ_VC_BLOCKING_REASONS: Final[frozenset[str]] = frozenset({
|
||||
CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED,
|
||||
CQ_REASON_VC_FORMAT_INVALID,
|
||||
CQ_REASON_VC_REGION_UNBOUND,
|
||||
})
|
||||
# 归入 review_required(轻量人工确认)而非 hard-blocked 的原因。
|
||||
CQ_VC_REVIEW_REASONS: Final[frozenset[str]] = frozenset({
|
||||
CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED,
|
||||
})
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 合并决议(与 SourceMergeService.resolution 对齐,前端只读不改)
|
||||
# ---------------------------------------------------------------------------
|
||||
VC_MERGE_RESOLUTIONS: Final[frozenset[str]] = frozenset({
|
||||
'single_source_direct',
|
||||
'same_value_merged',
|
||||
'fill_missing',
|
||||
'needs_review',
|
||||
'annotation_only_dropped',
|
||||
'invalid_line_reference_dropped',
|
||||
})
|
||||
VC_DECISION_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'accepted',
|
||||
'pending',
|
||||
'dropped',
|
||||
})
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 证据元数据键(与 Q18 metadata.shape 严格一致)
|
||||
# ---------------------------------------------------------------------------
|
||||
VC_EVIDENCE_META_KEYS: Final[frozenset[str]] = frozenset({
|
||||
'source_observations',
|
||||
'resolution',
|
||||
'accepted_value',
|
||||
'conflicts',
|
||||
'resolution_meta',
|
||||
'primary',
|
||||
})
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# VC Candidate Qualification 冲突项 shape(用于 candidate.conflicts_json 列表项)
|
||||
# ---------------------------------------------------------------------------
|
||||
def make_vc_candidate_conflict_item(
|
||||
*,
|
||||
reason: str,
|
||||
scope: Literal['header', 'line'],
|
||||
field_code: str,
|
||||
line_key: str | None = None,
|
||||
line_no: str | None = None,
|
||||
conflict_group_key: str,
|
||||
detail: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构造符合 CQ 契约的 Vendor Comments 冲突项。
|
||||
|
||||
核心逻辑:reason 必须来自 CQ_VC_BLOCKING_REASONS;
|
||||
conflict_group_key 用于幂等去重(同组多次评估只记一条)。
|
||||
|
||||
Args:
|
||||
reason: 原因码,限 CQ_VC_BLOCKING_REASONS。
|
||||
scope: header / line。
|
||||
field_code: 订单字段,如 reservation_id。
|
||||
line_key: line scope 时的逻辑行键,header 为 None。
|
||||
line_no: 原始明细号字符串,便于审计。
|
||||
conflict_group_key: (scope, field_code, line_no) 稳定键。
|
||||
detail: 三来源 values / source_observations 快照,不含正文大对象。
|
||||
|
||||
Returns:
|
||||
candidate.conflicts_json 列表中的一项字典。
|
||||
"""
|
||||
safe_reason = reason if reason in CQ_VC_BLOCKING_REASONS else CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED
|
||||
return {
|
||||
'kind': 'vc_source',
|
||||
'reason': safe_reason,
|
||||
'severity': 'review_required' if safe_reason in CQ_VC_REVIEW_REASONS else 'blocking',
|
||||
'scope': scope,
|
||||
'field_code': field_code,
|
||||
'line_key': line_key,
|
||||
'line_no': line_no,
|
||||
'conflict_group_key': conflict_group_key,
|
||||
'detail': dict(detail or {}),
|
||||
}
|
||||
@@ -63,6 +63,7 @@ XFA_SPLIT_UNMATCHED_PRIORITY: Final[int] = 3
|
||||
|
||||
XfaSplitHandling = Literal['mapped', 'evidence_only']
|
||||
XfaSplitMatcherType = Literal['position', 'prefix', 'regex']
|
||||
XfaSplitPostProcessorType = Literal['prefix']
|
||||
XfaSplitSourceScope = Literal['header', 'line']
|
||||
XfaSplitUnmatchedPolicy = Literal['evidence_only', 'needs_review']
|
||||
XfaSplitDuplicatePolicy = Literal['needs_review']
|
||||
@@ -170,6 +171,28 @@ class XfaSplitSegment(BaseSplitSegment):
|
||||
return self
|
||||
|
||||
|
||||
class XfaSplitPostProcessor(XfaContractModel):
|
||||
"""位置/正则命中后的受限二次取值器,当前仅支持从标签后提取值。"""
|
||||
|
||||
type: XfaSplitPostProcessorType
|
||||
value: str = Field(min_length=1, max_length=XFA_SPLIT_MAX_PREFIX_LENGTH)
|
||||
separators: list[str] = Field(default_factory=lambda: [':', ':'])
|
||||
case_sensitive: bool = False
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_prefix_shape(self) -> 'XfaSplitPostProcessor':
|
||||
"""标签和分隔符均为受限静态文本,避免引入脚本式 pipeline。"""
|
||||
value = str(self.value or '').strip()
|
||||
separators = [str(item) for item in (self.separators or []) if str(item)]
|
||||
if not value:
|
||||
raise ValueError('prefix post processor requires non-empty value')
|
||||
if not separators:
|
||||
raise ValueError('prefix post processor requires at least one separator')
|
||||
object.__setattr__(self, 'value', value)
|
||||
object.__setattr__(self, 'separators', separators)
|
||||
return self
|
||||
|
||||
|
||||
class XfaSplitMatcher(BaseSplitMatcher):
|
||||
"""
|
||||
单行匹配器:position / prefix / regex。
|
||||
@@ -185,6 +208,7 @@ class XfaSplitMatcher(BaseSplitMatcher):
|
||||
case_sensitive: bool = False
|
||||
pattern: str | None = Field(default=None, max_length=XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH)
|
||||
capture_group: int | None = Field(default=None, ge=0, le=XFA_SPLIT_MAX_REGEX_GROUPS)
|
||||
post_processors: list[XfaSplitPostProcessor] = Field(default_factory=list, max_length=1)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_matcher_shape(self) -> 'XfaSplitMatcher':
|
||||
|
||||
@@ -27,6 +27,7 @@ from app.services.shipping_notice.document_layout.field_split_core import (
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import XfaLeafValue
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
|
||||
XfaSplitPostProcessor,
|
||||
XfaSplitRuleSet,
|
||||
)
|
||||
|
||||
@@ -139,6 +140,56 @@ def _core_result_to_xfa(core: _CoreSplitEngineResult) -> XfaSplitEngineResult:
|
||||
)
|
||||
|
||||
|
||||
def _apply_prefix_post_processor(value: str, processor: XfaSplitPostProcessor) -> str | None:
|
||||
"""从已定位行中提取指定标签及分隔符后的值;未命中必须显式进入复核。"""
|
||||
source = str(value or '')
|
||||
comparable = source if processor.case_sensitive else source.lower()
|
||||
label = processor.value if processor.case_sensitive else processor.value.lower()
|
||||
start = comparable.find(label)
|
||||
if start < 0:
|
||||
return None
|
||||
tail_start = start + len(label)
|
||||
tail = source[tail_start:]
|
||||
for separator in processor.separators:
|
||||
if tail.startswith(separator):
|
||||
return tail[len(separator):].strip()
|
||||
return None
|
||||
|
||||
|
||||
def _apply_xfa_post_processors(
|
||||
result: XfaSplitEngineResult,
|
||||
*,
|
||||
rule_set: XfaSplitRuleSet,
|
||||
) -> XfaSplitEngineResult:
|
||||
"""对已由正式 matcher 定位的行执行受限后处理,并重新聚合正式字段。"""
|
||||
rules = {rule.rule_id: rule for rule in rule_set.rules}
|
||||
mapped_fields: dict[str, str] = {}
|
||||
needs_review = result.status == 'needs_review'
|
||||
for segment in result.segments:
|
||||
rule = rules.get(segment.rule_id)
|
||||
for processor in (rule.matcher.post_processors if rule else []):
|
||||
extracted = _apply_prefix_post_processor(segment.normalized_text, processor)
|
||||
if extracted is None:
|
||||
segment.normalized_text = ''
|
||||
segment.status = 'needs_review'
|
||||
needs_review = True
|
||||
result.diagnostics.append(XfaSplitDiagnostic(
|
||||
code='post_processor_no_match',
|
||||
message=f'Rule {segment.rule_id} post processor did not match the selected line',
|
||||
line_no=segment.line_no,
|
||||
field_code=segment.target_field_code,
|
||||
rule_ids=[segment.rule_id],
|
||||
))
|
||||
break
|
||||
segment.normalized_text = extracted
|
||||
if segment.handling == 'mapped' and segment.target_field_code:
|
||||
mapped_fields[segment.target_field_code] = segment.normalized_text
|
||||
result.mapped_fields = mapped_fields
|
||||
if needs_review:
|
||||
result.status = 'needs_review'
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 对外执行入口——签名 100% 不变
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -177,7 +228,7 @@ def execute_split_rule_set(
|
||||
rule_set=rule_set,
|
||||
lines=lines,
|
||||
)
|
||||
return _core_result_to_xfa(core_result)
|
||||
return _apply_xfa_post_processors(_core_result_to_xfa(core_result), rule_set=rule_set)
|
||||
|
||||
|
||||
def execute_split_on_leaf(
|
||||
|
||||
Reference in new issue
Block a user