feat(shipping-notice): 完善发货通知自动推进与多库存源复核闭环

This commit is contained in:
hugo committed 2026-08-09 11:43:53 +08:00
1 parent cfa19a0b7b
commit 8e0bbf7a81
180 files changed
+31210 -1864

No files matched your search

@@ -0,0 +1,231 @@
"""
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
@@ -0,0 +1,935 @@
"""
services/shipping_notice/document_layout/field_split_core.py
用途:共享的声明式字段拆分核心——承接 XFA(XML Forms Architecture)拆分引擎的纯文本执行能力,
为 Vendor Comments / Coordinate Region 等非 XFA 数据源提供统一的 prefix / regex / position
匹配、优先级仲裁、多规则冲突诊断、mapped/evidence_only 处理与规则内容指纹。
依赖:Pydantic 2、xfa_contract(复用 XfaContractModel 作为 Base Model 保持一致性)、
xfa_safe_regex(危险正则黑名单、超时限制、最大捕获组校验)。
逻辑:对外暴露 BaseSplit* 契约与 execute_base_split_rule_set() 执行入口;
XFA 链路通过 XfaSplit* extends BaseSplit* 复用本核心;Vendor Comments 链路直接使用 BaseSplit*;
本文件不得 import 任何 XFA 专属的 dataset/packet/leaf 节点(保持纯文本拆分引擎定位);
relation_capture 在此阶段仅在 core 内部捕获;XFA 适配器转换时丢弃(Q16 方案 A)。
"""
from __future__ import annotations
import json
import os
import re
import uuid
from dataclasses import dataclass, field
from typing import Any, Final, Literal
from pydantic import AliasChoices, Field, field_validator, model_validator
from app.services.shipping_notice.document_layout.xfa_contract import XfaContractModel
from app.services.shipping_notice.document_layout.xfa_safe_regex import (
SafeRegexError,
compile_safe_regex,
search_safe,
validate_restricted_regex_pattern,
)
# ---------------------------------------------------------------------------
# [STEP 0] 资源上限默认值——与 XFA 拆分保持同一量级,可由 settings / 环境变量覆盖
# ---------------------------------------------------------------------------
SPLIT_MAX_RULES_PER_SET: Final[int] = 32
SPLIT_MAX_RULE_SETS: Final[int] = 64
SPLIT_MAX_REGEX_PATTERN_LENGTH: Final[int] = 128
SPLIT_MAX_REGEX_GROUPS: Final[int] = 5
SPLIT_MAX_PREFIX_LENGTH: Final[int] = 64
SPLIT_MAX_SEGMENT_CODE_LENGTH: Final[int] = 64
SPLIT_MAX_DISPLAY_NAME_LENGTH: Final[int] = 128
SPLIT_MAX_INPUT_LENGTH: Final[int] = 32_768
SPLIT_REGEX_TIMEOUT_MS: Final[int] = 50
# 引擎固定匹配优先级(数值越小优先级越高)——与 XFA 拆分引擎保持一致,避免共享核心引入漂移
SPLIT_MATCHER_PRIORITY: Final[dict[str, int]] = {
'prefix': 0,
'regex': 1,
'position': 2,
}
SPLIT_UNMATCHED_PRIORITY: Final[int] = 3
SplitHandling = Literal['mapped', 'evidence_only']
SplitMatcherType = Literal['position', 'prefix', 'regex']
SplitSourceScope = Literal['header', 'line']
SplitUnmatchedPolicy = Literal['evidence_only', 'needs_review']
SplitDuplicatePolicy = Literal['needs_review']
SplitRuleStatus = Literal['draft', 'confirmed', 'published']
SplitRuleSource = Literal['system_suggestion', 'user', 'imported']
RelationCaptureType = Literal['line_reference']
RelationPolicyType = Literal['bind_target_line', 'annotation_only']
_SEGMENT_CODE_RE = re.compile(r'^[a-z][a-z0-9_]{1,63}$')
def _config_int(key: str, default: int) -> int:
"""
从 Flask config 或环境变量读取整型配置。
Args:
key: 配置键名。
default: 缺失时的默认值。
Returns:
解析后的正整数。
"""
try:
from flask import has_app_context, current_app
if has_app_context():
raw = current_app.config.get(key)
if raw is not None:
return max(1, int(raw))
except Exception:
pass
raw_env = os.getenv(key)
if raw_env is not None and str(raw_env).strip():
return max(1, int(raw_env))
return default
def get_split_max_rules_per_set() -> int:
"""单规则集最大 rules 条数。"""
return _config_int('SPLIT_MAX_RULES_PER_SET', SPLIT_MAX_RULES_PER_SET)
def get_split_max_rule_sets() -> int:
"""Profile 最大 split_rules 规则集数。"""
return _config_int('SPLIT_MAX_RULE_SETS', SPLIT_MAX_RULE_SETS)
def get_split_max_regex_pattern_length() -> int:
"""单条正则模式最大长度。"""
return _config_int('SPLIT_MAX_REGEX_PATTERN_LENGTH', SPLIT_MAX_REGEX_PATTERN_LENGTH)
def get_split_max_regex_groups() -> int:
"""正则最大捕获组数。"""
return _config_int('SPLIT_MAX_REGEX_GROUPS', SPLIT_MAX_REGEX_GROUPS)
def get_split_max_prefix_length() -> int:
"""前缀标签最大长度。"""
return _config_int('SPLIT_MAX_PREFIX_LENGTH', SPLIT_MAX_PREFIX_LENGTH)
def get_split_max_input_length() -> int:
"""拆分源字段最大输入长度。"""
return _config_int('SPLIT_MAX_INPUT_LENGTH', SPLIT_MAX_INPUT_LENGTH)
def get_split_regex_timeout_ms() -> int:
"""正则执行超时(毫秒)。"""
return _config_int('SPLIT_REGEX_TIMEOUT_MS', SPLIT_REGEX_TIMEOUT_MS)
# ---------------------------------------------------------------------------
# [STEP 1] 共享 Base 契约——剥离 XFA 专属 path_id / data_path / source_field_code
# ---------------------------------------------------------------------------
class RelationCaptureDef(XfaContractModel):
"""
可选:在规则命中时额外捕获"与目标字段相关的关系元数据"。
【AI 触发时机】:当 Profile 需要"先从备注提取值、再从同一句备注提取行号/关联号作为目标绑定依据"时,
在 BaseSplitMatcher 上配置本定义。
核心逻辑:和 value 捕获同一条正则或前缀行;但关系元数据不参与 mapped/evidence_only 的 target 决策,
关系如何解释由上层 Mapping 的 relation_policy 决定(Q2 双层设计)。
"""
type: RelationCaptureType = 'line_reference'
capture_group: int = Field(ge=0, le=SPLIT_MAX_REGEX_GROUPS)
labels: list[str] = Field(default_factory=list, max_length=16)
@model_validator(mode='after')
def validate_labels(self) -> 'RelationCaptureDef':
"""labels 去重,禁止空字符串。"""
cleaned = [str(item).strip() for item in (self.labels or []) if str(item).strip()]
object.__setattr__(self, 'labels', list(dict.fromkeys(cleaned)))
return self
class BaseSplitSegment(XfaContractModel):
"""共享拆分段:与 Schema 字段分离;mapped 时绑定冻结 Schema。"""
segment_id: str = Field(min_length=8, max_length=64)
segment_code: str = Field(min_length=2, max_length=SPLIT_MAX_SEGMENT_CODE_LENGTH)
display_name: str = Field(min_length=1, max_length=SPLIT_MAX_DISPLAY_NAME_LENGTH)
handling: SplitHandling
target_field_id: str | None = Field(default=None, max_length=64)
target_field_code: str | None = Field(default=None, max_length=128)
note: str | None = Field(default=None, max_length=256)
@field_validator('segment_code', mode='before')
@classmethod
def validate_segment_code(cls, value: Any) -> str:
"""segment_code 必须为小写蛇形,Profile 内唯一由上层校验。"""
code = str(value or '').strip()
if not _SEGMENT_CODE_RE.fullmatch(code):
raise ValueError(
'segment_code must be lowercase snake_case starting with a letter',
)
return code
@model_validator(mode='after')
def validate_handling_targets(self) -> 'BaseSplitSegment':
"""mapped 必须绑定目标字段;evidence_only 禁止目标字段。"""
if self.handling == 'mapped':
if not self.target_field_id or not self.target_field_code:
raise ValueError('mapped segment requires target_field_id and target_field_code')
else:
if self.target_field_id or self.target_field_code:
raise ValueError('evidence_only segment must not set target fields')
return self
class BaseSplitMatcher(XfaContractModel):
"""
共享单行匹配器:position / prefix / regex。
优先级由引擎固定为 prefix > regex > position;契约仅声明字段形状。
新增 relation_capture:当前仅 line_reference(Q2);XFA 链路当前不启用,
但 Base 契约提前引入避免阶段 2 再次改造。
"""
type: SplitMatcherType
line_index: int | None = Field(default=None, ge=1, le=1000)
value: str | None = Field(default=None, max_length=SPLIT_MAX_PREFIX_LENGTH)
separators: list[str] = Field(default_factory=lambda: [':', ':'])
case_sensitive: bool = False
pattern: str | None = Field(default=None, max_length=SPLIT_MAX_REGEX_PATTERN_LENGTH)
capture_group: int | None = Field(default=None, ge=0, le=SPLIT_MAX_REGEX_GROUPS)
relation_capture: RelationCaptureDef | None = None
@model_validator(mode='after')
def validate_matcher_shape(self) -> 'BaseSplitMatcher':
"""按 type 校验必填字段、前缀与正则安全边界。"""
max_prefix = get_split_max_prefix_length()
max_pattern_len = get_split_max_regex_pattern_length()
max_groups = get_split_max_regex_groups()
if self.type == 'position':
if self.line_index is None:
raise ValueError('position matcher requires line_index (1-based)')
elif self.type == 'prefix':
label = str(self.value or '').strip()
if not label:
raise ValueError('prefix matcher requires non-empty value')
if len(label) > max_prefix:
raise ValueError('prefix value exceeds max length')
seps = [str(item) for item in (self.separators or []) if str(item)]
if not seps:
raise ValueError('prefix matcher requires at least one separator')
object.__setattr__(self, 'separators', seps)
object.__setattr__(self, 'value', label)
elif self.type == 'regex':
pattern = str(self.pattern or '')
if not pattern:
raise ValueError('regex matcher requires pattern')
if len(pattern) > max_pattern_len:
raise ValueError('regex pattern exceeds max length')
try:
validate_restricted_regex_pattern(
pattern,
max_length=max_pattern_len,
max_groups=max_groups,
)
except SafeRegexError as exc:
raise ValueError(str(exc)) from exc
if self.capture_group is not None and self.capture_group > max_groups:
raise ValueError('capture_group exceeds pattern groups limit')
if self.relation_capture is not None and self.relation_capture.capture_group > max_groups:
raise ValueError('relation_capture.capture_group exceeds pattern groups limit')
else:
raise ValueError(f'unsupported matcher type: {self.type}')
return self
class BaseSplitRule(XfaContractModel):
"""共享单条拆分规则:rule_id + matcher + segment(无 stages[])。"""
rule_id: str = Field(min_length=1, max_length=64)
matcher: BaseSplitMatcher
segment: BaseSplitSegment
class BaseSplitNormalization(XfaContractModel):
"""规则集级换行与 trim 策略:引擎按 line_breaks 拆行后再逐行匹配。"""
trim: bool = True
remove_empty_lines: bool = True
line_breaks: list[str] = Field(default_factory=lambda: ['\r\n', '\r', '\n'])
@model_validator(mode='after')
def validate_breaks(self) -> 'BaseSplitNormalization':
"""line_breaks 不可为空。"""
breaks = [str(item) for item in (self.line_breaks or []) if str(item)]
if not breaks:
raise ValueError('normalization.line_breaks requires at least one value')
object.__setattr__(self, 'line_breaks', breaks)
return self
class BaseSplitRuleSet(XfaContractModel):
"""
共享规则集:针对单一源文本的拆分规则集合。
不含 XFA 专属的 source_path_id / source_data_path / source_field_code,
这些由 XfaSplitRuleSet extends 本类后追加。
"""
rule_set_id: str = Field(
min_length=1,
max_length=128,
validation_alias=AliasChoices('rule_set_id', 'rule_id'),
)
rule_version: int = Field(ge=1, le=10_000)
normalization: BaseSplitNormalization = Field(default_factory=BaseSplitNormalization)
rules: list[BaseSplitRule] = Field(default_factory=list)
unmatched_line_policy: SplitUnmatchedPolicy = 'evidence_only'
duplicate_match_policy: SplitDuplicatePolicy = 'needs_review'
same_field_multiple_segment_policy: SplitDuplicatePolicy = 'needs_review'
source: SplitRuleSource = 'user'
status: SplitRuleStatus = 'draft'
requires_confirmation: bool = False
@property
def rule_id(self) -> str:
"""兼容旧字段名 rule_id(等同 rule_set_id)。"""
return self.rule_set_id
@model_validator(mode='after')
def validate_rule_set_invariants(self) -> 'BaseSplitRuleSet':
"""规则集内唯一性与数量上限。"""
max_rules = get_split_max_rules_per_set()
if len(self.rules) > max_rules:
raise ValueError(f'rules exceed max {max_rules}')
rule_ids = [item.rule_id for item in self.rules]
if len(rule_ids) != len(set(rule_ids)):
raise ValueError('duplicate rule_id within split rule set')
segment_ids = [item.segment.segment_id for item in self.rules]
if len(segment_ids) != len(set(segment_ids)):
raise ValueError('duplicate segment_id within split rule set')
segment_codes = [item.segment.segment_code for item in self.rules]
if len(segment_codes) != len(set(segment_codes)):
raise ValueError('duplicate segment_code within split rule set')
if self.source == 'system_suggestion':
if self.status != 'draft' or not self.requires_confirmation:
raise ValueError(
'system_suggestion must be draft with requires_confirmation=true',
)
return self
def new_segment_id() -> str:
"""
生成不可变 segment_id。
Returns:
形如 seg-<uuid4hex> 的稳定标识。
"""
return f'seg-{uuid.uuid4().hex}'
def new_rule_id(prefix: str = 'rule') -> str:
"""
生成规则条目 ID。
Args:
prefix: ID 前缀。
Returns:
形如 ``{prefix}-<hex>`` 的标识。
"""
safe = re.sub(r'[^a-z0-9_]+', '_', str(prefix or 'rule').strip().lower()) or 'rule'
return f'{safe}-{uuid.uuid4().hex[:12]}'
def base_split_content_fingerprint(rule_set: BaseSplitRuleSet | dict[str, Any]) -> str:
"""
计算共享规则集内容指纹(排除 status / requires_confirmation / rule_version / handling/targets)。
核心逻辑:只冻结 matcher、normalization 与 relation_capture 定义;
segment 的 Schema 映射字段(handling/target_field_*)不属于拆分逻辑本身,
后续绑定或解绑目标字段不得取消已确认状态。
Args:
rule_set: 模型或 dict。
Returns:
稳定 JSON 字符串指纹素材(调用方可再 hash)。
"""
if isinstance(rule_set, BaseSplitRuleSet):
payload = rule_set.model_dump(mode='json', by_alias=True)
else:
payload = dict(rule_set or {})
if 'rule_set_id' not in payload and payload.get('rule_id'):
payload['rule_set_id'] = payload['rule_id']
payload.pop('status', None)
payload.pop('requires_confirmation', None)
payload.pop('rule_version', None)
payload.pop('rule_id', None)
for rule in payload.get('rules') or []:
segment = rule.get('segment') if isinstance(rule, dict) else None
if not isinstance(segment, dict):
continue
segment.pop('handling', None)
segment.pop('target_field_id', None)
segment.pop('target_field_code', None)
return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
# ---------------------------------------------------------------------------
# [STEP 2] 共享核心执行——纯 dataclass 中间结果,不暴露给 XFA 对外 API
# ---------------------------------------------------------------------------
@dataclass
class CoreCapturedRelation:
"""核心层捕获到的关系元数据(Q2 双层设计 rule/matcher 层)。"""
type: RelationCaptureType
line_no: int | None
raw_text: str | None
@dataclass
class _CoreSegmentResult:
"""单段执行结果(核心层,含 captured_relation;XFA 适配后丢弃)。"""
segment_id: str
segment_code: str
display_name: str
line_no: int | None
line_end_no: int | None
raw_text: str
normalized_text: str
handling: str
target_field_id: str | None
target_field_code: str | None
rule_id: str
status: str
matcher_type: str
captured_relation: CoreCapturedRelation | None = None
@dataclass
class CoreSplitDiagnostic:
"""共享核心规则执行诊断。"""
code: str
message: str
line_no: int | None = None
field_code: str | None = None
rule_ids: list[str] = field(default_factory=list)
@dataclass
class _CoreSplitEngineResult:
"""共享核心引擎输出。"""
status: str
segments: list[_CoreSegmentResult] = field(default_factory=list)
mapped_fields: dict[str, str] = field(default_factory=dict)
evidence_only_segments: list[_CoreSegmentResult] = field(default_factory=list)
diagnostics: list[CoreSplitDiagnostic] = field(default_factory=list)
rule_set_id: str | None = None
rule_version: int | None = None
@dataclass
class _LineMatch:
"""单行候选命中(共享核心版,含 relation 捕获)。"""
rule: BaseSplitRule
matcher_type: str
priority: int
line_text: str
normalized_text: str
raw_line: str
captured_relation: CoreCapturedRelation | None = None
# ---------------------------------------------------------------------------
# [STEP 3] 纯文本执行函数——从 XFA 拆分引擎原封不动迁移,保持字节级一致
# ---------------------------------------------------------------------------
def _split_text_by_breaks(text: str, line_breaks: list[str]) -> list[str]:
"""
按声明的 line_breaks 切分文本(长分隔符优先)。
Args:
text: 原始文本。
line_breaks: 换行符列表。
Returns:
切分后的行列表(尚未 trim / 去空行)。
"""
if not text:
return []
pattern = '|'.join(re.escape(item) for item in sorted(line_breaks, key=len, reverse=True))
if not pattern:
return [text]
return re.split(pattern, text)
def _apply_line_normalization(
lines: list[str],
*,
trim: bool,
remove_empty_lines: bool,
) -> list[str]:
"""对行列表应用 trim / 去空行。"""
out = list(lines)
if trim:
out = [item.strip() for item in out]
if remove_empty_lines:
out = [item for item in out if item]
return out
def _inventory_lines(raw_value: str, rule_set: BaseSplitRuleSet) -> list[str]:
"""
用规则集级 normalization 生成行清单。
核心逻辑:按 normalization.line_breaks 拆行并应用 trim / 去空行。
"""
norm = rule_set.normalization
lines = _split_text_by_breaks(raw_value or '', list(norm.line_breaks))
return _apply_line_normalization(
lines,
trim=bool(norm.trim),
remove_empty_lines=bool(norm.remove_empty_lines),
)
def _extract_prefix_value(line: str, matcher: BaseSplitMatcher) -> str | None:
"""
前缀匹配:标签 + 分隔符后的值。
Returns:
提取值;无法匹配时 None。
"""
label = str(matcher.value or '')
hay = line if matcher.case_sensitive else line.casefold()
needle = label if matcher.case_sensitive else label.casefold()
if not hay.startswith(needle):
return None
rest = line[len(label):]
for sep in matcher.separators:
if rest.startswith(sep):
return rest[len(sep):].strip()
stripped = rest.lstrip()
if stripped.startswith(sep):
return stripped[len(sep):].strip()
return None
def _regex_extract_value_and_relation(
line: str,
matcher: BaseSplitMatcher,
) -> tuple[str | None, CoreCapturedRelation | None, str | None]:
"""
正则捕获单行文本的值与可选 relation。
Returns:
(value, captured_relation, error_code);成功时 error_code 为 None。
"""
pattern = str(matcher.pattern or '')
timeout_ms = get_split_regex_timeout_ms()
max_len = get_split_max_regex_pattern_length()
max_groups = get_split_max_regex_groups()
try:
compiled = compile_safe_regex(
pattern,
case_sensitive=bool(matcher.case_sensitive),
max_length=max_len,
max_groups=max_groups,
)
matched = search_safe(compiled, line, timeout_ms=timeout_ms)
except SafeRegexError:
return None, None, 'regex_failed'
except TimeoutError:
return None, None, 'regex_timeout'
if not matched:
return None, None, 'regex_not_matched'
group = matcher.capture_group
try:
if group is None:
if matched.lastindex:
value = str(matched.group(1) or '').strip()
else:
value = str(matched.group(0) or '').strip()
else:
value = str(matched.group(group) or '').strip()
except IndexError:
return None, None, 'regex_failed'
relation: CoreCapturedRelation | None = None
rc = matcher.relation_capture
if rc is not None:
try:
rel_raw = matched.group(rc.capture_group)
rel_text = str(rel_raw or '').strip() if rel_raw is not None else None
rel_line_no: int | None = None
if rel_text:
m = re.search(r'(\d{1,6})', rel_text)
if m:
rel_line_no = int(m.group(1))
relation = CoreCapturedRelation(
type=rc.type,
line_no=rel_line_no,
raw_text=rel_text,
)
except (IndexError, ValueError):
relation = None
return value, relation, None
def _match_line(
line_no: int,
line: str,
rule: BaseSplitRule,
) -> tuple[_LineMatch | None, str | None]:
"""
判断单条规则是否命中指定行(共享核心版,支持 relation 捕获)。
Returns:
(match, error_code):命中时 error_code 为 None;未命中时 match 为 None。
"""
matcher = rule.matcher
priority = SPLIT_MATCHER_PRIORITY.get(matcher.type)
if priority is None:
return None, 'unknown_matcher'
if matcher.type == 'position':
if int(matcher.line_index or 0) != line_no:
return None, None
normalized = line.strip() if line else ''
return _LineMatch(
rule=rule,
matcher_type='position',
priority=priority,
line_text=line,
normalized_text=normalized,
raw_line=line,
), None
if matcher.type == 'prefix':
extracted = _extract_prefix_value(line, matcher)
if extracted is None:
return None, None
return _LineMatch(
rule=rule,
matcher_type='prefix',
priority=priority,
line_text=line,
normalized_text=extracted,
raw_line=line,
), None
if matcher.type == 'regex':
value, relation, err = _regex_extract_value_and_relation(line, matcher)
if err:
return None, err
if value is None:
return None, None
return _LineMatch(
rule=rule,
matcher_type='regex',
priority=priority,
line_text=line,
normalized_text=value,
raw_line=line,
captured_relation=relation,
), None
return None, 'unknown_matcher'
def _pick_line_winner(
line_no: int,
matches: list[_LineMatch],
diagnostics: list[CoreSplitDiagnostic],
) -> _LineMatch | None:
"""
按 prefix > regex > position 决出单行唯一胜出规则。
核心逻辑:同优先级多个 mapped 命中 → duplicate_line_match;不同优先级取最高优先级。
"""
if not matches:
return None
diagnostics.append(CoreSplitDiagnostic(
code='line_match_candidates',
message='All matcher hits for line recorded',
line_no=line_no,
rule_ids=[item.rule.rule_id for item in matches],
))
best_priority = min(item.priority for item in matches)
tier = [item for item in matches if item.priority == best_priority]
mapped_tier = [item for item in tier if item.rule.segment.handling == 'mapped']
if len(mapped_tier) >= 2:
diagnostics.append(CoreSplitDiagnostic(
code='duplicate_line_match',
message='Multiple mapped rules matched the same line at the same priority',
line_no=line_no,
rule_ids=[item.rule.rule_id for item in mapped_tier],
))
if len(tier) == 1:
return tier[0]
if len(mapped_tier) == 1:
return mapped_tier[0]
if len(mapped_tier) >= 2:
return sorted(mapped_tier, key=lambda item: item.rule.rule_id)[0]
return sorted(tier, key=lambda item: item.rule.rule_id)[0]
def execute_base_split_rule_set(
*,
raw_value: str,
rule_set: BaseSplitRuleSet,
lines: list[str] | None = None,
) -> _CoreSplitEngineResult:
"""
对单个源文本原值执行共享拆分规则集。
核心逻辑:
1. normalization.line_breaks 拆行;
2. 逐行收集命中规则,按 prefix > regex > position 决出唯一 segment;
3. 同优先级多个 mapped 命中 → duplicate_line_match / needs_review;
4. 未认领行按 unmatched_line_policy;
5. evidence_only 全部保留;
6. relation_capture 在 core 层保留到 _CoreSegmentResult(上层适配决定是否丢弃)。
Args:
raw_value: 保留换行的原始文本(XFA 场景下是 leaf.raw_value;VC 场景下是区域原文)。
rule_set: 已校验共享规则集。
lines: 可选预切分行(覆盖 normalization 结果)。
Returns:
_CoreSplitEngineResult。
"""
if len(raw_value or '') > get_split_max_input_length():
return _CoreSplitEngineResult(
status='needs_review',
diagnostics=[CoreSplitDiagnostic(
code='input_too_long',
message='Split source value exceeds max input length',
)],
rule_set_id=rule_set.rule_set_id,
rule_version=rule_set.rule_version,
)
inventory = list(lines) if lines is not None else _inventory_lines(raw_value, rule_set)
diagnostics: list[CoreSplitDiagnostic] = []
segments: list[_CoreSegmentResult] = []
claimed_lines: set[int] = set()
# [STEP 1] 逐行匹配并按优先级决出胜出规则。
for line_no, line in enumerate(inventory, start=1):
matches: list[_LineMatch] = []
for rule in rule_set.rules:
outcome, error = _match_line(line_no, line, rule)
if error:
diagnostics.append(CoreSplitDiagnostic(
code=error,
message=f'Rule {rule.rule_id} regex failed on line {line_no}',
line_no=line_no,
field_code=rule.segment.target_field_code,
rule_ids=[rule.rule_id],
))
continue
if outcome is not None:
matches.append(outcome)
winner = _pick_line_winner(line_no, matches, diagnostics)
if winner is None:
continue
claimed_lines.add(line_no)
seg = winner.rule.segment
status = 'parsed'
if not str(winner.normalized_text).strip() and seg.handling == 'mapped':
status = 'needs_review'
diagnostics.append(CoreSplitDiagnostic(
code='mapped_value_empty',
message=f'Mapped segment {seg.segment_code} extracted empty value',
line_no=line_no,
field_code=seg.target_field_code,
rule_ids=[winner.rule.rule_id],
))
segments.append(_CoreSegmentResult(
segment_id=seg.segment_id,
segment_code=seg.segment_code,
display_name=seg.display_name,
line_no=line_no,
line_end_no=line_no,
raw_text=winner.raw_line,
normalized_text=winner.normalized_text,
handling=seg.handling,
target_field_id=seg.target_field_id,
target_field_code=seg.target_field_code,
rule_id=winner.rule.rule_id,
status=status,
matcher_type=winner.matcher_type,
captured_relation=winner.captured_relation,
))
# [STEP 2] 未匹配行。
for line_index, line in enumerate(inventory, start=1):
if line_index in claimed_lines:
continue
status = 'needs_review' if rule_set.unmatched_line_policy == 'needs_review' else 'parsed'
if status == 'needs_review':
diagnostics.append(CoreSplitDiagnostic(
code='unmatched_line',
message='Unmatched line requires review',
line_no=line_index,
))
segments.append(_CoreSegmentResult(
segment_id=f'unmatched-{line_index}',
segment_code=f'unmatched_line_{line_index}',
display_name=f'其他编码/{line_index}',
line_no=line_index,
line_end_no=line_index,
raw_text=line,
normalized_text=line.strip(),
handling='evidence_only',
target_field_id=None,
target_field_code=None,
rule_id='unmatched',
status=status,
matcher_type='unmatched',
))
# [STEP 3] 聚合正式字段。
mapped_fields: dict[str, str] = {}
field_sources: dict[str, list[str]] = {}
overall = 'parsed'
for item in segments:
if item.status == 'needs_review':
overall = 'needs_review'
if item.handling != 'mapped' or not item.target_field_code:
continue
code = item.target_field_code
field_sources.setdefault(code, []).append(item.rule_id)
if code in mapped_fields:
overall = 'needs_review'
diagnostics.append(CoreSplitDiagnostic(
code='same_field_multiple_segment',
message=f'Schema field {code} hit by multiple segments',
field_code=code,
rule_ids=list(field_sources[code]),
))
else:
mapped_fields[code] = item.normalized_text
for _code, sources in field_sources.items():
if len(sources) > 1 and rule_set.same_field_multiple_segment_policy == 'needs_review':
overall = 'needs_review'
if any(d.code == 'duplicate_line_match' for d in diagnostics):
if rule_set.duplicate_match_policy == 'needs_review':
overall = 'needs_review'
if any(d.code in {
'regex_timeout', 'regex_failed', 'mapped_value_empty', 'input_too_long',
} for d in diagnostics):
overall = 'needs_review'
evidence_only = [item for item in segments if item.handling == 'evidence_only']
return _CoreSplitEngineResult(
status=overall,
segments=segments,
mapped_fields=mapped_fields,
evidence_only_segments=evidence_only,
diagnostics=diagnostics,
rule_set_id=rule_set.rule_set_id,
rule_version=rule_set.rule_version,
)
def project_base_split_result_safe(
result: _CoreSplitEngineResult,
*,
include_full_values: bool = False,
mask_value_for_dto_fn: Any = None,
) -> dict[str, Any]:
"""
将共享核心引擎结果投影为普通 DTO。
核心逻辑:默认脱敏 mapped/segment 文本;仅当调用方已通过敏感读权限且
include_full_values=True 时返回 raw_text / 完整 mapped 值。
Args:
result: 引擎输出。
include_full_values: 是否返回完整业务值(需上游权限门禁)。
mask_value_for_dto_fn: 可选脱敏函数;None 时使用恒等函数。
Returns:
JSON 可序列化 dict。
"""
def _text(value: str) -> str:
if include_full_values:
return str(value)
if mask_value_for_dto_fn is not None:
try:
return mask_value_for_dto_fn(value)
except Exception:
return str(value)
return str(value)
mapped = {
code: _text(value)
for code, value in result.mapped_fields.items()
}
return {
'status': result.status,
'rule_set_id': result.rule_set_id,
'rule_version': result.rule_version,
'full_values_revealed': bool(include_full_values),
'mapped_fields': mapped,
'segments': [
{
'segment_id': item.segment_id,
'segment_code': item.segment_code,
'display_name': item.display_name,
'line_no': item.line_no,
'line_end_no': item.line_end_no,
'raw_text': _text(item.raw_text),
'normalized_text': _text(item.normalized_text),
'handling': item.handling,
'target_field_id': item.target_field_id,
'target_field_code': item.target_field_code,
'rule_id': item.rule_id,
'status': item.status,
'matcher_type': item.matcher_type,
}
for item in result.segments
],
'evidence_only_segments': [],
'diagnostics': [
{
'code': item.code,
'message': item.message,
'line_no': item.line_no,
'field_code': item.field_code,
'rule_ids': list(item.rule_ids),
}
for item in result.diagnostics
],
}
@@ -13,29 +13,15 @@ def _coordinate_mapping(value: Any) -> dict[str, Any]:
return dict(value) if isinstance(value, dict) else {}
def _append_issue(layout: dict[str, Any], issue: str) -> None:
"""稳定追加坐标恢复失败码,不改变原 issues 相对顺序。"""
existing = layout.get('issues') if isinstance(layout.get('issues'), list) else []
issues = [str(item) for item in existing]
if issue not in issues:
issues.append(issue)
layout['issues'] = issues
def ensure_on_demand_coordinate_evidence(
*, document: ShippingOrderDocument, layout: dict[str, Any], page_nos: set[int] | None,
table_by_page: dict[int, dict[str, Any] | list[dict[str, Any]]] | None = None,
) -> dict[str, Any]:
"""为盲测和正式抽取恢复所需页坐标;同页多表必须分别保留字符证据。
【AI/调用方触发时机】:
- 订单字段重放、模板匹配或明细重建前,为当前 snapshot 恢复缺失页的真实坐标。
- 失败不静默;任何 PDFium/OCR 失败都会在 layout['issues'] 追加稳定失败码,
上游可据此将 matcher 从 no_match 转为 evidence_insufficient。
"""
"""为盲测和正式抽取恢复所需页坐标;同页多表必须分别保留字符证据。"""
if not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'):
return layout
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
# 兼容历史布局快照:布局任务曾将坐标证据写在顶层,正式抽取仍需复用它。
if not evidence:
legacy_keys = ('pages', 'page_glyphs', 'sources', 'tables')
evidence = {
@@ -43,6 +29,7 @@ def ensure_on_demand_coordinate_evidence(
for key in legacy_keys
if isinstance(layout.get(key), dict)
}
# Run 快照可能早于最近一次布局重试;读取当前成功/失败版本仅作本次内存补充。
current_version = getattr(document, 'current_layout_version', None)
current_payload = getattr(current_version, 'payload_json', None)
if isinstance(current_payload, dict):
@@ -57,15 +44,7 @@ def ensure_on_demand_coordinate_evidence(
sources = _coordinate_mapping(evidence.get('sources'))
source_pages = _coordinate_mapping(sources.get('pages'))
tables = _coordinate_mapping(evidence.get('tables'))
# [FAIL-CLOSED GATE] page_glyphs 必须对所需页真实存在;不能用 pages 元数据或
# 非数字脏键来假装已恢复。MinerU HTML 表 + 空 page_glyphs 的组合必须继续走
# 真实 PDFium/OCR 抽取,否则会退化为"伪精确匹配分数"。
present_pages = {
int(key) for key in page_glyphs
if str(key).isdigit() and isinstance(page_glyphs.get(key), list) and len(page_glyphs.get(key) or []) > 0
}
needs_recovery = bool(page_nos is None) or not page_nos.issubset(present_pages)
if not needs_recovery:
if page_nos is not None and page_nos.issubset({int(p) for p in page_glyphs if str(p).isdigit()}):
return layout
tables_by_page: dict[int, list[dict[str, Any]]] = {}
for raw_table in layout.get('tables') or []:
@@ -91,15 +70,11 @@ def ensure_on_demand_coordinate_evidence(
)
asset = db.session.get(FileAsset, int(document.asset_id))
if asset is None:
_append_issue(layout, 'coordinate_evidence_asset_missing')
return layout
try:
native_pages = extract_native_pdf_pages(read_asset_bytes(asset))
except Exception:
# [FAIL-CLOSED] PDFium 级异常必须显式上报;禁止用 MinerU HTML 列名顶替坐标。
_append_issue(layout, 'coordinate_evidence_native_pdf_unavailable')
return layout
recovered_any_page = False
for page in native_pages:
if page_nos is not None and int(page.page_no) not in page_nos:
continue
@@ -112,14 +87,12 @@ def ensure_on_demand_coordinate_evidence(
source = 'ocr_coordinate'
except Exception:
glyphs = []
_append_issue(layout, f'coordinate_evidence_ocr_failed_page_{page.page_no}')
if not glyphs:
continue
page_key = str(page.page_no)
pages[page_key] = {'width': page.width, 'height': page.height}
page_glyphs[page_key] = glyphs
source_pages[page_key] = source
recovered_any_page = True
for table in tables_by_page.get(int(page.page_no), []):
table_id = str(table.get('table_id') or '')
chars = _native_characters_in_table(
@@ -134,8 +107,6 @@ def ensure_on_demand_coordinate_evidence(
chars = []
if table_id and chars:
tables[table_id] = chars
if page_nos is not None and not recovered_any_page:
_append_issue(layout, 'coordinate_evidence_no_page_recovered')
next_layout = dict(layout)
next_layout['coordinate_evidence'] = {
**evidence, 'pages': pages, 'page_glyphs': page_glyphs,
@@ -119,22 +119,7 @@ def match_frozen_coordinate_profiles(
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
glyph_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 {}
# [FAIL-CLOSED GATE] 第零层:on-demand 坐标恢复显式失败时直接拒绝匹配。
# 任何 coordinate_evidence_* 失败码都意味着正式证据不可用,MinerU HTML 列名
# 不得作为坐标模板匹配的替代事实源。
layout_issues = {str(item) for item in (layout.get('issues') or []) if str(item)}
coordinate_failure_issues = {
code for code in layout_issues if code.startswith('coordinate_evidence_')
}
if coordinate_failure_issues:
return ProfileMatchResult(status='evidence_insufficient')
# [FAIL-CLOSED GATE] 第一层:坐标字符证据必须至少有一种来源。
# MinerU HTML tables(layout['tables'])只有结构化列名、没有绝对坐标/bbox,
# 严禁单独充当坐标模板的匹配证据。否则会出现"MinerU 有列名但 matcher
# header_tokens=空、column_count=0、evidence_coverage 伪分数"的分裂。
if not pages:
return ProfileMatchResult(status='evidence_insufficient')
if not glyph_tables and not page_glyphs:
if not pages or (not glyph_tables and not page_glyphs and not tables):
return ProfileMatchResult(status='evidence_insufficient')
page_text = _layout_page_text(
@@ -216,25 +201,6 @@ def match_frozen_coordinate_profiles(
)
reason_codes.extend(hard_conflict_codes)
# [FAIL-CLOSED GATE] 第二层:身份证据缺失时,结构/几何维度不得独立构成模板命中。
# 用户场景:page_glyphs 虽有字符但观测不到 header_tokens 或
# column_centers;若签名冻结了核心列身份证据,就必须以身份优先、
# 结构辅助。否则 table_geometry + page_structure 的弱证据会掩盖
# "列名证据没有进入匹配器" 的真正问题。
signature_patterns = (
[item for item in (signature_body or {}).get('table_patterns') or [] if isinstance(item, dict)]
if signature_body is not None else []
)
signature_expects_identity = any(
bool(p.get('header_tokens') or p.get('column_centers') or (p.get('column_count') or 0) > 0)
for p in signature_patterns
)
observed_header = [str(item) for item in (observed.get('header_tokens') or []) if str(item).strip()]
observed_col_count = int(observed.get('column_count') or 0)
observed_has_identity = bool(observed_header) or observed_col_count > 0
if signature_expects_identity and not observed_has_identity:
reason_codes.append('profile_core_column_evidence_missing')
weights = profile.document_match.scoring_weights
score, evidence_coverage = _aggregate_dimension_score(weights=weights, dimension_results=dimension_results)
hard_match = not reason_codes
@@ -290,19 +256,6 @@ def match_frozen_coordinate_profiles(
status='no_match', candidates=rendered,
top1_score=top1_score, top2_score=top2_score, margin=margin,
)
# [FAIL-CLOSED GATE] 第三层:全局证据不足优先于 no_match / layout_drift。
# 当所有候选要么缺签名身份证据、要么观测不到核心列名/列坐标时,必须
# evidence_insufficient,禁止把"没证据"误报成"模板都不匹配"。
global_identity_missing = all(
'profile_core_column_evidence_missing' in item.reason_codes
or 'profile_signature_missing' in item.reason_codes
for item in rendered
)
if global_identity_missing:
return ProfileMatchResult(
status='evidence_insufficient', candidates=rendered,
top1_score=None, top2_score=None, margin=None,
)
if _any_special_profile_feature(candidates, page_text=page_text):
return ProfileMatchResult(
status='layout_drift', candidates=rendered,
@@ -0,0 +1,456 @@
"""
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),
}
@@ -0,0 +1,338 @@
"""
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()
@@ -0,0 +1,152 @@
"""
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,
)
@@ -0,0 +1,228 @@
"""
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,
)
@@ -500,12 +500,10 @@ def _native_pdf_fallback_snapshot(
layout_payload=layout_payload_preview,
)
evidence_started = perf_counter()
# [FAIL-CLOSED OVERRIDE] Fallback 快照即使是 PDFium 文本回退,也必须默认
# 保存整页 glyph。否则一旦 on-demand 恢复异常(如 asset_id 丢失或 PDFium 崩
# 溃),matcher 会看到"MinerU 列名存在 + 空 page_glyphs"的分裂证据,输出
# 伪精确模板分数。坐标预算由后续 compact 负责兜底,初始生成必须包含身份证据。
# Fallback snapshots only need table-local glyphs for template modeling. Keeping
# every page glyph can exceed the persisted snapshot budget on text-heavy PDFs.
evidence = _table_coordinate_evidence(
pages=native_pages, tables=tables, include_page_glyphs=True,
pages=native_pages, tables=tables, include_page_glyphs=False,
diagnostics=diagnostics,
)
if diagnostics is not None:
@@ -0,0 +1,342 @@
"""
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
@@ -0,0 +1,195 @@
"""
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
@@ -0,0 +1,230 @@
"""
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
@@ -0,0 +1,204 @@
"""
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 {}),
}
@@ -816,8 +816,7 @@ def extract_xfa_profile(
reason_codes: list[str] = []
if has_unconfirmed_split_rules:
reason_codes.append('xfa_split_rule_unconfirmed')
if required_missing:
reason_codes.append('xfa_required_field_missing')
source_mapping_incomplete = bool(required_missing)
evidence_summary = sanitize_xfa_dto({
'header_field_count': len(header_fields),
@@ -827,6 +826,7 @@ def extract_xfa_profile(
'parser_identity': XFA_PARSER_IDENTITY,
'profile_checksum': str(raw_profile.get('checksum') or '') or None,
'header_split_evidence': header_split_evidence,
'xfa_source_mapping_incomplete': source_mapping_incomplete,
'field_evidence_refs': [
item.evidence for item in header_fields
] + [
@@ -3,13 +3,18 @@ services/shipping_notice/document_layout/xfa_split_rule_contract.py
用途:冻结 XFA 字段拆分规则契约——matcher 优先级模型、segment 映射、
evidence_only 边界、正则资源上限与 Schema 校验入口。
依赖:Pydantic 2、xfa_contract、xfa_safe_regex、Flask settings(可选)。
依赖:Pydantic 2、xfa_contract、xfa_safe_regex、Flask settings(可选);
共享契约来自 field_split_core(BaseSplitNormalization / BaseSplitMatcher /
BaseSplitSegment / BaseSplitRule / BaseSplitRuleSet)。
逻辑:仅声明式校验,不执行规则、不读 PDF、不接网络;非法契约以 ValidationError
或 ValueError 拒绝;匹配优先级由引擎固定 prefix > regex > position > unmatched。
或 ValueError 拒绝;匹配优先级由引擎固定 prefix > regex > position > unmatched;
XfaSplit* 系列继承共享核心 BaseSplit*,但保留 XFA 专属字段(source_path_id /
source_data_path 等)和 XFA 前缀的环境变量读取,保持对外行为零漂移。
"""
from __future__ import annotations
import json
import os
import re
import uuid
@@ -17,6 +22,13 @@ from typing import Any, Final, Literal
from pydantic import AliasChoices, Field, field_validator, model_validator
from app.services.shipping_notice.document_layout.field_split_core import (
BaseSplitMatcher,
BaseSplitNormalization,
BaseSplitRule,
BaseSplitRuleSet,
BaseSplitSegment,
)
from app.services.shipping_notice.document_layout.xfa_contract import (
XfaContractModel,
validate_controlled_data_path,
@@ -28,6 +40,7 @@ from app.services.shipping_notice.document_layout.xfa_safe_regex import (
# ---------------------------------------------------------------------------
# 资源上限默认值(可被 settings / 环境变量覆盖)
# 注意:为保持 XFA 链路零行为变化,环境变量前缀仍使用 XFA_SPLIT_*(与共享核心 SPLIT_* 分治)
# ---------------------------------------------------------------------------
XFA_SPLIT_MAX_RULES_PER_SET: Final[int] = 32
@@ -120,8 +133,11 @@ def get_xfa_split_regex_timeout_ms() -> int:
return _config_int('XFA_SPLIT_REGEX_TIMEOUT_MS', XFA_SPLIT_REGEX_TIMEOUT_MS)
class XfaSplitSegment(XfaContractModel):
"""自定义拆分段:与 Schema 字段分离;mapped 时绑定冻结 Schema。"""
class XfaSplitSegment(BaseSplitSegment):
"""
自定义拆分段:与 Schema 字段分离;mapped 时绑定冻结 Schema。
继承共享核心 BaseSplitSegment;保留 XFA 自己的校验器以保证 XFA_ 前缀环境变量仍生效。
"""
segment_id: str = Field(min_length=8, max_length=64)
segment_code: str = Field(min_length=2, max_length=XFA_SPLIT_MAX_SEGMENT_CODE_LENGTH)
@@ -154,11 +170,12 @@ class XfaSplitSegment(XfaContractModel):
return self
class XfaSplitMatcher(XfaContractModel):
class XfaSplitMatcher(BaseSplitMatcher):
"""
单行匹配器:position / prefix / regex。
优先级由引擎固定为 prefix > regex > position;契约仅声明字段形状。
继承共享核心 BaseSplitMatcher;保留 XFA 自己的校验器与 XFA_ 前缀长度常量。
"""
type: XfaSplitMatcherType
@@ -211,7 +228,7 @@ class XfaSplitMatcher(XfaContractModel):
return self
class XfaSplitRule(XfaContractModel):
class XfaSplitRule(BaseSplitRule):
"""单条拆分规则:rule_id + matcher + segment(无 stages[])。"""
rule_id: str = Field(min_length=1, max_length=64)
@@ -219,7 +236,7 @@ class XfaSplitRule(XfaContractModel):
segment: XfaSplitSegment
class XfaSplitNormalization(XfaContractModel):
class XfaSplitNormalization(BaseSplitNormalization):
"""规则集级换行与 trim 策略:引擎按 line_breaks 拆行后再逐行匹配。"""
trim: bool = True
@@ -236,12 +253,16 @@ class XfaSplitNormalization(XfaContractModel):
return self
class XfaSplitRuleSet(XfaContractModel):
class XfaSplitRuleSet(BaseSplitRuleSet):
"""
针对单一源字段的拆分规则集,存于 Profile definition_json.split_rules。
规则由管理员手工配置(source=user/imported)。若出现历史 source=system_suggestion,
必须保持 draft + requires_confirmation,且不得进入正式提取/发布。
继承共享核心 BaseSplitRuleSet;追加 XFA 专属字段:source_path_id / source_scope /
source_field_code / source_data_path。校验器保留 XFA 自己的实现,确保 XFA_SPLIT_*
前缀环境变量、path_id 白名单校验仍然生效,不会被共享核心的默认值覆盖。
"""
rule_set_id: str = Field(
@@ -278,7 +299,7 @@ class XfaSplitRuleSet(XfaContractModel):
@model_validator(mode='after')
def validate_rule_set_invariants(self) -> 'XfaSplitRuleSet':
"""规则集内唯一性与数量上限。"""
"""规则集内唯一性与数量上限(XFA 专用,读取 XFA_SPLIT_* 环境变量前缀)。"""
max_rules = get_xfa_split_max_rules_per_set()
if len(self.rules) > max_rules:
raise ValueError(f'rules exceed max {max_rules}')
@@ -330,14 +351,16 @@ def split_rule_content_fingerprint(rule_set: XfaSplitRuleSet | dict[str, Any]) -
核心逻辑:只冻结 matcher 与 normalization;segment 的 Schema 映射字段不属于拆分逻辑,
后续绑定或解绑目标字段不得取消已确认状态。
【重要】:XFA 版指纹实现独立保留,不直接调用共享核心 base_split_content_fingerprint。
原因:未来若共享核心为 Vendor Comments 增加 relation_capture 字段纳入指纹计算,
此处必须保持 XFA 既有指纹与历史 Profile 校验和完全一致,避免发布确认状态误判。
Args:
rule_set: 模型或 dict。
Returns:
稳定 JSON 字符串指纹素材(调用方可再 hash)。
"""
import json
if isinstance(rule_set, XfaSplitRuleSet):
payload = rule_set.model_dump(mode='json', by_alias=True)
else:
@@ -2,39 +2,43 @@
services/shipping_notice/document_layout/xfa_split_rule_engine.py
用途:按冻结优先级执行 XFA 字段拆分——prefix > regex > position > unmatched。
依赖:xfa_split_rule_contract、xfa_safe_regex、concurrent.futures。
依赖:xfa_split_rule_contract(XfaSplitRuleSet extends BaseSplitRuleSet)、
field_split_core(execute_base_split_rule_set 共享核心执行)、
xfa_dataset(XfaLeafValue、mask_value_for_dto)。
逻辑:由预览 API 与正式提取调用;无网络、无脚本、无 LLM;
【阶段 1 架构】:对外 dataclass / 函数签名 100% 保持不变,
内部逻辑委托共享核心 field_split_core.execute_base_split_rule_set(),
转换 _CoreSegmentResult → XfaSplitSegmentResult 时显式丢弃 captured_relation
(Q16 方案 A:阶段 1 XFA 对外结果零字段变化);
逐行收集命中规则后按优先级决出唯一 segment;同优先级多个 mapped 命中 → needs_review;
全部候选命中写入 diagnostics;evidence_only 不写 Schema。
"""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from typing import Any
from app.services.shipping_notice.document_layout.field_split_core import (
CoreSplitDiagnostic,
_CoreSegmentResult,
_CoreSplitEngineResult,
execute_base_split_rule_set,
)
from app.services.shipping_notice.document_layout.xfa_dataset import XfaLeafValue
from app.services.shipping_notice.document_layout.xfa_safe_regex import (
SafeRegexError,
compile_safe_regex,
search_safe,
)
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
XFA_SPLIT_MATCHER_PRIORITY,
XfaSplitMatcher,
XfaSplitRule,
XfaSplitRuleSet,
get_xfa_split_max_input_length,
get_xfa_split_max_regex_groups,
get_xfa_split_max_regex_pattern_length,
get_xfa_split_regex_timeout_ms,
)
# ---------------------------------------------------------------------------
# 对外 dataclass——阶段 1 零字段变化(captured_relation 不出现在 XFA 对外结果)
# ---------------------------------------------------------------------------
@dataclass
class XfaSplitSegmentResult:
"""单段执行结果(含起止行号与证据文本)。"""
"""单段执行结果(含起止行号与证据文本)。阶段 1 不含 captured_relation(Q16 方案 A)。"""
segment_id: str
segment_code: str
@@ -75,223 +79,69 @@ class XfaSplitEngineResult:
rule_version: int | None = None
@dataclass
class _LineMatch:
"""单行候选命中。"""
rule: XfaSplitRule
matcher_type: str
priority: int
line_text: str
normalized_text: str
raw_line: str
# ---------------------------------------------------------------------------
# 适配层:共享核心 → XFA 对外结果(丢弃 captured_relation)
# ---------------------------------------------------------------------------
def _split_text_by_breaks(text: str, line_breaks: list[str]) -> list[str]:
def _core_segment_to_xfa(core: _CoreSegmentResult) -> XfaSplitSegmentResult:
"""
按声明的 line_breaks 切分文本(长分隔符优先)。
Args:
text: 原始文本。
line_breaks: 换行符列表。
Returns:
切分后的行列表(尚未 trim / 去空行)。
将共享核心单段结果转换为 XFA 对外结果。
【关键约束(Q16 方案 A)】:显式不传入 captured_relation,阶段 1 XFA 对外结果零字段变化。
"""
if not text:
return []
pattern = '|'.join(re.escape(item) for item in sorted(line_breaks, key=len, reverse=True))
if not pattern:
return [text]
return re.split(pattern, text)
def _apply_line_normalization(
lines: list[str],
*,
trim: bool,
remove_empty_lines: bool,
) -> list[str]:
"""对行列表应用 trim / 去空行。"""
out = list(lines)
if trim:
out = [item.strip() for item in out]
if remove_empty_lines:
out = [item for item in out if item]
return out
def _inventory_lines(raw_value: str, rule_set: XfaSplitRuleSet) -> list[str]:
"""
用规则集级 normalization 生成行清单。
核心逻辑:按 normalization.line_breaks 拆行并应用 trim / 去空行。
"""
norm = rule_set.normalization
lines = _split_text_by_breaks(raw_value or '', list(norm.line_breaks))
return _apply_line_normalization(
lines,
trim=bool(norm.trim),
remove_empty_lines=bool(norm.remove_empty_lines),
return XfaSplitSegmentResult(
segment_id=core.segment_id,
segment_code=core.segment_code,
display_name=core.display_name,
line_no=core.line_no,
line_end_no=core.line_end_no,
raw_text=core.raw_text,
normalized_text=core.normalized_text,
handling=core.handling,
target_field_id=core.target_field_id,
target_field_code=core.target_field_code,
rule_id=core.rule_id,
status=core.status,
matcher_type=core.matcher_type,
)
def _extract_prefix_value(line: str, matcher: XfaSplitMatcher) -> str | None:
def _core_diagnostic_to_xfa(core: CoreSplitDiagnostic) -> XfaSplitDiagnostic:
"""将共享核心诊断转换为 XFA 对外诊断。"""
return XfaSplitDiagnostic(
code=core.code,
message=core.message,
line_no=core.line_no,
field_code=core.field_code,
rule_ids=list(core.rule_ids),
)
def _core_result_to_xfa(core: _CoreSplitEngineResult) -> XfaSplitEngineResult:
"""
前缀匹配:标签 + 分隔符后的值。
Returns:
提取值;无法匹配时 None。
将共享核心完整引擎结果转换为 XFA 对外结果。
关键转换点:
1. rule_set_id → rule_id(XFA 对外使用 rule_id 键名,兼容历史调用);
2. 所有 segments / evidence_only_segments 丢弃 captured_relation;
3. mapped_fields 原样透传(key 结构完全一致)。
"""
label = str(matcher.value or '')
hay = line if matcher.case_sensitive else line.casefold()
needle = label if matcher.case_sensitive else label.casefold()
if not hay.startswith(needle):
return None
rest = line[len(label):]
for sep in matcher.separators:
if rest.startswith(sep):
return rest[len(sep):].strip()
stripped = rest.lstrip()
if stripped.startswith(sep):
return stripped[len(sep):].strip()
return None
xfa_segments = [_core_segment_to_xfa(s) for s in core.segments]
xfa_evidence_only = [_core_segment_to_xfa(s) for s in core.evidence_only_segments]
xfa_diagnostics = [_core_diagnostic_to_xfa(d) for d in core.diagnostics]
return XfaSplitEngineResult(
status=core.status,
segments=xfa_segments,
mapped_fields=dict(core.mapped_fields),
evidence_only_segments=xfa_evidence_only,
diagnostics=xfa_diagnostics,
rule_id=core.rule_set_id,
rule_version=core.rule_version,
)
def _regex_extract_value(line: str, matcher: XfaSplitMatcher) -> tuple[str | None, str | None]:
"""
正则捕获单行文本。
Returns:
(value, error_code);成功时 error_code 为 None。
"""
pattern = str(matcher.pattern or '')
timeout_ms = get_xfa_split_regex_timeout_ms()
max_len = get_xfa_split_max_regex_pattern_length()
max_groups = get_xfa_split_max_regex_groups()
try:
compiled = compile_safe_regex(
pattern,
case_sensitive=bool(matcher.case_sensitive),
max_length=max_len,
max_groups=max_groups,
)
matched = search_safe(compiled, line, timeout_ms=timeout_ms)
except SafeRegexError:
return None, 'regex_failed'
except TimeoutError:
return None, 'regex_timeout'
if not matched:
return None, 'regex_not_matched'
group = matcher.capture_group
try:
if group is None:
if matched.lastindex:
return str(matched.group(1) or '').strip(), None
return str(matched.group(0) or '').strip(), None
return str(matched.group(group) or '').strip(), None
except IndexError:
return None, 'regex_failed'
def _match_line(line_no: int, line: str, rule: XfaSplitRule) -> tuple[_LineMatch | None, str | None]:
"""
判断单条规则是否命中指定行。
Returns:
(match, error_code):命中时 error_code 为 None;未命中时 match 为 None。
"""
matcher = rule.matcher
priority = XFA_SPLIT_MATCHER_PRIORITY.get(matcher.type)
if priority is None:
return None, 'unknown_matcher'
if matcher.type == 'position':
if int(matcher.line_index or 0) != line_no:
return None, None
normalized = line.strip() if line else ''
return _LineMatch(
rule=rule,
matcher_type='position',
priority=priority,
line_text=line,
normalized_text=normalized,
raw_line=line,
), None
if matcher.type == 'prefix':
extracted = _extract_prefix_value(line, matcher)
if extracted is None:
return None, None
return _LineMatch(
rule=rule,
matcher_type='prefix',
priority=priority,
line_text=line,
normalized_text=extracted,
raw_line=line,
), None
if matcher.type == 'regex':
value, err = _regex_extract_value(line, matcher)
if err:
return None, err
if value is None:
return None, None
return _LineMatch(
rule=rule,
matcher_type='regex',
priority=priority,
line_text=line,
normalized_text=value,
raw_line=line,
), None
return None, 'unknown_matcher'
def _pick_line_winner(
line_no: int,
matches: list[_LineMatch],
diagnostics: list[XfaSplitDiagnostic],
) -> _LineMatch | None:
"""
按 prefix > regex > position 决出单行唯一胜出规则。
核心逻辑:同优先级多个 mapped 命中 → duplicate_line_match;不同优先级取最高优先级。
"""
if not matches:
return None
diagnostics.append(XfaSplitDiagnostic(
code='line_match_candidates',
message='All matcher hits for line recorded',
line_no=line_no,
rule_ids=[item.rule.rule_id for item in matches],
))
best_priority = min(item.priority for item in matches)
tier = [item for item in matches if item.priority == best_priority]
mapped_tier = [item for item in tier if item.rule.segment.handling == 'mapped']
if len(mapped_tier) >= 2:
diagnostics.append(XfaSplitDiagnostic(
code='duplicate_line_match',
message='Multiple mapped rules matched the same line at the same priority',
line_no=line_no,
rule_ids=[item.rule.rule_id for item in mapped_tier],
))
if len(tier) == 1:
return tier[0]
if len(mapped_tier) == 1:
return mapped_tier[0]
if len(mapped_tier) >= 2:
return sorted(mapped_tier, key=lambda item: item.rule.rule_id)[0]
return sorted(tier, key=lambda item: item.rule.rule_id)[0]
# ---------------------------------------------------------------------------
# 对外执行入口——签名 100% 不变
# ---------------------------------------------------------------------------
def execute_split_rule_set(
@@ -303,7 +153,11 @@ def execute_split_rule_set(
"""
对单个源字段原值执行拆分规则集。
核心逻辑:
【阶段 1 委托模式】:不重复实现逐行匹配逻辑,直接调用共享核心
execute_base_split_rule_set() 执行纯文本拆分,再通过适配层转换回 XFA
对外结果形状。XfaSplitRuleSet extends BaseSplitRuleSet,因此可直接透传。
核心逻辑(由共享核心保证字节级一致):
1. normalization.line_breaks 拆行;
2. 逐行收集命中规则,按 prefix > regex > position 决出唯一 segment;
3. 同优先级多个 mapped 命中 → duplicate_line_match / needs_review;
@@ -312,149 +166,18 @@ def execute_split_rule_set(
Args:
raw_value: 保留换行的原始叶子值。
rule_set: 已校验规则集。
rule_set: 已校验规则集(XfaSplitRuleSet extends BaseSplitRuleSet)。
lines: 可选预切分行(覆盖 normalization 结果)。
Returns:
XfaSplitEngineResult。
XfaSplitEngineResult——字段零变化,captured_relation 已丢弃。
"""
if len(raw_value or '') > get_xfa_split_max_input_length():
return XfaSplitEngineResult(
status='needs_review',
diagnostics=[XfaSplitDiagnostic(
code='input_too_long',
message='Split source value exceeds max input length',
)],
rule_id=rule_set.rule_set_id,
rule_version=rule_set.rule_version,
)
inventory = list(lines) if lines is not None else _inventory_lines(raw_value, rule_set)
diagnostics: list[XfaSplitDiagnostic] = []
segments: list[XfaSplitSegmentResult] = []
claimed_lines: set[int] = set()
# [STEP 1] 逐行匹配并按优先级决出胜出规则。
for line_no, line in enumerate(inventory, start=1):
matches: list[_LineMatch] = []
for rule in rule_set.rules:
outcome, error = _match_line(line_no, line, rule)
if error:
diagnostics.append(XfaSplitDiagnostic(
code=error,
message=f'Rule {rule.rule_id} regex failed on line {line_no}',
line_no=line_no,
field_code=rule.segment.target_field_code,
rule_ids=[rule.rule_id],
))
continue
if outcome is not None:
matches.append(outcome)
winner = _pick_line_winner(line_no, matches, diagnostics)
if winner is None:
continue
claimed_lines.add(line_no)
seg = winner.rule.segment
status = 'parsed'
if not str(winner.normalized_text).strip() and seg.handling == 'mapped':
status = 'needs_review'
diagnostics.append(XfaSplitDiagnostic(
code='mapped_value_empty',
message=f'Mapped segment {seg.segment_code} extracted empty value',
line_no=line_no,
field_code=seg.target_field_code,
rule_ids=[winner.rule.rule_id],
))
segments.append(XfaSplitSegmentResult(
segment_id=seg.segment_id,
segment_code=seg.segment_code,
display_name=seg.display_name,
line_no=line_no,
line_end_no=line_no,
raw_text=winner.raw_line,
normalized_text=winner.normalized_text,
handling=seg.handling,
target_field_id=seg.target_field_id,
target_field_code=seg.target_field_code,
rule_id=winner.rule.rule_id,
status=status,
matcher_type=winner.matcher_type,
))
# [STEP 2] 未匹配行。
for line_index, line in enumerate(inventory, start=1):
if line_index in claimed_lines:
continue
status = 'needs_review' if rule_set.unmatched_line_policy == 'needs_review' else 'parsed'
if status == 'needs_review':
diagnostics.append(XfaSplitDiagnostic(
code='unmatched_line',
message='Unmatched line requires review',
line_no=line_index,
))
segments.append(XfaSplitSegmentResult(
segment_id=f'unmatched-{line_index}',
segment_code=f'unmatched_line_{line_index}',
display_name=f'其他编码/{line_index}',
line_no=line_index,
line_end_no=line_index,
raw_text=line,
normalized_text=line.strip(),
handling='evidence_only',
target_field_id=None,
target_field_code=None,
rule_id='unmatched',
status=status,
matcher_type='unmatched',
))
# [STEP 3] 聚合正式字段。
mapped_fields: dict[str, str] = {}
field_sources: dict[str, list[str]] = {}
overall = 'parsed'
for item in segments:
if item.status == 'needs_review':
overall = 'needs_review'
if item.handling != 'mapped' or not item.target_field_code:
continue
code = item.target_field_code
field_sources.setdefault(code, []).append(item.rule_id)
if code in mapped_fields:
overall = 'needs_review'
diagnostics.append(XfaSplitDiagnostic(
code='same_field_multiple_segment',
message=f'Schema field {code} hit by multiple segments',
field_code=code,
rule_ids=list(field_sources[code]),
))
else:
mapped_fields[code] = item.normalized_text
for _code, sources in field_sources.items():
if len(sources) > 1 and rule_set.same_field_multiple_segment_policy == 'needs_review':
overall = 'needs_review'
if any(d.code == 'duplicate_line_match' for d in diagnostics):
if rule_set.duplicate_match_policy == 'needs_review':
overall = 'needs_review'
if any(d.code in {
'regex_timeout', 'regex_failed', 'mapped_value_empty', 'input_too_long',
} for d in diagnostics):
overall = 'needs_review'
evidence_only = [item for item in segments if item.handling == 'evidence_only']
return XfaSplitEngineResult(
status=overall,
segments=segments,
mapped_fields=mapped_fields,
evidence_only_segments=evidence_only,
diagnostics=diagnostics,
rule_id=rule_set.rule_set_id,
rule_version=rule_set.rule_version,
core_result = execute_base_split_rule_set(
raw_value=raw_value,
rule_set=rule_set,
lines=lines,
)
return _core_result_to_xfa(core_result)
def execute_split_on_leaf(
@@ -486,6 +209,8 @@ def project_split_result_safe(
核心逻辑:默认脱敏 mapped/segment 文本;仅当调用方已通过敏感读权限且
include_full_values=True 时返回 raw_text / 完整 mapped 值。
evidence_only_segments 避免与 segments 重复展示(置空列表)。
【阶段 1 零契约漂移】:JSON 键名(rule_id 而非 rule_set_id)、段结构、
诊断结构完全与历史一致。
Args:
result: 引擎输出。