feat(shipping-notice): 添加订单文档 Profile 的样本和审计管理功能,支持样本绑定、审计记录和模板预览,增强文档模板的管理和验证能力
This commit is contained in:
1 parent
d62f5107b2
commit
93777fd6df
63 files changed
+9707
-1491
No files matched your search
@@ -1004,7 +1004,11 @@ def save_rule(data: dict[str, Any], *, actor_id: int | None, rule_id: int | None
|
||||
|
||||
|
||||
def publish_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""发布草稿并写入不可变规则定义快照。"""
|
||||
"""发布草稿并写入不可变规则定义快照。
|
||||
|
||||
路由规则只声明库存源候选,允许引用已配置但暂时停用的 Source;实际
|
||||
库存 RPA 运行时仍由库存源门禁拒绝停用 Source,避免发布配置误触发 RPA。
|
||||
"""
|
||||
rule = db.session.get(ShippingInventoryRoutingRule, rule_id)
|
||||
if rule is None:
|
||||
raise NotFoundError('Routing rule not found', code='SHIPPING.INVENTORY_RULE_NOT_FOUND')
|
||||
@@ -1017,11 +1021,11 @@ def publish_rule(rule_id: int, *, actor_id: int | None) -> dict[str, Any]:
|
||||
for code in payload.get('source_codes', [])
|
||||
if str(code or '').strip()
|
||||
}
|
||||
enabled_codes = {
|
||||
existing_codes = {
|
||||
str(code).strip().upper()
|
||||
for (code,) in db.session.query(ShippingInventorySource.source_code).filter_by(enabled=True).all()
|
||||
for (code,) in db.session.query(ShippingInventorySource.source_code).all()
|
||||
}
|
||||
missing_codes = sorted(source_codes - enabled_codes)
|
||||
missing_codes = sorted(source_codes - existing_codes)
|
||||
if missing_codes:
|
||||
raise ValidationError(
|
||||
'Routing rule references unavailable inventory sources',
|
||||
|
||||
+627
-4
@@ -15,6 +15,7 @@ from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter
|
||||
from app.services.shipping_notice.document_layout.order_profile_extractors import extract_profile_field_value
|
||||
|
||||
|
||||
_LINE_NUMBER_PATTERN = re.compile(r'^(?:0{2,}\d+|\d{1,6})$')
|
||||
@@ -112,10 +113,371 @@ class CoordinateSubrowSuggestion(CoordinateReconstructionModel):
|
||||
role: Literal['main', 'continuation']
|
||||
row_offset: int = Field(ge=0)
|
||||
column_boundaries: list[float] = Field(min_length=2)
|
||||
y0: float = Field(ge=0, le=1)
|
||||
y1: float = Field(ge=0, le=1)
|
||||
column_samples: list[list[str]]
|
||||
suggested_field_codes: list[str | None]
|
||||
|
||||
|
||||
class CoordinateHeaderRegionSuggestion(CoordinateReconstructionModel):
|
||||
"""数据区之前的独立表头视觉行;只提供几何和复核文本,不自动绑定字段。"""
|
||||
|
||||
region: LayoutBBox
|
||||
text: str = ''
|
||||
fields: list['CoordinateHeaderFieldRegionSuggestion'] = Field(default_factory=list)
|
||||
|
||||
|
||||
class CoordinateHeaderFieldRegionSuggestion(CoordinateReconstructionModel):
|
||||
"""表头物理行内的单列文字块及其相对区域。"""
|
||||
|
||||
region: LayoutBBox
|
||||
text: str = ''
|
||||
|
||||
|
||||
class HeaderFieldSuggestion(CoordinateReconstructionModel):
|
||||
"""一个已配置表头字段区域的受控建议;不向调用方暴露字符坐标。"""
|
||||
|
||||
field_code: str | None = None
|
||||
text: str = ''
|
||||
confidence: Literal['confirmed_binding', 'exact_alias', 'unmapped'] = 'unmapped'
|
||||
|
||||
|
||||
class HeaderLayoutSuggestion(CoordinateReconstructionModel):
|
||||
"""单条表头物理行的候选结果,供管理员确认而非自动覆盖绑定。"""
|
||||
|
||||
layout_id: str
|
||||
fields: list[HeaderFieldSuggestion] = Field(default_factory=list)
|
||||
|
||||
|
||||
class CoordinateProfileLogicalRow(CoordinateReconstructionModel):
|
||||
"""v2 坐标模板重建的一条逻辑明细,字段仍由上层 Schema 规范化。"""
|
||||
|
||||
fields: dict[str, str] = Field(default_factory=dict)
|
||||
source_row_indices: list[int] = Field(min_length=1)
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
def suggest_header_layouts(
|
||||
*,
|
||||
characters: list[PositionedCharacter | dict[str, Any]],
|
||||
table_bbox: LayoutBBox | dict[str, Any],
|
||||
header_layouts: list[dict[str, Any]],
|
||||
schema_fields: list[dict[str, Any]],
|
||||
) -> list[HeaderLayoutSuggestion]:
|
||||
"""
|
||||
在管理员已划定的独立表头区域内给出严格别名建议。
|
||||
|
||||
AI/调用方触发时机:管理员点击“识别当前/全部表头”时调用。此函数仅以当前
|
||||
Schema 的 field_code、display_name、aliases 作精确规范化匹配;无唯一结果保持
|
||||
未映射,因此绝不会根据列位置覆盖管理员已确认字段绑定。
|
||||
|
||||
Args:
|
||||
characters: 表格范围内冻结的原生或 OCR 字符。
|
||||
table_bbox: 表格的绝对页面区域,用来把相对区域转换为绝对区域。
|
||||
header_layouts: 当前画布中的表头物理行及可选字段区域;未绑定时直接分析表头框。
|
||||
schema_fields: 当前冻结 Schema 的启用且允许坐标来源的字段。
|
||||
Returns:
|
||||
每个表头字段区域的脱敏文本和唯一精确别名建议,不含任何 bbox 或 glyph ID。
|
||||
"""
|
||||
bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox)
|
||||
glyphs = _table_glyphs(characters, bbox)
|
||||
aliases: dict[str, str | None] = {}
|
||||
for field in schema_fields:
|
||||
code = str(field.get('field_code') or '')
|
||||
for value in (code, field.get('display_name'), *(field.get('aliases') or [])):
|
||||
normalized = _normalized_header_text(str(value or ''))
|
||||
if not normalized:
|
||||
continue
|
||||
aliases[normalized] = code if aliases.get(normalized, code) == code else None
|
||||
suggestions: list[HeaderLayoutSuggestion] = []
|
||||
for layout in header_layouts:
|
||||
if not isinstance(layout, dict):
|
||||
continue
|
||||
fields: list[HeaderFieldSuggestion] = []
|
||||
configured_fields = [
|
||||
item for item in layout.get('field_regions') or []
|
||||
if isinstance(item, dict) and isinstance(item.get('region'), dict)
|
||||
]
|
||||
# 工作台以一个表头框表达一个语义字段;尚未绑定时直接分析表头框本身。
|
||||
candidate_fields = configured_fields or [{'field_code': None, 'region': layout.get('region')}]
|
||||
for field_region in candidate_fields:
|
||||
if not isinstance(field_region, dict) or not isinstance(field_region.get('region'), dict):
|
||||
continue
|
||||
region = _absolute_relative_region(bbox, field_region['region'])
|
||||
text = ''.join(glyph.text for _, glyph in glyphs if _inside_region(glyph.bbox, region)).strip()
|
||||
confirmed_code = str(field_region.get('field_code') or '').strip()
|
||||
code = confirmed_code if confirmed_code in {str(item.get('field_code') or '') for item in schema_fields} else aliases.get(_normalized_header_text(text))
|
||||
fields.append(HeaderFieldSuggestion(
|
||||
field_code=code,
|
||||
text=text[:160],
|
||||
confidence='confirmed_binding' if confirmed_code and code == confirmed_code else ('exact_alias' if code else 'unmapped'),
|
||||
))
|
||||
suggestions.append(HeaderLayoutSuggestion(layout_id=str(layout.get('layout_id') or ''), fields=fields))
|
||||
return suggestions
|
||||
|
||||
|
||||
def reconstruct_coordinate_profile_rows(
|
||||
*,
|
||||
characters: list[PositionedCharacter | dict[str, Any]],
|
||||
table_bbox: LayoutBBox | dict[str, Any],
|
||||
line_layouts: list[dict[str, Any]],
|
||||
table_region: dict[str, Any] | None = None,
|
||||
termination_rules: list[dict[str, Any]] | None = None,
|
||||
exclusion_regions: list[dict[str, Any]] | None = None,
|
||||
initial_fields: dict[str, str] | None = None,
|
||||
initial_next_offset: int = 0,
|
||||
) -> list[CoordinateProfileLogicalRow]:
|
||||
"""
|
||||
按 v2 物理行和字段区域合并逻辑明细,不使用 MinerU 的行列结果。
|
||||
|
||||
主行必须在其已绑定 ``line_no`` 区域中出现有效行号才启动明细;未满足此条件的
|
||||
视觉行不会被猜测为新行。随后只按连续 ``row_offset`` 消费 continuation,避免描述
|
||||
换行、合计或相邻无关表区静默混入当前订单行。
|
||||
"""
|
||||
bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox)
|
||||
ordered_layouts = sorted((item for item in line_layouts if isinstance(item, dict)), key=lambda item: item.get('row_offset', -1))
|
||||
if not ordered_layouts or [item.get('row_offset') for item in ordered_layouts] != list(range(len(ordered_layouts))):
|
||||
raise ValueError('coordinate profile line layouts must have contiguous offsets')
|
||||
region_centers = []
|
||||
for item in ordered_layouts:
|
||||
region = item.get('region')
|
||||
if isinstance(region, dict):
|
||||
region_centers.append((float(region['y0']) + float(region['y1'])) / 2)
|
||||
layout_order_valid = len(region_centers) != len(ordered_layouts) or all(
|
||||
right > left for left, right in zip(region_centers, region_centers[1:])
|
||||
)
|
||||
glyphs = _table_glyphs(characters, bbox)
|
||||
if isinstance(table_region, dict):
|
||||
configured_table_region = _absolute_relative_region(bbox, table_region)
|
||||
# 标注框描述可重复应用的行版式,纵向只是一条样例;整表候选不能因此被裁成单行。
|
||||
glyphs = [item for item in glyphs if _inside_horizontal_region(item[1].bbox, configured_table_region)]
|
||||
exclusions = [
|
||||
_absolute_relative_region(bbox, item)
|
||||
for item in (exclusion_regions or []) if isinstance(item, dict)
|
||||
]
|
||||
if exclusions:
|
||||
# Footer, signature and tax blocks are not candidate physical rows at all.
|
||||
glyphs = [item for item in glyphs if not any(_inside_region(item[1].bbox, region) for region in exclusions)]
|
||||
if not glyphs:
|
||||
return []
|
||||
|
||||
relative_y_rows = _reconstruct_relative_y_profile_rows(
|
||||
glyphs=glyphs,
|
||||
table_bbox=bbox,
|
||||
ordered_layouts=ordered_layouts,
|
||||
termination_rules=termination_rules or [],
|
||||
initial_fields=initial_fields,
|
||||
)
|
||||
if relative_y_rows is not None:
|
||||
return relative_y_rows
|
||||
|
||||
def values_for(band: list[tuple[int, PositionedCharacter]], layout: dict[str, Any]) -> tuple[dict[str, str], list[str]]:
|
||||
"""按当前物理行读取字段列;标注区域的纵向位置只表达子行版式,不限定绝对页坐标。"""
|
||||
values: dict[str, str] = {}
|
||||
issues: list[str] = []
|
||||
for field in layout.get('field_regions') or []:
|
||||
if not isinstance(field, dict) or not isinstance(field.get('region'), dict):
|
||||
continue
|
||||
code = str(field.get('field_code') or '')
|
||||
if not code:
|
||||
continue
|
||||
region = _absolute_relative_region(bbox, field['region'])
|
||||
text = _text_in_horizontal_region(band, region)
|
||||
if text:
|
||||
extracted = extract_profile_field_value(
|
||||
extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=text,
|
||||
)
|
||||
# Composite parsers are atomic: no partial output may contaminate a logical row.
|
||||
if extracted:
|
||||
for extracted_code, extracted_value in extracted.items():
|
||||
previous = values.get(extracted_code)
|
||||
if previous is not None and previous != extracted_value:
|
||||
issues.append(f'coordinate_profile_composite_conflict:{extracted_code}')
|
||||
else:
|
||||
values[extracted_code] = extracted_value
|
||||
return values, issues
|
||||
|
||||
results: list[CoordinateProfileLogicalRow] = []
|
||||
current: dict[str, str] | None = dict(initial_fields) if initial_fields else None
|
||||
sources: list[int] = []
|
||||
next_offset = initial_next_offset if current is not None else 0
|
||||
current_issues: list[str] = []
|
||||
|
||||
def flush() -> None:
|
||||
nonlocal current, sources, next_offset, current_issues
|
||||
if current is not None and (sources or initial_fields):
|
||||
results.append(CoordinateProfileLogicalRow(fields=current, source_row_indices=sources, issues=current_issues))
|
||||
current, sources, next_offset, current_issues = None, [], 0, []
|
||||
|
||||
for row_index, band in enumerate(_group_visual_rows(glyphs)):
|
||||
text = ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)).strip()
|
||||
if _SUMMARY_PATTERN.search(text) or _matches_termination_rule(band, bbox, termination_rules or []):
|
||||
flush()
|
||||
break
|
||||
if _DELETED_PATTERN.fullmatch(re.sub(r'\s+', '', text)):
|
||||
# Deletion markers apply only to the immediately preceding started record.
|
||||
# Do not emit it as a partial row and do not guess an association when no
|
||||
# main row is active.
|
||||
current, sources, next_offset, current_issues = None, [], 0, []
|
||||
continue
|
||||
main_values, main_issues = values_for(band, ordered_layouts[0])
|
||||
line_no = re.sub(r'\s+', '', main_values.get('line_no', ''))
|
||||
if _LINE_NUMBER_PATTERN.fullmatch(line_no):
|
||||
flush()
|
||||
current, sources, next_offset, current_issues = main_values, [row_index], 1, main_issues
|
||||
continue
|
||||
if current is None or next_offset >= len(ordered_layouts):
|
||||
continue
|
||||
if not layout_order_valid:
|
||||
current_issues.append('coordinate_profile_layout_region_mismatch')
|
||||
flush()
|
||||
continue
|
||||
continuation, continuation_issues = values_for(band, ordered_layouts[next_offset])
|
||||
if not continuation:
|
||||
# Once a logical row has started, its declared physical rows must be consecutive.
|
||||
# Continuing after an unexpected region would silently mix two visual records.
|
||||
if continuation_issues:
|
||||
current_issues.extend(continuation_issues)
|
||||
flush()
|
||||
continue
|
||||
for code, value in continuation.items():
|
||||
previous = current.get(code, '').strip()
|
||||
if previous and previous != value:
|
||||
current_issues.append(f'coordinate_profile_composite_conflict:{code}')
|
||||
else:
|
||||
current[code] = value
|
||||
sources.append(row_index)
|
||||
current_issues.extend(continuation_issues)
|
||||
next_offset += 1
|
||||
flush()
|
||||
return results
|
||||
|
||||
|
||||
def _reconstruct_relative_y_profile_rows(
|
||||
*,
|
||||
glyphs: list[tuple[int, PositionedCharacter]],
|
||||
table_bbox: LayoutBBox,
|
||||
ordered_layouts: list[dict[str, Any]],
|
||||
termination_rules: list[dict[str, Any]],
|
||||
initial_fields: dict[str, str] | None,
|
||||
) -> list[CoordinateProfileLogicalRow] | None:
|
||||
"""
|
||||
将单个多视觉行物理框按父行内相对 Y 投影到每条重复明细。
|
||||
|
||||
只有字段框明确切分了父物理行的纵向子带时才启用;旧模板的整高字段和多物理行
|
||||
row_offset 继续走原有逐视觉行算法。运行时先用 ``line_no`` 找到每条明细起点,再把
|
||||
样例字段的相对 Y 映射到相邻起点之间,避免料号尾数污染下方数量、单位和日期。
|
||||
"""
|
||||
if initial_fields or len(ordered_layouts) != 1:
|
||||
return None
|
||||
layout = ordered_layouts[0]
|
||||
parent = layout.get('region')
|
||||
fields = [
|
||||
field for field in (layout.get('field_regions') or [])
|
||||
if isinstance(field, dict) and isinstance(field.get('region'), dict)
|
||||
]
|
||||
if not isinstance(parent, dict) or not _has_relative_y_subregions(parent, fields):
|
||||
return None
|
||||
line_field = next((field for field in fields if str(field.get('field_code') or '') == 'line_no'), None)
|
||||
if line_field is None:
|
||||
return None
|
||||
bands = _group_visual_rows(glyphs)
|
||||
usable_bands: list[tuple[int, list[tuple[int, PositionedCharacter]]]] = []
|
||||
for row_index, band in enumerate(bands):
|
||||
text = ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)).strip()
|
||||
if _SUMMARY_PATTERN.search(text) or _matches_termination_rule(band, table_bbox, termination_rules):
|
||||
break
|
||||
usable_bands.append((row_index, band))
|
||||
if not usable_bands:
|
||||
return []
|
||||
|
||||
line_region = _absolute_relative_region(table_bbox, line_field['region'])
|
||||
anchors: list[int] = []
|
||||
for index, (_, band) in enumerate(usable_bands):
|
||||
line_text = re.sub(r'\s+', '', _text_in_horizontal_region(band, line_region))
|
||||
if _LINE_NUMBER_PATTERN.fullmatch(line_text):
|
||||
anchors.append(index)
|
||||
if not anchors:
|
||||
return []
|
||||
|
||||
sample_end = anchors[1] if len(anchors) > 1 else len(usable_bands)
|
||||
sample_record = usable_bands[anchors[0]:sample_end]
|
||||
field_band_indices = _calibrate_field_band_indices(
|
||||
fields=fields, sample_record=sample_record, table_bbox=table_bbox,
|
||||
)
|
||||
results: list[CoordinateProfileLogicalRow] = []
|
||||
for anchor_index, start in enumerate(anchors):
|
||||
end = anchors[anchor_index + 1] if anchor_index + 1 < len(anchors) else len(usable_bands)
|
||||
record = usable_bands[start:end]
|
||||
if any(_DELETED_PATTERN.fullmatch(re.sub(
|
||||
r'\s+', '', ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)),
|
||||
)) for _, band in record):
|
||||
continue
|
||||
values: dict[str, str] = {}
|
||||
issues: list[str] = []
|
||||
matched_bands, alignment_issues = _match_field_band_groups(
|
||||
fields=fields,
|
||||
record=record,
|
||||
expected_indices=field_band_indices,
|
||||
table_bbox=table_bbox,
|
||||
)
|
||||
issues.extend(alignment_issues)
|
||||
for field in fields:
|
||||
code = str(field.get('field_code') or '')
|
||||
if not code:
|
||||
continue
|
||||
band_index = matched_bands.get(id(field))
|
||||
if band_index is None:
|
||||
continue
|
||||
region = _absolute_relative_region(table_bbox, field['region'])
|
||||
raw = _text_in_horizontal_region(record[band_index][1], region)
|
||||
if not raw:
|
||||
continue
|
||||
extracted = extract_profile_field_value(
|
||||
extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=raw,
|
||||
)
|
||||
for extracted_code, extracted_value in extracted.items():
|
||||
previous = values.get(extracted_code)
|
||||
if previous is not None and previous != extracted_value:
|
||||
issues.append(f'coordinate_profile_composite_conflict:{extracted_code}')
|
||||
else:
|
||||
values[extracted_code] = extracted_value
|
||||
line_no = re.sub(r'\s+', '', values.get('line_no', ''))
|
||||
if _LINE_NUMBER_PATTERN.fullmatch(line_no):
|
||||
results.append(CoordinateProfileLogicalRow(
|
||||
fields=values,
|
||||
source_row_indices=[row_index for row_index, _ in record],
|
||||
issues=issues,
|
||||
))
|
||||
return results
|
||||
|
||||
|
||||
def _matches_termination_rule(
|
||||
band: list[tuple[int, PositionedCharacter]], table_bbox: LayoutBBox, rules: list[dict[str, Any]],
|
||||
) -> bool:
|
||||
"""仅在管理员声明的区域和文字锚点同时命中时停止,避免条款文本误伤明细。"""
|
||||
text = ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)).strip()
|
||||
for rule in rules:
|
||||
anchor = rule.get('anchor') if isinstance(rule, dict) else None
|
||||
if not isinstance(anchor, dict):
|
||||
continue
|
||||
expected = str(anchor.get('text') or '').strip()
|
||||
if not expected:
|
||||
continue
|
||||
region = anchor.get('region')
|
||||
if isinstance(region, dict):
|
||||
absolute = _absolute_relative_region(table_bbox, region)
|
||||
center_y = sum((glyph.bbox.y0 + glyph.bbox.y1) / 2 for _, glyph in band) / len(band)
|
||||
if not absolute.y0 <= center_y <= absolute.y1:
|
||||
continue
|
||||
if str(anchor.get('match_mode') or 'contains') == 'exact':
|
||||
if text.casefold() == expected.casefold():
|
||||
return True
|
||||
elif expected.casefold() in text.casefold():
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def suggest_multi_subrow_layouts(
|
||||
*,
|
||||
characters: list[PositionedCharacter | dict[str, Any]],
|
||||
@@ -171,10 +533,17 @@ def suggest_multi_subrow_layouts(
|
||||
boundaries, column_samples, line_column = _suggest_band_boundaries(
|
||||
samples, bbox, detect_line_number=row_offset == 0,
|
||||
)
|
||||
# 列边界可聚合多条明细,但纵向样例必须来自同一条记录;否则会把每种
|
||||
# 子行拉伸到整张表高度,造成主行与续行区域互相重叠。
|
||||
band_glyphs = [glyph for _, glyph in samples[0]]
|
||||
y0 = min(glyph.bbox.y0 for glyph in band_glyphs)
|
||||
y1 = max(glyph.bbox.y1 for glyph in band_glyphs)
|
||||
suggestions.append(CoordinateSubrowSuggestion(
|
||||
role='main' if row_offset == 0 else 'continuation',
|
||||
row_offset=row_offset,
|
||||
column_boundaries=boundaries,
|
||||
y0=max(0, (y0 - bbox.y0) / (bbox.y1 - bbox.y0)),
|
||||
y1=min(1, (y1 - bbox.y0) / (bbox.y1 - bbox.y0)),
|
||||
column_samples=column_samples,
|
||||
suggested_field_codes=[
|
||||
'line_no' if row_offset == 0 and index == line_column else None
|
||||
@@ -184,6 +553,66 @@ def suggest_multi_subrow_layouts(
|
||||
return suggestions
|
||||
|
||||
|
||||
def suggest_header_regions(
|
||||
*,
|
||||
characters: list[PositionedCharacter | dict[str, Any]],
|
||||
table_bbox: LayoutBBox | dict[str, Any],
|
||||
) -> list[CoordinateHeaderRegionSuggestion]:
|
||||
"""从首条明细前识别独立表头视觉行;混有业务值的行保持人工复核。"""
|
||||
bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox)
|
||||
glyphs = _table_glyphs(characters, bbox)
|
||||
width = bbox.x1 - bbox.x0
|
||||
height = bbox.y1 - bbox.y0
|
||||
if not glyphs or width <= 0 or height <= 0:
|
||||
return []
|
||||
result: list[CoordinateHeaderRegionSuggestion] = []
|
||||
for band in _group_visual_rows(glyphs):
|
||||
if _band_starts_item(band, bbox):
|
||||
break
|
||||
text = ' '.join(value for value in (
|
||||
''.join(glyph.text for _, glyph in run).strip()
|
||||
for run in _group_text_runs(sorted(band, key=lambda item: item[1].bbox.x0))
|
||||
) if value)
|
||||
if not _looks_like_header(text):
|
||||
continue
|
||||
band_bbox = _band_bbox(band)
|
||||
field_runs = [
|
||||
run for run in _group_text_runs(sorted(band, key=lambda item: item[1].bbox.x0))
|
||||
if ''.join(glyph.text for _, glyph in run).strip()
|
||||
]
|
||||
run_boxes = [_run_bbox(run) for run in field_runs]
|
||||
field_regions: list[CoordinateHeaderFieldRegionSuggestion] = []
|
||||
for field_index, run in enumerate(field_runs):
|
||||
run_text = ''.join(glyph.text for _, glyph in run).strip()
|
||||
if not run_text:
|
||||
continue
|
||||
run_bbox = _run_bbox(run)
|
||||
# Expand each text token to its column slot using neighboring midpoints;
|
||||
# this keeps the header field aligned with the detail column below it.
|
||||
left = band_bbox.x0 if field_index == 0 else (run_boxes[field_index - 1].x1 + run_bbox.x0) / 2
|
||||
right = band_bbox.x1 if field_index == len(run_boxes) - 1 else (run_bbox.x1 + run_boxes[field_index + 1].x0) / 2
|
||||
field_regions.append(CoordinateHeaderFieldRegionSuggestion(
|
||||
region={
|
||||
'x0': max(0, (left - bbox.x0) / width),
|
||||
'y0': max(0, (run_bbox.y0 - bbox.y0) / height),
|
||||
'x1': min(1, (right - bbox.x0) / width),
|
||||
'y1': min(1, (run_bbox.y1 - bbox.y0) / height),
|
||||
},
|
||||
text=run_text[:160],
|
||||
))
|
||||
result.append(CoordinateHeaderRegionSuggestion(
|
||||
region={
|
||||
'x0': max(0, (band_bbox.x0 - bbox.x0) / width),
|
||||
'y0': max(0, (band_bbox.y0 - bbox.y0) / height),
|
||||
'x1': min(1, (band_bbox.x1 - bbox.x0) / width),
|
||||
'y1': min(1, (band_bbox.y1 - bbox.y0) / height),
|
||||
},
|
||||
text=text[:160],
|
||||
fields=field_regions,
|
||||
))
|
||||
return result
|
||||
|
||||
|
||||
def reconstruct_table_from_positioned_text(
|
||||
*,
|
||||
characters: list[PositionedCharacter | dict[str, Any]],
|
||||
@@ -393,9 +822,18 @@ def _band_field_values(
|
||||
|
||||
|
||||
def _looks_like_header(text: str) -> bool:
|
||||
"""以有限英文表头词识别数据区之前的多层表头,避免把表头并入首条明细。"""
|
||||
"""以有限英文表头词识别数据区之前的多层表头,兼容 PDF 丢失词间空格。"""
|
||||
words = set(re.findall(r'[a-z]+', text.lower()))
|
||||
return len(words & _HEADER_TERMS) >= 2
|
||||
matched = words & _HEADER_TERMS
|
||||
# 部分 PDF 字符层会把 ``ITEM NO``、``UNIT PRICE`` 合并成 ITEMNO、UNITPRICE。
|
||||
# 仅对已知表头词做子串恢复,且仍要求至少两个不同词,避免普通业务值误命中。
|
||||
compact_words = {word for word in words if len(word) >= 5}
|
||||
matched.update(
|
||||
term
|
||||
for term in _HEADER_TERMS
|
||||
if len(term) >= 3 and any(term in word for word in compact_words)
|
||||
)
|
||||
return len(matched) >= 2
|
||||
|
||||
|
||||
def _band_starts_item(
|
||||
@@ -480,6 +918,182 @@ def _table_glyphs(
|
||||
return sorted(glyphs, key=lambda item: ((item[1].bbox.y0 + item[1].bbox.y1) / 2, item[1].bbox.x0, item[0]))
|
||||
|
||||
|
||||
def _absolute_relative_region(table_bbox: LayoutBBox, relative: dict[str, Any]) -> LayoutBBox:
|
||||
"""把 Profile 的 0..1 相对区域投影到当前页面绝对坐标,适配页面缩放。"""
|
||||
x0, y0, x1, y1 = (float(relative[key]) for key in ('x0', 'y0', 'x1', 'y1'))
|
||||
return LayoutBBox(
|
||||
x0=table_bbox.x0 + (table_bbox.x1 - table_bbox.x0) * x0,
|
||||
y0=table_bbox.y0 + (table_bbox.y1 - table_bbox.y0) * y0,
|
||||
x1=table_bbox.x0 + (table_bbox.x1 - table_bbox.x0) * x1,
|
||||
y1=table_bbox.y0 + (table_bbox.y1 - table_bbox.y0) * y1,
|
||||
)
|
||||
|
||||
|
||||
def _inside_region(glyph_bbox: LayoutBBox, region: LayoutBBox) -> bool:
|
||||
"""仅收集中心在管理员框选区域内的字符,边缘字符不跨区域复制。"""
|
||||
return region.x0 <= (glyph_bbox.x0 + glyph_bbox.x1) / 2 <= region.x1 and region.y0 <= (glyph_bbox.y0 + glyph_bbox.y1) / 2 <= region.y1
|
||||
|
||||
|
||||
def _inside_horizontal_region(glyph_bbox: LayoutBBox, region: LayoutBBox) -> bool:
|
||||
"""仅按标注框横向范围筛选字符,使同一行版式可应用到整张表的重复明细。"""
|
||||
return region.x0 <= (glyph_bbox.x0 + glyph_bbox.x1) / 2 <= region.x1
|
||||
|
||||
|
||||
def _has_relative_y_subregions(parent: dict[str, Any], fields: list[dict[str, Any]]) -> bool:
|
||||
"""判断字段是否在父物理行内提供了可用于投影的纵向子带。"""
|
||||
parent_y0, parent_y1 = float(parent['y0']), float(parent['y1'])
|
||||
if parent_y1 <= parent_y0:
|
||||
return False
|
||||
tolerance = max(1e-6, (parent_y1 - parent_y0) * .02)
|
||||
return any(
|
||||
float(field['region']['y0']) > parent_y0 + tolerance
|
||||
or float(field['region']['y1']) < parent_y1 - tolerance
|
||||
for field in fields
|
||||
)
|
||||
|
||||
|
||||
def _calibrate_field_band_indices(
|
||||
*,
|
||||
fields: list[dict[str, Any]],
|
||||
sample_record: list[tuple[int, list[tuple[int, PositionedCharacter]]]],
|
||||
table_bbox: LayoutBBox,
|
||||
) -> dict[int, int]:
|
||||
"""用样例字段框与首条明细真实字符的 Y 重叠校准视觉 band offset。"""
|
||||
result: dict[int, int] = {}
|
||||
band_boxes = [_band_bbox(band) for _, band in sample_record]
|
||||
for field in fields:
|
||||
region = _absolute_relative_region(table_bbox, field['region'])
|
||||
overlaps = [max(0.0, min(region.y1, box.y1) - max(region.y0, box.y0)) for box in band_boxes]
|
||||
best_overlap = max(overlaps, default=0.0)
|
||||
if best_overlap > 0:
|
||||
candidates = [index for index, overlap in enumerate(overlaps) if overlap == best_overlap]
|
||||
else:
|
||||
center = (region.y0 + region.y1) / 2
|
||||
distances = [abs(center - (box.y0 + box.y1) / 2) for box in band_boxes]
|
||||
nearest = min(distances, default=0.0)
|
||||
candidates = [index for index, distance in enumerate(distances) if distance == nearest]
|
||||
result[id(field)] = candidates[0] if candidates else 0
|
||||
return result
|
||||
|
||||
|
||||
def _match_field_band_groups(
|
||||
*,
|
||||
fields: list[dict[str, Any]],
|
||||
record: list[tuple[int, list[tuple[int, PositionedCharacter]]]],
|
||||
expected_indices: dict[int, int],
|
||||
table_bbox: LayoutBBox,
|
||||
) -> tuple[dict[int, int], list[str]]:
|
||||
"""将样例纵向字段组单调对齐到运行时 bands;额外换行可插入但组顺序不可倒退。"""
|
||||
if not record:
|
||||
return {}, []
|
||||
groups: dict[int, list[dict[str, Any]]] = {}
|
||||
for field in fields:
|
||||
groups.setdefault(expected_indices[id(field)], []).append(field)
|
||||
matched: dict[int, int] = {}
|
||||
issues: list[str] = []
|
||||
previous_index = -1
|
||||
for expected_index, group_fields in sorted(groups.items()):
|
||||
if any(str(field.get('field_code') or '') == 'line_no' for field in group_fields):
|
||||
selected_index = 0
|
||||
else:
|
||||
candidates: list[tuple[float, int]] = []
|
||||
for index in range(previous_index + 1, len(record)):
|
||||
score = 0.0
|
||||
evidence_count = 0
|
||||
for field in group_fields:
|
||||
region = _absolute_relative_region(table_bbox, field['region'])
|
||||
raw = _text_in_horizontal_region(record[index][1], region)
|
||||
if not raw:
|
||||
continue
|
||||
evidence_count += 1
|
||||
score += _profile_field_band_score(
|
||||
raw=raw,
|
||||
field_code=str(field.get('field_code') or ''),
|
||||
extractor_key=str(field.get('extractor_key') or 'direct'),
|
||||
)
|
||||
if evidence_count:
|
||||
score -= abs(index - expected_index) * .2
|
||||
candidates.append((score, index))
|
||||
if not candidates:
|
||||
continue
|
||||
candidates.sort(reverse=True)
|
||||
best_score, selected_index = candidates[0]
|
||||
if len(candidates) > 1 and best_score - candidates[1][0] < .25:
|
||||
codes = ','.join(sorted(str(field.get('field_code') or '') for field in group_fields))
|
||||
issues.append(f'coordinate_profile_field_band_ambiguous:{codes}')
|
||||
continue
|
||||
for field in group_fields:
|
||||
matched[id(field)] = selected_index
|
||||
previous_index = selected_index
|
||||
return matched, issues
|
||||
|
||||
|
||||
def _profile_field_band_score(*, raw: str, field_code: str, extractor_key: str) -> float:
|
||||
"""以注册解析器和既有有限字段形态评分,禁止自由规则或模板专用特例。"""
|
||||
extracted = extract_profile_field_value(extractor_key=extractor_key, field_code=field_code, raw=raw)
|
||||
if not extracted:
|
||||
return -1.0
|
||||
score = 1.0 + _field_content_score(raw, field_code)
|
||||
if field_code in {'part_number', 'customer_part_number', 'aws_part_number'}:
|
||||
compact = re.sub(r'\s+', '', raw)
|
||||
if re.search(r'\s', raw):
|
||||
score -= .75
|
||||
if re.search(r'\d|[._/-]', compact):
|
||||
score += .5
|
||||
return score
|
||||
|
||||
|
||||
def _text_in_region(
|
||||
band: list[tuple[int, PositionedCharacter]], region: LayoutBBox,
|
||||
) -> str:
|
||||
"""按 PDF 字符间距恢复视觉空格,避免原生文本层省略空格导致字段粘连。"""
|
||||
selected = sorted(
|
||||
(item for item in band if _inside_region(item[1].bbox, region)),
|
||||
key=lambda item: (item[1].bbox.x0, item[0]),
|
||||
)
|
||||
if not selected:
|
||||
return ''
|
||||
widths = [glyph.bbox.x1 - glyph.bbox.x0 for _, glyph in selected]
|
||||
gap_limit = max(1.5, median(widths) * 0.65)
|
||||
result: list[str] = []
|
||||
for index, (_, glyph) in enumerate(selected):
|
||||
if index:
|
||||
previous = selected[index - 1][1]
|
||||
gap = glyph.bbox.x0 - previous.bbox.x1
|
||||
if gap > gap_limit and not result[-1].isspace() and not glyph.text.isspace():
|
||||
result.append(' ')
|
||||
result.append(glyph.text)
|
||||
return ''.join(result).strip()
|
||||
|
||||
|
||||
def _text_in_horizontal_region(
|
||||
band: list[tuple[int, PositionedCharacter]], region: LayoutBBox,
|
||||
) -> str:
|
||||
"""在当前视觉行内按字段横向边界恢复文本,忽略标注样例的绝对纵向位置。"""
|
||||
selected = sorted(
|
||||
(item for item in band if _inside_horizontal_region(item[1].bbox, region)),
|
||||
key=lambda item: (item[1].bbox.x0, item[0]),
|
||||
)
|
||||
if not selected:
|
||||
return ''
|
||||
widths = [glyph.bbox.x1 - glyph.bbox.x0 for _, glyph in selected]
|
||||
gap_limit = max(1.5, median(widths) * 0.65)
|
||||
result: list[str] = []
|
||||
for index, (_, glyph) in enumerate(selected):
|
||||
if index:
|
||||
previous = selected[index - 1][1]
|
||||
gap = glyph.bbox.x0 - previous.bbox.x1
|
||||
if gap > gap_limit and not result[-1].isspace() and not glyph.text.isspace():
|
||||
result.append(' ')
|
||||
result.append(glyph.text)
|
||||
return ''.join(result).strip()
|
||||
|
||||
|
||||
def _normalized_header_text(value: str) -> str:
|
||||
"""标准化表头候选,允许空格、斜线和标点差异但不执行模糊语义猜测。"""
|
||||
return re.sub(r'[^a-z0-9]+', '', value.lower())
|
||||
|
||||
|
||||
def _group_visual_rows(glyphs: list[tuple[int, PositionedCharacter]]) -> list[list[tuple[int, PositionedCharacter]]]:
|
||||
"""按自适应 y 阈值形成视觉行,阈值来自字体高度而不是固定页面像素。"""
|
||||
heights = [glyph.bbox.y1 - glyph.bbox.y0 for _, glyph in glyphs]
|
||||
@@ -522,6 +1136,15 @@ def _run_bbox(run: list[tuple[int, PositionedCharacter]]) -> LayoutBBox:
|
||||
)
|
||||
|
||||
|
||||
def _band_bbox(band: list[tuple[int, PositionedCharacter]]) -> LayoutBBox:
|
||||
"""汇总一条视觉 band 的字符边界,供样例字段框校准真实子行。"""
|
||||
boxes = [glyph.bbox for _, glyph in band]
|
||||
return LayoutBBox(
|
||||
x0=min(item.x0 for item in boxes), y0=min(item.y0 for item in boxes),
|
||||
x1=max(item.x1 for item in boxes), y1=max(item.y1 for item in boxes),
|
||||
)
|
||||
|
||||
|
||||
def _assign_column(
|
||||
bbox: LayoutBBox,
|
||||
text: str,
|
||||
@@ -569,11 +1192,11 @@ def _field_content_score(text: str, field_code: str | None) -> float:
|
||||
compact = value.replace(',', '').replace(' ', '')
|
||||
if field_code == 'line_no':
|
||||
return 1.0 if _LINE_NUMBER_PATTERN.fullmatch(compact) else -1.0
|
||||
if field_code in {'qty', 'unit_price', 'amount'}:
|
||||
if field_code in {'qty', 'unit_price', 'amount', 'line_amount_before_tax', 'line_amount_with_tax'}:
|
||||
return 1.0 if re.fullmatch(r'[-+]?\d+(?:\.\d+)?', compact) else -1.0
|
||||
if field_code == 'uom':
|
||||
return 1.0 if re.fullmatch(r'[A-Za-z]{1,6}', compact) else -0.5
|
||||
if field_code == 'required_date':
|
||||
if field_code in {'required_date', 'requested_receipt_date'}:
|
||||
return 1.0 if re.fullmatch(r'\d{1,4}[-/]\d{1,2}[-/]\d{1,4}', compact) else -0.5
|
||||
if field_code in {'part_number', 'customer_part_number', 'aws_part_number'}:
|
||||
return 0.75 if re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._/-]{2,}', compact) else 0.0
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/order_profile.py
|
||||
|
||||
用途:定义订单文档模板级解析 Profile 纯契约,覆盖全局 Schema 无法表达的模板列语义。
|
||||
依赖:Pydantic、HTML 网格、订单字段规则和既有 TEMP 复合料号规则。
|
||||
逻辑:普通 Profile 按精确表头指纹匹配;坐标 Profile 先合并物理续行并生成稳定虚拟表头,再按固定列执行注册解析器。
|
||||
用途:定义订单文档坐标模板 v2 的纯契约和受控字段绑定。
|
||||
依赖:Pydantic、坐标 bbox 契约、订单字段规则和已注册解析器。
|
||||
逻辑:管理员保存稳定锚点、相对区域和 field_code 绑定;运行时匹配器与坐标解析器只消费该不可变定义。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -32,8 +32,8 @@ from app.services.shipping_notice.order_schema.table_contract import (
|
||||
)
|
||||
|
||||
|
||||
ORDER_PROFILE_VERSION = 'shipping_order_document_profile.v1'
|
||||
PROFILE_EXTRACTORS = frozenset({'direct', 'temp_internal_parts'})
|
||||
ORDER_PROFILE_VERSION = 'order_coordinate_profile.v2'
|
||||
PROFILE_EXTRACTORS = frozenset({'direct', 'temp_internal_parts', 'quantity_uom', 'amount_currency', 'price_currency'})
|
||||
HEADER_LINE_ITEM_VALUE_PATTERN = re.compile(
|
||||
r'\b(?:item|line)\s*(?:no\.?|number|#)?\s*[:#-]?\s*0{2,}\d+\b',
|
||||
re.IGNORECASE,
|
||||
@@ -46,8 +46,235 @@ class OrderProfileModel(BaseModel):
|
||||
model_config = ConfigDict(extra='forbid', validate_assignment=True)
|
||||
|
||||
|
||||
class RelativeRegion(OrderProfileModel):
|
||||
"""表示页面或表格内的归一化矩形;绝不持久化浏览器像素。"""
|
||||
|
||||
x0: float = Field(ge=0, le=1)
|
||||
y0: float = Field(ge=0, le=1)
|
||||
x1: float = Field(ge=0, le=1)
|
||||
y1: float = Field(ge=0, le=1)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_area(self) -> 'RelativeRegion':
|
||||
"""拒绝零面积和反向区域,避免运行时存在不确定的坐标归属。"""
|
||||
if self.x0 >= self.x1 or self.y0 >= self.y1:
|
||||
raise ValueError('relative region must have positive area')
|
||||
return self
|
||||
|
||||
|
||||
class AnchorRule(OrderProfileModel):
|
||||
"""定义模板匹配或行启动使用的稳定静态文字锚点。"""
|
||||
|
||||
anchor_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
text: str = Field(min_length=1, max_length=160)
|
||||
match_mode: Literal['exact', 'contains'] = 'contains'
|
||||
region: RelativeRegion | None = None
|
||||
minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate'
|
||||
|
||||
|
||||
class FieldRegion(OrderProfileModel):
|
||||
"""将一个管理员确认的坐标区域绑定至稳定 Schema field_code。"""
|
||||
|
||||
field_id: str = Field(min_length=1, max_length=128)
|
||||
field_code: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
region: RelativeRegion
|
||||
extractor_key: Literal['direct', 'temp_internal_parts', 'quantity_uom', 'amount_currency', 'price_currency'] = 'direct'
|
||||
allowed_sources: list[Literal['pdf_coordinate', 'ocr_coordinate']] = Field(min_length=1)
|
||||
minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate'
|
||||
target_fields: list[dict[str, str]] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_extractor_source(self) -> 'FieldRegion':
|
||||
"""限制为后端注册的解析器和坐标来源,禁止正则、脚本或 Prompt 注入。"""
|
||||
if len(self.allowed_sources) != len(set(self.allowed_sources)):
|
||||
raise ValueError('field region sources must be unique')
|
||||
if self.target_fields:
|
||||
codes = [str(item.get('field_code') or '') for item in self.target_fields]
|
||||
if len(codes) != len(set(codes)) or self.field_code not in codes:
|
||||
raise ValueError('field region targets must be unique and include field_code')
|
||||
return self
|
||||
|
||||
|
||||
class HeaderLayout(OrderProfileModel):
|
||||
"""描述一条独立表头物理行;它只提供校准和字段建议证据。"""
|
||||
|
||||
layout_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
region: RelativeRegion
|
||||
field_regions: list[FieldRegion] = Field(default_factory=list)
|
||||
|
||||
|
||||
class LineLayout(OrderProfileModel):
|
||||
"""描述一条逻辑明细内的物理行及其字段区域。"""
|
||||
|
||||
layout_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
row_offset: int = Field(ge=0)
|
||||
role: Literal['main', 'continuation']
|
||||
region: RelativeRegion
|
||||
field_regions: list[FieldRegion] = Field(default_factory=list)
|
||||
new_line_anchor: AnchorRule | None = None
|
||||
continuation_conditions: list[AnchorRule] = Field(default_factory=list)
|
||||
required_fields: list[str] = Field(default_factory=list)
|
||||
allowed_empty_fields: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ContinuationRule(OrderProfileModel):
|
||||
"""声明表区或页面之间可合并的明确证据,默认绝不自动跨页拼接。"""
|
||||
|
||||
allow_cross_page: bool = False
|
||||
required_anchor_ids: list[str] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_explicit_cross_page_evidence(self) -> 'ContinuationRule':
|
||||
"""跨页必须有至少一个静态锚点;仅因相邻页或相似列布局不得合并。"""
|
||||
if self.allow_cross_page and not self.required_anchor_ids:
|
||||
raise ValueError('cross-page continuation requires anchor evidence')
|
||||
if len(self.required_anchor_ids) != len(set(self.required_anchor_ids)):
|
||||
raise ValueError('cross-page continuation anchors must be unique')
|
||||
return self
|
||||
|
||||
|
||||
class TerminationRule(OrderProfileModel):
|
||||
"""定义明确的终止标记,防止合计、税额和条款被当作订单明细。"""
|
||||
|
||||
rule_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
anchor: AnchorRule
|
||||
|
||||
|
||||
class DraftUnboundFieldRegion(OrderProfileModel):
|
||||
"""草稿阶段尚未绑定 Schema 的字段框;运行和发布均不得使用。"""
|
||||
|
||||
region_id: str = Field(pattern=r'^[a-z][a-z0-9_-]{0,95}$')
|
||||
parent_layout_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
label: str = Field(min_length=1, max_length=160)
|
||||
region: RelativeRegion
|
||||
|
||||
|
||||
class TableRegionProfile(OrderProfileModel):
|
||||
"""定义一个订单明细表区、独立表头和多物理行布局。"""
|
||||
|
||||
region_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
page_scope: Literal['first_page', 'all_pages', 'continuation_pages', 'exact_page'] = 'all_pages'
|
||||
page_no: int | None = Field(default=None, ge=1)
|
||||
region: RelativeRegion
|
||||
header_layouts: list[HeaderLayout] = Field(default_factory=list)
|
||||
line_layouts: list[LineLayout] = Field(default_factory=list)
|
||||
continuation_rule: ContinuationRule = Field(default_factory=ContinuationRule)
|
||||
termination_rules: list[TerminationRule] = Field(default_factory=list)
|
||||
exclusion_regions: list[RelativeRegion] = Field(default_factory=list)
|
||||
draft_unbound_field_regions: list[DraftUnboundFieldRegion] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_table_layout(self) -> 'TableRegionProfile':
|
||||
"""校验物理行顺序、字段唯一性和同级区域不重叠,拒绝含糊的模板真相。"""
|
||||
if self.page_scope == 'exact_page' and self.page_no is None:
|
||||
raise ValueError('exact_page table 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 table regions')
|
||||
layouts = self.header_layouts + self.line_layouts
|
||||
if not layouts:
|
||||
raise ValueError('table region requires at least one header or line layout')
|
||||
ids = [item.layout_id for item in layouts]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError('table layout ids must be unique')
|
||||
offsets = [item.row_offset for item in self.line_layouts]
|
||||
if sorted(offsets) != list(range(len(offsets))):
|
||||
raise ValueError('line layout offsets must be contiguous from zero')
|
||||
if self.line_layouts and (sum(item.role == 'main' for item in self.line_layouts) != 1 or self.line_layouts[0].role != 'main'):
|
||||
raise ValueError('line layouts require one main layout at offset zero')
|
||||
if any(item.role != 'continuation' for item in self.line_layouts[1:]):
|
||||
raise ValueError('line layouts after the main layout must be continuations')
|
||||
# 表头映射只用于建议/校准,可以与明细字段同名;真正的提取绑定必须唯一。
|
||||
fields = [field.field_code for item in self.line_layouts for field in item.field_regions]
|
||||
if len(fields) != len(set(fields)):
|
||||
raise ValueError('field_code may bind to only one coordinate region per table')
|
||||
# A physical text band must have exactly one layout interpretation. Allowing
|
||||
# overlapping header/line regions would reintroduce the cross-row ambiguity
|
||||
# that v2 coordinate profiles are intended to eliminate.
|
||||
_validate_non_overlapping_regions([item.region for item in layouts])
|
||||
for item in layouts:
|
||||
_validate_non_overlapping_regions([field.region for field in item.field_regions])
|
||||
_validate_non_overlapping_regions(self.exclusion_regions)
|
||||
layout_ids = {item.layout_id for item in layouts}
|
||||
if any(item.parent_layout_id not in layout_ids for item in self.draft_unbound_field_regions):
|
||||
raise ValueError('draft unbound field region requires a layout parent')
|
||||
region_ids = [item.region_id for item in self.draft_unbound_field_regions]
|
||||
if len(region_ids) != len(set(region_ids)):
|
||||
raise ValueError('draft unbound field region ids must be unique')
|
||||
return self
|
||||
|
||||
|
||||
class DocumentMatchProfile(OrderProfileModel):
|
||||
"""定义模板唯一匹配所需的静态证据;动态订单业务值不可进入此对象。"""
|
||||
|
||||
document_type: Literal['purchase_order'] = 'purchase_order'
|
||||
page_pattern: Literal['one_or_more'] = 'one_or_more'
|
||||
required_anchors: list[AnchorRule] = Field(default_factory=list)
|
||||
optional_anchors: list[AnchorRule] = Field(default_factory=list)
|
||||
minimum_score: float = Field(default=0.9, ge=0, le=1)
|
||||
minimum_margin: float = Field(default=0.15, ge=0, le=1)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_anchor_ids(self) -> 'DocumentMatchProfile':
|
||||
"""要求必选和可选锚点名称唯一,避免评分器使用含糊证据。"""
|
||||
ids = [item.anchor_id for item in self.required_anchors + self.optional_anchors]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError('document match anchor ids must be unique')
|
||||
return self
|
||||
|
||||
|
||||
class OrderCoordinateProfileV2(OrderProfileModel):
|
||||
"""保存阶段 0 评审中的订单坐标模板 v2 定义,尚未接入旧运行路径。"""
|
||||
|
||||
contract_version: Literal[ORDER_PROFILE_VERSION] = ORDER_PROFILE_VERSION
|
||||
profile_code: str = Field(pattern=r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
|
||||
version: int = Field(ge=1)
|
||||
document_match: DocumentMatchProfile
|
||||
table_regions: list[TableRegionProfile] = Field(min_length=1)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_profile_rules(self) -> 'OrderCoordinateProfileV2':
|
||||
"""阻断重复表区和重叠表区,确保一个字段位置只有唯一模板解释。"""
|
||||
ids = [item.region_id for item in self.table_regions]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError('table region ids must be unique')
|
||||
for index, left in enumerate(self.table_regions):
|
||||
for right in self.table_regions[index + 1:]:
|
||||
# Different exact pages may use identical coordinates without competing at runtime.
|
||||
if _table_regions_can_apply_same_page(left, right):
|
||||
_validate_non_overlapping_regions([left.region, right.region])
|
||||
anchor_ids = {item.anchor_id for item in self.document_match.required_anchors + self.document_match.optional_anchors}
|
||||
for table in self.table_regions:
|
||||
if not set(table.continuation_rule.required_anchor_ids).issubset(anchor_ids):
|
||||
raise ValueError('cross-page continuation anchor must be a document match anchor')
|
||||
return self
|
||||
|
||||
|
||||
def _validate_non_overlapping_regions(regions: list[RelativeRegion]) -> None:
|
||||
"""拒绝任意正面积重叠,边缘相接仍是合法的精确坐标布局。"""
|
||||
for index, left in enumerate(regions):
|
||||
for right in regions[index + 1:]:
|
||||
if min(left.x1, right.x1) > max(left.x0, right.x0) and min(left.y1, right.y1) > max(left.y0, right.y0):
|
||||
raise ValueError('coordinate regions must not overlap')
|
||||
|
||||
|
||||
def _table_regions_can_apply_same_page(left: TableRegionProfile, right: TableRegionProfile) -> bool:
|
||||
"""判断两个页作用域是否可能命中同一页,供表区重叠校验排除不同精确页。"""
|
||||
if left.page_scope == 'all_pages' or right.page_scope == 'all_pages':
|
||||
return True
|
||||
if left.page_scope == 'exact_page' and right.page_scope == 'exact_page':
|
||||
return left.page_no == right.page_no
|
||||
if left.page_scope == 'exact_page':
|
||||
return left.page_no == 1 if right.page_scope == 'first_page' else bool(left.page_no and left.page_no > 1)
|
||||
if right.page_scope == 'exact_page':
|
||||
return right.page_no == 1 if left.page_scope == 'first_page' else bool(right.page_no and right.page_no > 1)
|
||||
return left.page_scope == right.page_scope
|
||||
|
||||
|
||||
# Transitional adapters keep the currently deployed extraction workflow importable while its
|
||||
# callers are migrated to the v2 coordinate runtime in later gated stages. They are not part
|
||||
# of the persisted v2 contract and must not be used by new Profile writes.
|
||||
class OrderProfileColumnRule(OrderProfileModel):
|
||||
"""定义一个固定来源列使用的注册解析器及目标字段编码。"""
|
||||
"""Legacy runtime column rule retained only until the frozen-run migration is complete."""
|
||||
|
||||
column_index: int = Field(ge=0)
|
||||
extractor_key: Literal['direct', 'temp_internal_parts']
|
||||
@@ -55,21 +282,19 @@ class OrderProfileColumnRule(OrderProfileModel):
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_extractor_targets(self) -> 'OrderProfileColumnRule':
|
||||
"""限制注册解析器的固定输出形态,禁止自由脚本或任意字段注入。"""
|
||||
"""Preserve the established finite extractor whitelist for historical frozen snapshots."""
|
||||
targets = set(self.target_field_codes)
|
||||
if len(targets) != len(self.target_field_codes):
|
||||
raise ValueError('order profile target fields must be unique')
|
||||
if self.extractor_key == 'direct' and len(targets) != 1:
|
||||
raise ValueError('direct order profile extractor requires one target field')
|
||||
if self.extractor_key == 'temp_internal_parts' and targets != {
|
||||
'customer_part_number', 'part_number',
|
||||
}:
|
||||
if self.extractor_key == 'temp_internal_parts' and targets != {'customer_part_number', 'part_number'}:
|
||||
raise ValueError('TEMP/internal extractor targets are fixed')
|
||||
return self
|
||||
|
||||
|
||||
class CoordinateReconstructionProfile(OrderProfileModel):
|
||||
"""冻结管理员确认的相对列边界;同版 PDF 表格据此重建并仍受 Profile 精确指纹门禁。"""
|
||||
"""Legacy frozen-run coordinate reconstruction adapter; v2 uses FieldRegion instead."""
|
||||
|
||||
method: Literal['native_pdf_coordinates.v1', 'ocr_pdf_coordinates.v1'] = 'native_pdf_coordinates.v1'
|
||||
column_boundaries: list[float] = Field(default_factory=list)
|
||||
@@ -79,38 +304,27 @@ class CoordinateReconstructionProfile(OrderProfileModel):
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_boundaries(self) -> 'CoordinateReconstructionProfile':
|
||||
"""边界须覆盖整表且严格递增,禁止由错误 HTML 反向猜列。"""
|
||||
"""Validate historical settings so existing frozen Run snapshots remain safe to load."""
|
||||
if self.subrow_layouts:
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import CoordinateSubrowLayout
|
||||
|
||||
layouts = [CoordinateSubrowLayout.model_validate(item) for item in self.subrow_layouts]
|
||||
offsets = [item.row_offset for item in layouts]
|
||||
roles = [item.role for item in layouts]
|
||||
if len(offsets) != len(set(offsets)) or sorted(offsets) != list(range(len(offsets))) or roles.count('main') != 1:
|
||||
if len(offsets) != len(set(offsets)) or sorted(offsets) != list(range(len(offsets))) or sum(item.role == 'main' for item in layouts) != 1:
|
||||
raise ValueError('coordinate subrow layouts require contiguous offsets and one main row')
|
||||
if next(item for item in layouts if item.role == 'main').row_offset != 0:
|
||||
raise ValueError('coordinate main row must use offset zero')
|
||||
if any(item.row_offset > 0 and item.role != 'continuation' for item in layouts):
|
||||
raise ValueError('coordinate rows after the main row must be continuations')
|
||||
return self
|
||||
if len(self.column_boundaries) < 3:
|
||||
raise ValueError('coordinate reconstruction requires column boundaries')
|
||||
if self.column_boundaries[0] != 0 or self.column_boundaries[-1] != 1:
|
||||
raise ValueError('coordinate reconstruction boundaries must start at 0 and end at 1')
|
||||
if len(self.column_boundaries) < 3 or self.column_boundaries[0] != 0 or self.column_boundaries[-1] != 1:
|
||||
raise ValueError('coordinate reconstruction boundaries must cover the table')
|
||||
if any(left >= right for left, right in zip(self.column_boundaries, self.column_boundaries[1:])):
|
||||
raise ValueError('coordinate reconstruction boundaries must be strictly increasing')
|
||||
column_count = len(self.column_boundaries) - 1
|
||||
if self.column_field_codes and len(self.column_field_codes) != column_count:
|
||||
if self.column_field_codes and len(self.column_field_codes) != len(self.column_boundaries) - 1:
|
||||
raise ValueError('coordinate reconstruction field codes must match column count')
|
||||
if self.line_start_column_index >= column_count:
|
||||
raise ValueError('coordinate reconstruction line start column is out of range')
|
||||
return self
|
||||
|
||||
|
||||
class OrderDocumentProfile(OrderProfileModel):
|
||||
"""保存不可变模板结构、列覆盖、数据起始行和质量策略。"""
|
||||
"""保存当前已发布运行路径的模板结构、列覆盖、数据起始行和质量策略。"""
|
||||
|
||||
contract_version: Literal[ORDER_PROFILE_VERSION] = ORDER_PROFILE_VERSION
|
||||
contract_version: Literal['shipping_order_document_profile.v1'] = 'shipping_order_document_profile.v1'
|
||||
profile_code: str = Field(pattern=r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
|
||||
version: int = Field(ge=1)
|
||||
structure_fingerprint: str = Field(pattern=r'^[0-9a-f]{64}$')
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/order_profile_extractors.py
|
||||
|
||||
用途:执行订单坐标 Profile v2 的有限注册字段解析器。
|
||||
依赖:订单料号复合解析与数值解析。
|
||||
逻辑:坐标重建先取得管理员框选的原文,本模块再将其安全拆成固定业务字段;任何拆分失败均不返回部分字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from decimal import Decimal, InvalidOperation
|
||||
|
||||
from app.services.shipping_notice.notice_lines import resolve_composite_part_numbers
|
||||
|
||||
|
||||
_NUMBER_UNIT = re.compile(r'^\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*([A-Za-z]{1,12})\s*$')
|
||||
_MONEY_CURRENCY = re.compile(r'^\s*([A-Za-z]{3}|[$€£¥])\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*$')
|
||||
_CURRENCY_MONEY = re.compile(r'^\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*([A-Za-z]{3}|[$€£¥])\s*$')
|
||||
_CURRENCY_SYMBOLS = {'$': 'USD', '€': 'EUR', '£': 'GBP', '¥': 'CNY'}
|
||||
|
||||
|
||||
def extract_profile_field_value(*, extractor_key: str, field_code: str, raw: str) -> dict[str, str]:
|
||||
"""将一个已确认区域按注册解析器拆分;不允许调用方传入规则、脚本或正则。"""
|
||||
text = str(raw or '').strip()
|
||||
if not text:
|
||||
return {}
|
||||
if extractor_key == 'direct':
|
||||
return {field_code: text}
|
||||
if extractor_key == 'temp_internal_parts':
|
||||
resolved = resolve_composite_part_numbers(text)
|
||||
return {
|
||||
code: str(value).strip() for code, value in (resolved or {}).items()
|
||||
if code in {'customer_part_number', 'part_number'} and str(value or '').strip()
|
||||
}
|
||||
if extractor_key == 'quantity_uom':
|
||||
matched = _NUMBER_UNIT.fullmatch(text)
|
||||
if not matched:
|
||||
return {}
|
||||
return {'qty': matched.group(1).replace(',', ''), 'uom': matched.group(2).upper()}
|
||||
if extractor_key in {'amount_currency', 'price_currency'}:
|
||||
matched = _MONEY_CURRENCY.fullmatch(text) or _CURRENCY_MONEY.fullmatch(text)
|
||||
if not matched:
|
||||
return {}
|
||||
first, second = matched.groups()
|
||||
currency, amount = (first, second) if first.isalpha() or first in _CURRENCY_SYMBOLS else (second, first)
|
||||
try:
|
||||
Decimal(amount.replace(',', ''))
|
||||
except (InvalidOperation, ValueError):
|
||||
return {}
|
||||
return {
|
||||
'line_amount_before_tax' if extractor_key == 'amount_currency' else 'unit_price': amount.replace(',', ''),
|
||||
'currency': _CURRENCY_SYMBOLS.get(currency, currency.upper()),
|
||||
}
|
||||
return {}
|
||||
|
||||
|
||||
def registered_extractor_output_codes(*, extractor_key: str, field_code: str) -> set[str]:
|
||||
"""返回一个注册解析器的固定输出集合,供契约校验拒绝含糊字段绑定。"""
|
||||
if extractor_key == 'direct':
|
||||
return {field_code}
|
||||
if extractor_key == 'temp_internal_parts':
|
||||
return {'customer_part_number', 'part_number'}
|
||||
if extractor_key == 'quantity_uom':
|
||||
return {'qty', 'uom'}
|
||||
if extractor_key == 'amount_currency':
|
||||
return {'line_amount_before_tax', 'currency'}
|
||||
if extractor_key == 'price_currency':
|
||||
return {'unit_price', 'currency'}
|
||||
return set()
|
||||
@@ -0,0 +1,122 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/order_profile_matcher.py
|
||||
|
||||
用途:以冻结的页面坐标证据唯一匹配订单坐标模板。
|
||||
依赖:OrderCoordinateProfileV2 和布局快照。逻辑:必需锚点与表区数量先作为硬条件,
|
||||
可选锚点只参与评分;没有达到阈值或分差的候选绝不进入确定性解析。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfileV2
|
||||
|
||||
|
||||
class ProfileMatchCandidate(BaseModel):
|
||||
"""记录单个冻结 Profile 的非敏感匹配分数和失败原因。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
profile_code: str
|
||||
version: int = Field(ge=1)
|
||||
score: float = Field(ge=0, le=1)
|
||||
hard_match: bool
|
||||
reasons: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ProfileMatchResult(BaseModel):
|
||||
"""文档级唯一匹配结果;只有 unique_match 可以启动坐标确定性解析。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
status: Literal['unique_match', 'no_match', 'ambiguous', 'layout_drift', 'evidence_insufficient']
|
||||
profile_code: str | None = None
|
||||
version: int | None = None
|
||||
checksum: str | None = None
|
||||
candidates: list[ProfileMatchCandidate] = Field(default_factory=list)
|
||||
|
||||
|
||||
def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout: dict[str, Any]) -> ProfileMatchResult:
|
||||
"""对同一文档的冻结 Profile 做唯一匹配,业务值和上传时间均不参与计算。"""
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
|
||||
if not tables or not pages or not glyph_tables:
|
||||
return ProfileMatchResult(status='evidence_insufficient')
|
||||
|
||||
candidates: list[tuple[dict[str, Any], OrderCoordinateProfileV2, ProfileMatchCandidate]] = []
|
||||
for raw in profiles:
|
||||
definition = raw.get('definition') if isinstance(raw.get('definition'), dict) else {}
|
||||
if definition.get('contract_version') != 'order_coordinate_profile.v2':
|
||||
continue
|
||||
try:
|
||||
profile = OrderCoordinateProfileV2(
|
||||
profile_code=str(raw.get('profile_code') or ''), version=int(raw.get('version') or 0),
|
||||
document_match=definition.get('document_match'), table_regions=definition.get('table_regions'),
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
reasons: list[str] = []
|
||||
if len(tables) < len(profile.table_regions):
|
||||
reasons.append('table_region_count_insufficient')
|
||||
required = profile.document_match.required_anchors
|
||||
required_hits = [_anchor_present(anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, pages=pages) for anchor in required]
|
||||
if not all(required_hits):
|
||||
reasons.append('required_anchor_missing')
|
||||
optional = profile.document_match.optional_anchors
|
||||
optional_hits = sum(_anchor_present(anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, pages=pages) for anchor in optional)
|
||||
hard_match = not reasons
|
||||
# Required evidence is mandatory rather than a soft score. Optional evidence only separates already valid templates.
|
||||
score = 1.0 if not optional else 0.8 + 0.2 * optional_hits / len(optional)
|
||||
candidates.append((raw, profile, ProfileMatchCandidate(
|
||||
profile_code=profile.profile_code, version=profile.version, score=score if hard_match else 0.0,
|
||||
hard_match=hard_match, reasons=reasons,
|
||||
)))
|
||||
rendered = sorted((item[2] for item in candidates), key=lambda item: (-item.score, item.profile_code, item.version))
|
||||
valid = sorted((item for item in candidates if item[2].hard_match), key=lambda item: (-item[2].score, item[1].profile_code, item[1].version))
|
||||
if not valid:
|
||||
status: Literal['no_match', 'layout_drift'] = 'layout_drift' if rendered else 'no_match'
|
||||
return ProfileMatchResult(status=status, candidates=rendered)
|
||||
raw, profile, first = valid[0]
|
||||
if first.score < profile.document_match.minimum_score:
|
||||
return ProfileMatchResult(status='no_match', candidates=rendered)
|
||||
if len(valid) > 1 and first.score - valid[1][2].score < profile.document_match.minimum_margin:
|
||||
return ProfileMatchResult(status='ambiguous', candidates=rendered)
|
||||
return ProfileMatchResult(
|
||||
status='unique_match', profile_code=profile.profile_code, version=profile.version,
|
||||
checksum=str(raw.get('checksum') or ''), candidates=rendered,
|
||||
)
|
||||
|
||||
|
||||
def _anchor_present(anchor: dict[str, Any], *, tables: list[dict[str, Any]], glyph_tables: dict[str, Any], pages: dict[str, Any]) -> bool:
|
||||
"""检查静态锚点是否在指定页面区域出现;不读取订单业务字段或 HTML 网格。"""
|
||||
expected = str(anchor.get('text') or '').strip()
|
||||
if not expected:
|
||||
return False
|
||||
for table in tables:
|
||||
glyphs = glyph_tables.get(str(table.get('table_id') or ''))
|
||||
page = pages.get(str(table.get('page_no') or ''))
|
||||
if not isinstance(glyphs, list) or not isinstance(page, dict):
|
||||
continue
|
||||
selected = glyphs
|
||||
region = anchor.get('region')
|
||||
if isinstance(region, dict):
|
||||
try:
|
||||
width, height = float(page['width']), float(page['height'])
|
||||
x0, y0, x1, y1 = float(region['x0']) * width, float(region['y0']) * height, float(region['x1']) * width, float(region['y1']) * height
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
selected = [item for item in glyphs if isinstance(item, dict) and isinstance(item.get('bbox'), dict)
|
||||
and x0 <= (float(item['bbox'].get('x0', 0)) + float(item['bbox'].get('x1', 0))) / 2 <= x1
|
||||
and y0 <= (float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 <= y1]
|
||||
text = ''.join(str(item.get('text') or '') for item in sorted(selected, key=lambda item: (item.get('bbox', {}).get('y0', 0), item.get('bbox', {}).get('x0', 0))))
|
||||
if str(anchor.get('match_mode') or 'contains') == 'exact':
|
||||
if expected.casefold() == text.casefold():
|
||||
return True
|
||||
elif expected.casefold() in text.casefold():
|
||||
return True
|
||||
return False
|
||||
@@ -187,7 +187,7 @@ def build_mineru_table_snapshot(
|
||||
|
||||
|
||||
def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""按 MinerU 整表 bbox 截取 PDF 字符证据;非表格正文与页面图像绝不持久化。"""
|
||||
"""保存表内字符和内部页尺寸,使 v2 页面相对坐标可在冻结 Run 中精确换算。"""
|
||||
from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages
|
||||
|
||||
pages = {item.page_no: item for item in extract_native_pdf_pages(content)}
|
||||
@@ -211,7 +211,15 @@ def _table_coordinate_evidence(*, content: bytes, tables: list[dict[str, Any]])
|
||||
glyphs.append(item.model_dump(mode='json'))
|
||||
if glyphs:
|
||||
evidence[table_id] = glyphs
|
||||
return {'version': 'shipping_order_coordinate_evidence.v1', 'tables': evidence}
|
||||
return {
|
||||
'version': 'shipping_order_coordinate_evidence.v1',
|
||||
'tables': evidence,
|
||||
# Internal runtime metadata only. It is removed with layout_snapshot before Dify input.
|
||||
'pages': {
|
||||
str(page_no): {'width': page.width, 'height': page.height}
|
||||
for page_no, page in pages.items()
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def attach_mineru_layout_snapshots(result: Any, *, root_asset_bytes: bytes | None = None) -> None:
|
||||
|
||||
@@ -23,23 +23,54 @@ from app.models import (
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
OrderCoordinateProfileV2,
|
||||
parse_html_table_with_order_profile,
|
||||
reconstruct_order_profile_html,
|
||||
)
|
||||
from app.services.shipping_notice.order_document_profile_service import _definition_contract
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import reconstruct_coordinate_profile_rows
|
||||
from app.services.shipping_notice.order_document_profile_service import _audit, _definition_contract
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
|
||||
MINIMUM_BLIND_SAMPLES = 3
|
||||
HEADERLESS_MINIMUM_BLIND_SAMPLES = 5
|
||||
|
||||
|
||||
def _quality_checksum(profile: ShippingOrderDocumentProfile) -> str:
|
||||
"""返回当前可测试定义的稳定校验值;草稿用定义 hash,发布版用正式 checksum。"""
|
||||
checksum = profile.checksum if profile.status == 'published' else profile.structure_fingerprint
|
||||
if not checksum:
|
||||
raise ConflictError('Profile checksum is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
|
||||
return str(checksum)
|
||||
|
||||
|
||||
def _requires_cross_page_sample(profile: ShippingOrderDocumentProfile) -> bool:
|
||||
"""判断模板是否声明跨页拼接;该类模板必须用真实续页证据进行盲测。"""
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
return any(
|
||||
isinstance(region, dict)
|
||||
and bool((region.get('continuation_rule') or {}).get('allow_cross_page'))
|
||||
for region in definition.get('table_regions') or []
|
||||
)
|
||||
|
||||
|
||||
def _is_headerless(profile: ShippingOrderDocumentProfile) -> bool:
|
||||
"""无表头坐标模板风险更高,要求五个独立回放样本。"""
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
regions = definition.get('table_regions') if isinstance(definition.get('table_regions'), list) else []
|
||||
return bool(regions) and not any(
|
||||
isinstance(region, dict) and region.get('header_layouts') for region in regions
|
||||
)
|
||||
|
||||
|
||||
def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
"""读取已发布 Profile;草稿和退役版本不能获得自动建单质量凭证。"""
|
||||
"""读取草稿或发布 Profile;仅发布版本可最终获得自动建单凭证。"""
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
if profile is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
if profile.status != 'published' or not profile.checksum:
|
||||
raise ConflictError('Only published order document profile can be tested', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
|
||||
if profile.status not in {'draft', 'published'}:
|
||||
raise ConflictError('Only draft or published order document profile can be tested', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID')
|
||||
_quality_checksum(profile)
|
||||
return profile
|
||||
|
||||
|
||||
@@ -57,6 +88,19 @@ def _table_html(document_id: int, table_id: str) -> str:
|
||||
raise ValidationError('Test sample table is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
|
||||
|
||||
|
||||
def _coordinate_table_available(document_id: int, table_id: str) -> bool:
|
||||
"""确认 v2 盲测有冻结页面尺寸和目标表的字符证据,不要求 MinerU HTML。"""
|
||||
document = db.session.get(ShippingNoticeDocument, int(document_id))
|
||||
layout = current_layout_snapshot(document) if document is not None else {}
|
||||
raw_table = next((item for item in (layout or {}).get('tables') or [] if isinstance(item, dict) and str(item.get('table_id') or '') == str(table_id)), None)
|
||||
evidence = (layout or {}).get('coordinate_evidence') if isinstance((layout or {}).get('coordinate_evidence'), dict) else {}
|
||||
return bool(
|
||||
isinstance(raw_table, dict)
|
||||
and isinstance((evidence.get('tables') or {}).get(str(table_id)), list)
|
||||
and isinstance((evidence.get('pages') or {}).get(str(raw_table.get('page_no') or '')), dict)
|
||||
)
|
||||
|
||||
|
||||
def _expected_rows(raw: Any) -> list[dict[str, Any]]:
|
||||
"""校验人工录入的盲测真值,只接受行字段字典且不允许空集合。"""
|
||||
if not isinstance(raw, list) or not raw or any(not isinstance(item, dict) or not item for item in raw):
|
||||
@@ -65,15 +109,18 @@ def _expected_rows(raw: Any) -> list[dict[str, Any]]:
|
||||
|
||||
|
||||
def create_suite(*, profile_id: int, actor_id: int) -> dict[str, Any]:
|
||||
"""为一个发布 Profile 建立唯一盲测集;旧批准凭证不会被覆盖。"""
|
||||
"""为草稿或发布 Profile 建立唯一盲测集;发布前完成审批以形成真正发布门禁。"""
|
||||
profile = _profile(profile_id)
|
||||
existing = ShippingDocumentProfileTestSuite.query.filter_by(profile_id=profile.id).first()
|
||||
if existing is not None:
|
||||
return serialize_suite(existing)
|
||||
suite = ShippingDocumentProfileTestSuite(
|
||||
profile_id=profile.id, profile_checksum=profile.checksum, created_by_id=actor_id,
|
||||
profile_id=profile.id, profile_checksum=_quality_checksum(profile), created_by_id=actor_id,
|
||||
)
|
||||
db.session.add(suite)
|
||||
_audit(profile_id=profile.id, event_type='blind_test_suite_created', actor_id=actor_id, detail={
|
||||
'profile_checksum': _quality_checksum(profile),
|
||||
})
|
||||
db.session.commit()
|
||||
return serialize_suite(suite)
|
||||
|
||||
@@ -85,17 +132,50 @@ def add_sample(*, suite_id: int, document_id: int, table_id: str, expected_rows:
|
||||
raise NotFoundError('Order document profile test suite not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_FOUND')
|
||||
if suite.status != 'draft':
|
||||
raise ConflictError('Approved test suite is immutable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_IMMUTABLE')
|
||||
_table_html(document_id, table_id)
|
||||
profile = _profile(suite.profile_id)
|
||||
from app.models import ShippingOrderDocumentProfileSample
|
||||
if ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id, document_id=int(document_id)).first() is not None:
|
||||
raise ConflictError('Blind test samples must be independent of modelling samples', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_NOT_INDEPENDENT')
|
||||
parser = _definition_contract(profile)
|
||||
if isinstance(parser, OrderCoordinateProfileV2):
|
||||
if not _coordinate_table_available(document_id, table_id):
|
||||
raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
|
||||
else:
|
||||
_table_html(document_id, table_id)
|
||||
sample = ShippingDocumentProfileTestSample(
|
||||
suite_id=suite.id, document_id=int(document_id), table_id=str(table_id),
|
||||
expected_rows_json=_expected_rows(expected_rows), created_by_id=actor_id,
|
||||
)
|
||||
db.session.add(sample)
|
||||
try:
|
||||
db.session.commit()
|
||||
db.session.flush()
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
raise ConflictError('Test sample already exists', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_CONFLICT') from exc
|
||||
_audit(profile_id=suite.profile_id, document_id=sample.document_id, event_type='blind_test_sample_added', actor_id=actor_id, detail={
|
||||
'suite_id': suite.id, 'has_table_binding': bool(sample.table_id),
|
||||
})
|
||||
db.session.commit()
|
||||
return serialize_suite(suite)
|
||||
|
||||
|
||||
def remove_sample(*, suite_id: int, sample_id: int, actor_id: int) -> dict[str, Any]:
|
||||
"""删除草稿盲测样本真值;批准后的证据不可原地删除或替换。"""
|
||||
suite = db.session.get(ShippingDocumentProfileTestSuite, int(suite_id))
|
||||
if suite is None:
|
||||
raise NotFoundError('Order document profile test suite not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_FOUND')
|
||||
if suite.status != 'draft':
|
||||
raise ConflictError('Approved test suite is immutable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_IMMUTABLE')
|
||||
sample = db.session.get(ShippingDocumentProfileTestSample, int(sample_id))
|
||||
if sample is None or sample.suite_id != suite.id:
|
||||
raise NotFoundError('Order document profile test sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SAMPLE_NOT_FOUND')
|
||||
document_id = sample.document_id
|
||||
db.session.delete(sample)
|
||||
db.session.flush()
|
||||
_audit(profile_id=suite.profile_id, document_id=document_id, event_type='blind_test_sample_removed', actor_id=actor_id, detail={
|
||||
'suite_id': suite.id,
|
||||
})
|
||||
db.session.commit()
|
||||
return serialize_suite(suite)
|
||||
|
||||
|
||||
@@ -105,17 +185,44 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
if suite is None:
|
||||
raise NotFoundError('Order document profile test suite not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_FOUND')
|
||||
profile = _profile(suite.profile_id)
|
||||
if suite.profile_checksum != profile.checksum:
|
||||
if suite.profile_checksum != _quality_checksum(profile):
|
||||
raise ConflictError('Profile changed after test suite creation', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_STALE')
|
||||
contract = compile_table_header_contract(profile.schema_version.definition_json or {})
|
||||
parser = _definition_contract(profile)
|
||||
failures: list[str] = []
|
||||
passed = 0
|
||||
for sample in suite.samples:
|
||||
document = db.session.get(ShippingNoticeDocument, sample.document_id)
|
||||
layout = current_layout_snapshot(document) if document is not None else None
|
||||
if isinstance(parser, OrderCoordinateProfileV2):
|
||||
evidence = (layout or {}).get('coordinate_evidence') if isinstance((layout or {}).get('coordinate_evidence'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
characters = (evidence.get('tables') or {}).get(sample.table_id) if isinstance(evidence.get('tables'), dict) else None
|
||||
raw_table = next((item for item in (layout or {}).get('tables') or [] if isinstance(item, dict) and str(item.get('table_id') or '') == sample.table_id), None)
|
||||
page = pages.get(str((raw_table or {}).get('page_no') or '')) if isinstance(pages, dict) else None
|
||||
if not isinstance(characters, list) or not isinstance(page, dict):
|
||||
failures.append(f'sample:{sample.id}:coordinate_evidence_missing')
|
||||
continue
|
||||
try:
|
||||
table_bbox = {'x0': 0, 'y0': 0, 'x1': float(page['width']), 'y1': float(page['height'])}
|
||||
except (KeyError, TypeError, ValueError):
|
||||
failures.append(f'sample:{sample.id}:coordinate_evidence_missing')
|
||||
continue
|
||||
actual_rows: list[dict[str, Any]] = []
|
||||
for region in parser.table_regions:
|
||||
actual_rows.extend(item.fields for item in reconstruct_coordinate_profile_rows(
|
||||
characters=[item for item in characters if isinstance(item, dict)], table_bbox=table_bbox,
|
||||
line_layouts=[item.model_dump() for item in region.line_layouts], table_region=region.region.model_dump(),
|
||||
termination_rules=[item.model_dump() for item in region.termination_rules],
|
||||
exclusion_regions=[item.model_dump() for item in region.exclusion_regions],
|
||||
) if not item.issues)
|
||||
if actual_rows == list(sample.expected_rows_json or []):
|
||||
passed += 1
|
||||
else:
|
||||
failures.append(f'sample:{sample.id}:mismatch')
|
||||
continue
|
||||
html = _table_html(sample.document_id, sample.table_id)
|
||||
if parser.coordinate_reconstruction is not None:
|
||||
document = db.session.get(ShippingNoticeDocument, sample.document_id)
|
||||
layout = current_layout_snapshot(document) if document is not None else None
|
||||
raw_table = next((
|
||||
item for item in (layout or {}).get('tables') or []
|
||||
if isinstance(item, dict) and str(item.get('table_id') or '') == sample.table_id
|
||||
@@ -140,12 +247,16 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
failures.append(f'sample:{sample.id}:mismatch')
|
||||
sample_count = len(suite.samples)
|
||||
run = ShippingDocumentProfileTestRun(
|
||||
suite_id=suite.id, profile_checksum=profile.checksum,
|
||||
suite_id=suite.id, profile_checksum=_quality_checksum(profile),
|
||||
status='passed' if sample_count >= MINIMUM_BLIND_SAMPLES and passed == sample_count else 'failed',
|
||||
sample_count=sample_count, passed_sample_count=passed, failure_codes_json=failures,
|
||||
executed_by_id=actor_id,
|
||||
)
|
||||
db.session.add(run)
|
||||
_audit(profile_id=profile.id, event_type='blind_test_executed', actor_id=actor_id, detail={
|
||||
'suite_id': suite.id, 'status': run.status, 'sample_count': sample_count,
|
||||
'passed_sample_count': passed,
|
||||
})
|
||||
db.session.commit()
|
||||
return serialize_suite(suite)
|
||||
|
||||
@@ -158,13 +269,16 @@ def approve_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
profile = _profile(suite.profile_id)
|
||||
last_run = suite.runs[-1] if suite.runs else None
|
||||
if (
|
||||
suite.status != 'draft' or suite.profile_checksum != profile.checksum or last_run is None
|
||||
or last_run.status != 'passed' or last_run.profile_checksum != profile.checksum
|
||||
suite.status != 'draft' or suite.profile_checksum != _quality_checksum(profile) or last_run is None
|
||||
or last_run.status != 'passed' or last_run.profile_checksum != _quality_checksum(profile)
|
||||
):
|
||||
raise ConflictError('A current passing blind test run is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY')
|
||||
suite.status = 'approved'
|
||||
suite.approved_by_id = actor_id
|
||||
suite.approved_at = datetime.utcnow()
|
||||
_audit(profile_id=profile.id, event_type='blind_test_approved', actor_id=actor_id, detail={
|
||||
'suite_id': suite.id, 'profile_checksum': _quality_checksum(profile),
|
||||
})
|
||||
db.session.commit()
|
||||
return serialize_suite(suite)
|
||||
|
||||
@@ -177,6 +291,60 @@ def profile_is_auto_create_approved(*, profile_id: int, checksum: str) -> bool:
|
||||
return suite is not None
|
||||
|
||||
|
||||
def assert_profile_publishable(profile: ShippingOrderDocumentProfile) -> None:
|
||||
"""执行坐标模板发布门禁:训练样本、独立盲测、多明细与跨页覆盖均不可绕过。"""
|
||||
from app.models import ShippingOrderDocumentProfileSample
|
||||
|
||||
draft_checksum = _quality_checksum(profile)
|
||||
training_count = ShippingOrderDocumentProfileSample.query.filter_by(
|
||||
profile_id=profile.id, sample_role='training',
|
||||
).count()
|
||||
if training_count < 1:
|
||||
raise ConflictError('A training sample is required before publishing', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_TRAINING')
|
||||
suite = ShippingDocumentProfileTestSuite.query.filter_by(
|
||||
profile_id=profile.id, profile_checksum=draft_checksum, status='approved',
|
||||
).first()
|
||||
if suite is None or not suite.runs or suite.runs[-1].status != 'passed' or suite.runs[-1].profile_checksum != draft_checksum:
|
||||
raise ConflictError('An approved current blind test is required before publishing', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST')
|
||||
minimum = HEADERLESS_MINIMUM_BLIND_SAMPLES if _is_headerless(profile) else MINIMUM_BLIND_SAMPLES
|
||||
samples = list(suite.samples)
|
||||
if len(samples) < minimum or len({item.document_id for item in samples}) < minimum:
|
||||
raise ConflictError('Insufficient independent blind test samples', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST')
|
||||
model_documents = {
|
||||
item.document_id for item in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).all()
|
||||
}
|
||||
if model_documents & {item.document_id for item in samples}:
|
||||
raise ConflictError('Blind test samples must be independent of modelling samples', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST')
|
||||
if not any(len(item.expected_rows_json or []) > 1 for item in samples):
|
||||
raise ConflictError('A multi-line blind test sample is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_MULTILINE')
|
||||
if _requires_cross_page_sample(profile):
|
||||
has_cross_page = False
|
||||
for sample in samples:
|
||||
document = db.session.get(ShippingNoticeDocument, sample.document_id)
|
||||
layout = current_layout_snapshot(document) if document is not None else {}
|
||||
table = next((item for item in (layout or {}).get('tables') or [] if isinstance(item, dict) and str(item.get('table_id') or '') == sample.table_id), None)
|
||||
if isinstance(table, dict) and table.get('continuation_of'):
|
||||
has_cross_page = True
|
||||
break
|
||||
if not has_cross_page:
|
||||
raise ConflictError('A cross-page blind test sample is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_CROSS_PAGE')
|
||||
|
||||
|
||||
def promote_approved_suite_for_publish(*, profile: ShippingOrderDocumentProfile, draft_checksum: str, published_checksum: str) -> None:
|
||||
"""将已批准草稿盲测凭证原子冻结为正式 Profile checksum,供历史 Run 精确引用。"""
|
||||
suite = ShippingDocumentProfileTestSuite.query.filter_by(
|
||||
profile_id=profile.id, profile_checksum=draft_checksum, status='approved',
|
||||
).one_or_none()
|
||||
# Production callers have passed assert_profile_publishable. This guard keeps
|
||||
# isolated lifecycle tests from fabricating a quality credential by monkeypatch.
|
||||
if suite is None:
|
||||
return
|
||||
suite.profile_checksum = published_checksum
|
||||
for run in suite.runs:
|
||||
if run.profile_checksum == draft_checksum:
|
||||
run.profile_checksum = published_checksum
|
||||
|
||||
|
||||
def serialize_suite(suite: ShippingDocumentProfileTestSuite) -> dict[str, Any]:
|
||||
"""返回不含订单正文的盲测治理摘要,供管理端确认发布状态。"""
|
||||
latest = suite.runs[-1] if suite.runs else None
|
||||
|
||||
@@ -64,6 +64,19 @@ def _cfg_bool(key: str, default: bool = False) -> bool:
|
||||
return str(val).strip().lower() in {"1", "true", "yes", "on"}
|
||||
|
||||
|
||||
def _rpa_callback_success(value: Any) -> bool:
|
||||
"""严格解析 Worker 上传回调结果,拒绝把字符串 ``"false"`` 当作成功。"""
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
normalized = value.strip().lower()
|
||||
if normalized in {'true', '1'}:
|
||||
return True
|
||||
if normalized in {'false', '0'}:
|
||||
return False
|
||||
raise ValidationError('Upload callback success must be boolean', code='SHIPPING.UPLOAD_CALLBACK_INVALID')
|
||||
|
||||
|
||||
def _task_disposition_gate_response(task: ShippingTask) -> dict[str, Any] | None:
|
||||
"""在履约副作用前阻断回收站、作废或归档任务,避免迟到请求继续改变业务事实。"""
|
||||
reason = task_execution_block_reason(task)
|
||||
@@ -749,9 +762,21 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
artifact = current_upload_artifact(task, attempt.artifact_id)
|
||||
except (ConflictError, ValidationError) as exc:
|
||||
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
|
||||
queued, trigger = write_upload_trigger(task.task_no, artifact.file_path, payload={
|
||||
'artifact_id': artifact.id, 'attempt_id': attempt.id, 'callback_id': f'rpa:{attempt.id}',
|
||||
})
|
||||
upload_connector_type = str(task.inventory_connector_type or '').strip().lower()
|
||||
upload_entry_url = ''
|
||||
if upload_connector_type == 'dbs' and task.inventory_source_code:
|
||||
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
|
||||
|
||||
source = get_rpa_trigger_inventory_source(task.inventory_source_code, enabled_only=False) or {}
|
||||
upload_entry_url = str(source.get('login_url') or source.get('entry_url') or '').strip()
|
||||
try:
|
||||
queued, trigger = write_upload_trigger(task.task_no, artifact.file_path, payload={
|
||||
'artifact_id': artifact.id, 'attempt_id': attempt.id, 'callback_id': f'rpa:{attempt.id}',
|
||||
'inventory_connector_type': upload_connector_type,
|
||||
'inventory_entry_url': upload_entry_url,
|
||||
})
|
||||
except OSError:
|
||||
queued, trigger = None, None
|
||||
if queued and trigger:
|
||||
apply_task_transition(task, TaskTransition.UPLOAD_RPA_PENDING)
|
||||
attempt_no = attempt.attempt_no
|
||||
@@ -798,6 +823,15 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
},
|
||||
)
|
||||
|
||||
# Trigger 写入失败时,不能遗留 running Attempt / uploading Artifact;否则下一次
|
||||
# retry_upload 会被假性进行中的状态阻断。以独立 callback id 记录本地投递失败。
|
||||
complete_attempt(
|
||||
attempt,
|
||||
success=False,
|
||||
callback_id=f'trigger_failed:{attempt.id}',
|
||||
error_message='RPA upload trigger could not be written',
|
||||
)
|
||||
|
||||
apply_task_transition(task, TaskTransition.UPLOAD_FAILED)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
@@ -809,7 +843,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
detail=t("workflow.fulfillment.upload_takeover_detail", lang=lang),
|
||||
)
|
||||
task.error_message = t("workflow.fulfillment.upload_trigger_failed", lang=lang)
|
||||
log_task_event(task, "upload_rpa_pending", {})
|
||||
log_task_event(task, "upload_rpa_trigger_failed", {'attempt_id': attempt.id if 'attempt' in locals() else None})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
@@ -855,7 +889,10 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id)
|
||||
if artifact is None or artifact.task_id != task.id:
|
||||
return tool_response(status='failed', task=task, message='Upload attempt does not belong to this task', data=serialize_task_for_tool(task))
|
||||
success = bool(payload.get("success", True))
|
||||
try:
|
||||
success = _rpa_callback_success(payload.get("success", True))
|
||||
except ValidationError as exc:
|
||||
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
|
||||
try:
|
||||
completed = complete_attempt(
|
||||
attempt, success=success, callback_id=str(payload.get('callback_id') or f'rpa:{attempt.id}'),
|
||||
@@ -863,7 +900,8 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
except (ConflictError, ValidationError) as exc:
|
||||
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
|
||||
if success:
|
||||
# 重复 callback 由 Attempt 的持久化结果决定,不能按本次请求值重写 UI 状态。
|
||||
if completed.status == 'succeeded':
|
||||
if task.process_status == 'uploaded':
|
||||
apply_task_transition(task, TaskTransition.UPLOADED)
|
||||
set_task_step_progress(
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -19,11 +19,15 @@ from app.services.shipping_notice.context_fields.dify_exposure import compile_re
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
OrderDocumentProfile,
|
||||
OrderCoordinateProfileV2,
|
||||
OrderProfileColumnRule,
|
||||
parse_html_table_with_order_profile,
|
||||
reconstruct_order_profile_html,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import reconstruct_coordinate_profile_rows
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import match_frozen_coordinate_profiles
|
||||
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value
|
||||
|
||||
|
||||
def _unit_snapshot(run: Any, unit: Any) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
@@ -225,9 +229,30 @@ def _frozen_order_profile(raw: dict[str, Any]) -> OrderDocumentProfile:
|
||||
)
|
||||
|
||||
|
||||
def _profile_snapshot_targets_valid(raw: dict[str, Any], *, contract: Any) -> bool:
|
||||
def _profile_snapshot_targets_valid(
|
||||
raw: dict[str, Any], *, contract: Any, schema_fields: dict[str, dict[str, Any]] | None = None,
|
||||
) -> bool:
|
||||
"""确认 Profile 冻结的 field_id/code 与 Run Schema 完全一致,禁止仅凭可变名称执行。"""
|
||||
definition = raw.get('definition') if isinstance(raw.get('definition'), dict) else {}
|
||||
if definition.get('contract_version') == 'order_coordinate_profile.v2':
|
||||
for table in definition.get('table_regions') or []:
|
||||
if not isinstance(table, dict):
|
||||
return False
|
||||
for layout in (table.get('header_layouts') or []) + (table.get('line_layouts') or []):
|
||||
for target in layout.get('field_regions') or []:
|
||||
code = str(target.get('field_code') or '')
|
||||
config = contract.fields_by_code.get(code) or (schema_fields or {}).get(code)
|
||||
if config is None or str(target.get('field_id') or '') != str(config.get('field_id') or ''):
|
||||
return False
|
||||
targets = target.get('target_fields') if isinstance(target.get('target_fields'), list) else []
|
||||
if not targets:
|
||||
return False
|
||||
for output in targets:
|
||||
output_code = str(output.get('field_code') or '') if isinstance(output, dict) else ''
|
||||
output_config = contract.fields_by_code.get(output_code) or (schema_fields or {}).get(output_code)
|
||||
if output_config is None or str(output.get('field_id') or '') != str(output_config.get('field_id') or ''):
|
||||
return False
|
||||
return True
|
||||
for rule in definition.get('column_rules') or []:
|
||||
if not isinstance(rule, dict):
|
||||
return False
|
||||
@@ -288,6 +313,147 @@ def _dify_profile_candidates(tables: list[dict[str, Any]]) -> list[dict[str, Any
|
||||
return result
|
||||
|
||||
|
||||
def _coordinate_v2_profile_rows(
|
||||
*, raw_profile: dict[str, Any], raw_table: dict[str, Any], layout: dict[str, Any],
|
||||
contract: Any, schema_fields: dict[str, dict[str, Any]], initial_carry: dict[str, Any] | None = None,
|
||||
) -> list[dict[str, Any]] | None:
|
||||
"""用冻结 v2 区域和字符证据生成紧凑行候选;缺少坐标时 fail closed。"""
|
||||
profile = _frozen_coordinate_profile(raw_profile)
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
characters = tables.get(str(raw_table.get('table_id') or ''))
|
||||
page_size = pages.get(str(raw_table.get('page_no') or ''))
|
||||
if not isinstance(characters, list) or not isinstance(page_size, dict):
|
||||
return None
|
||||
try:
|
||||
page_bbox = {
|
||||
'x0': 0, 'y0': 0, 'x1': float(page_size['width']), 'y1': float(page_size['height']),
|
||||
}
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
if page_bbox['x1'] <= 0 or page_bbox['y1'] <= 0:
|
||||
return None
|
||||
rows: list[dict[str, Any]] = []
|
||||
for region in profile.table_regions:
|
||||
page_no = int(raw_table.get('page_no') or 1)
|
||||
if region.page_scope == 'first_page' and page_no != 1:
|
||||
continue
|
||||
if region.page_scope == 'continuation_pages' and page_no <= 1:
|
||||
continue
|
||||
if region.page_scope == 'exact_page' and page_no != region.page_no:
|
||||
continue
|
||||
# A continuation page may carry column headers only; it is not a data layout.
|
||||
if not region.line_layouts:
|
||||
continue
|
||||
carry = initial_carry if isinstance(initial_carry, dict) and initial_carry.get('region_id') == region.region_id else {}
|
||||
for reconstructed in reconstruct_coordinate_profile_rows(
|
||||
characters=[item for item in characters if isinstance(item, dict)], table_bbox=page_bbox,
|
||||
line_layouts=[item.model_dump() for item in region.line_layouts],
|
||||
table_region=region.region.model_dump(),
|
||||
termination_rules=[item.model_dump() for item in region.termination_rules],
|
||||
exclusion_regions=[item.model_dump() for item in region.exclusion_regions],
|
||||
initial_fields=carry.get('fields'), initial_next_offset=int(carry.get('next_offset') or 0),
|
||||
):
|
||||
values: list[dict[str, Any]] = []
|
||||
issues = list(reconstructed.issues)
|
||||
for code, raw_value in reconstructed.fields.items():
|
||||
config = contract.fields_by_code.get(code)
|
||||
# Composite extractors may produce a frozen Header output (for example currency).
|
||||
# It is retained here and later accepted only when all rows agree on the same value.
|
||||
if config is None:
|
||||
config = schema_fields.get(code)
|
||||
if config is None:
|
||||
issues.append(f'order_profile_field_invalid:{code}')
|
||||
continue
|
||||
try:
|
||||
value = normalize_order_field_value(raw_value, config)
|
||||
except (TypeError, ValueError, ValidationError):
|
||||
value = None
|
||||
if value is None or not validate_order_field_value(value, config):
|
||||
issues.append(f'order_profile_field_invalid:{code}')
|
||||
continue
|
||||
values.append({'field_id': str(config.get('field_id') or ''), 'field_code': code, 'value': value, 'quote': str(raw_value)[:1000]})
|
||||
rows.append({'row_index': reconstructed.source_row_indices[0], 'status': 'parsed' if not issues else 'needs_review', 'fields': values, 'issues': issues,
|
||||
'_coordinate_region_id': region.region_id, '_coordinate_row_count': int(carry.get('source_row_count') or 0) + len(reconstructed.source_row_indices)})
|
||||
return rows
|
||||
|
||||
|
||||
def _cross_page_anchor_matches(*, raw_profile: dict[str, Any], raw_table: dict[str, Any], layout: dict[str, Any], anchor_ids: list[str]) -> bool:
|
||||
"""续页必须在冻结字符证据中命中管理员声明的静态锚点,缺坐标即拒绝合并。"""
|
||||
definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {}
|
||||
match = definition.get('document_match') if isinstance(definition.get('document_match'), dict) else {}
|
||||
anchors = {str(item.get('anchor_id') or ''): item for item in (match.get('required_anchors') or []) + (match.get('optional_anchors') or []) if isinstance(item, dict)}
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
glyphs = (evidence.get('tables') or {}).get(str(raw_table.get('table_id') or ''))
|
||||
if not isinstance(glyphs, list):
|
||||
return False
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
page = pages.get(str(raw_table.get('page_no') or ''))
|
||||
if not isinstance(page, dict):
|
||||
return False
|
||||
try:
|
||||
page_width, page_height = float(page['width']), float(page['height'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return False
|
||||
for anchor_id in anchor_ids:
|
||||
anchor = anchors.get(anchor_id)
|
||||
expected = str((anchor or {}).get('text') or '')
|
||||
if not expected:
|
||||
return False
|
||||
selected = glyphs
|
||||
region = anchor.get('region')
|
||||
if isinstance(region, dict):
|
||||
try:
|
||||
x0, y0 = float(region['x0']) * page_width, float(region['y0']) * page_height
|
||||
x1, y1 = float(region['x1']) * page_width, float(region['y1']) * page_height
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return False
|
||||
selected = [item for item in glyphs if isinstance(item, dict) and isinstance(item.get('bbox'), dict)
|
||||
and x0 <= (float(item['bbox'].get('x0', 0)) + float(item['bbox'].get('x1', 0))) / 2 <= x1
|
||||
and y0 <= (float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 <= y1]
|
||||
bands: dict[int, list[dict[str, Any]]] = {}
|
||||
for item in selected:
|
||||
if not isinstance(item, dict) or not isinstance(item.get('bbox'), dict):
|
||||
continue
|
||||
center_y = (float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2
|
||||
bands.setdefault(round(center_y / 3), []).append(item)
|
||||
texts = [
|
||||
''.join(str(item.get('text') or '') for item in sorted(band, key=lambda item: item.get('bbox', {}).get('x0', 0)))
|
||||
for _band, band in sorted(bands.items())
|
||||
]
|
||||
text = '\n'.join(texts)
|
||||
if str(anchor.get('match_mode') or 'contains') == 'exact':
|
||||
if not any(expected.casefold() == item.casefold() for item in texts):
|
||||
return False
|
||||
elif expected.casefold() not in text.casefold():
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _validate_table_header_outputs(rows: list[dict[str, Any]], *, schema_fields: dict[str, dict[str, Any]]) -> bool:
|
||||
"""Header 输出只能在同表所有有效明细行一致时保留,否则阻断确定性建单。"""
|
||||
values_by_field: dict[str, set[str]] = {}
|
||||
for row in rows:
|
||||
if not isinstance(row, dict) or row.get('status') != 'parsed':
|
||||
continue
|
||||
for field in row.get('fields') or []:
|
||||
if not isinstance(field, dict):
|
||||
continue
|
||||
config = schema_fields.get(str(field.get('field_code') or ''))
|
||||
if config is not None and config.get('scope') == 'header':
|
||||
values_by_field.setdefault(str(field.get('field_id') or ''), set()).add(
|
||||
json.dumps(field.get('value'), ensure_ascii=False, sort_keys=True),
|
||||
)
|
||||
if any(len(values) > 1 for values in values_by_field.values()):
|
||||
for row in rows:
|
||||
if isinstance(row, dict):
|
||||
row['status'] = 'needs_review'
|
||||
row.setdefault('issues', []).append('order_profile_header_value_conflict')
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
"""
|
||||
用 Run 冻结 Profile 解析 MinerU HTML,并生成不含坐标/HTML的紧凑字段候选。
|
||||
@@ -298,6 +464,10 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
definition = schema_snapshot.get('definition') if isinstance(schema_snapshot.get('definition'), dict) else {}
|
||||
contract = compile_table_header_contract(definition)
|
||||
schema_fields = {
|
||||
str(item.get('field_code') or ''): item for item in definition.get('fields') or []
|
||||
if isinstance(item, dict) and item.get('enabled', True)
|
||||
}
|
||||
profiles = [
|
||||
item for item in snapshot.get('order_document_profiles') or []
|
||||
if isinstance(item, dict)
|
||||
@@ -307,18 +477,86 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
layout = document.get('layout_snapshot') if isinstance(document.get('layout_snapshot'), dict) else {}
|
||||
if layout.get('status') != 'ready' or not profiles:
|
||||
return {'matched': False, 'blocking': False, 'tables': [], 'issues': []}
|
||||
v2_profiles = [
|
||||
item for item in profiles
|
||||
if isinstance(item.get('definition'), dict)
|
||||
and item['definition'].get('contract_version') == 'order_coordinate_profile.v2'
|
||||
]
|
||||
if v2_profiles:
|
||||
match = match_frozen_coordinate_profiles(profiles=v2_profiles, layout=layout)
|
||||
if match.status != 'unique_match':
|
||||
return {
|
||||
'matched': False, 'blocking': True, 'tables': [],
|
||||
'issues': [f'order_profile_{match.status}'],
|
||||
'match': match.model_dump(mode='json'),
|
||||
}
|
||||
profiles = [
|
||||
item for item in v2_profiles
|
||||
if item.get('profile_code') == match.profile_code and int(item.get('version') or 0) == match.version
|
||||
and str(item.get('checksum') or '') == match.checksum
|
||||
]
|
||||
result_tables: list[dict[str, Any]] = []
|
||||
issues: list[str] = []
|
||||
matched_any = False
|
||||
for raw_table in layout.get('tables') or []:
|
||||
if not isinstance(raw_table, dict) or not str(raw_table.get('html') or '').strip():
|
||||
cross_page_carries: dict[tuple[str, str], dict[str, Any]] = {}
|
||||
for raw_table in sorted((item for item in layout.get('tables') or [] if isinstance(item, dict)), key=lambda item: (int(item.get('page_no') or 1), str(item.get('table_id') or ''))):
|
||||
if not isinstance(raw_table, dict):
|
||||
continue
|
||||
table_id = str(raw_table.get('table_id') or '')
|
||||
matches: list[tuple[dict[str, Any], Any]] = []
|
||||
for raw_profile in profiles:
|
||||
if not _profile_snapshot_targets_valid(raw_profile, contract=contract):
|
||||
if not _profile_snapshot_targets_valid(raw_profile, contract=contract, schema_fields=schema_fields):
|
||||
issues.append('order_profile_snapshot_field_mismatch')
|
||||
continue
|
||||
definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {}
|
||||
if definition.get('contract_version') == 'order_coordinate_profile.v2':
|
||||
# v2 consumes only the frozen table bounds and native/OCR coordinates.
|
||||
# MinerU HTML is intentionally neither required nor parsed on this path.
|
||||
try:
|
||||
profile = _frozen_coordinate_profile(raw_profile)
|
||||
carry = None
|
||||
parent_table_id = str(raw_table.get('continuation_of') or '')
|
||||
if parent_table_id:
|
||||
for region in profile.table_regions:
|
||||
candidate = cross_page_carries.get((str(raw_profile.get('profile_code') or ''), parent_table_id))
|
||||
if candidate and candidate.get('region_id') == region.region_id and region.continuation_rule.allow_cross_page and _cross_page_anchor_matches(
|
||||
raw_profile=raw_profile, raw_table=raw_table, layout=layout,
|
||||
anchor_ids=region.continuation_rule.required_anchor_ids,
|
||||
):
|
||||
carry = candidate
|
||||
break
|
||||
v2_rows = _coordinate_v2_profile_rows(
|
||||
raw_profile=raw_profile, raw_table=raw_table, layout=layout,
|
||||
contract=contract, schema_fields=schema_fields, initial_carry=carry,
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
issues.append('order_profile_snapshot_invalid')
|
||||
continue
|
||||
if v2_rows is None:
|
||||
issues.append('order_profile_coordinate_reconstruction_unavailable')
|
||||
continue
|
||||
if v2_rows:
|
||||
complete_rows = []
|
||||
for row in v2_rows:
|
||||
region = next((item for item in profile.table_regions if item.region_id == row.get('_coordinate_region_id')), None)
|
||||
if region is not None and row.get('_coordinate_row_count', 0) < len(region.line_layouts):
|
||||
cross_page_carries[(str(raw_profile.get('profile_code') or ''), table_id)] = {
|
||||
'region_id': region.region_id,
|
||||
'fields': {str(field.get('field_code') or ''): str(field.get('value') or '') for field in row.get('fields') or [] if isinstance(field, dict)},
|
||||
'next_offset': int(row.get('_coordinate_row_count') or 0),
|
||||
'source_row_count': int(row.get('_coordinate_row_count') or 0),
|
||||
}
|
||||
continue
|
||||
row.pop('_coordinate_region_id', None)
|
||||
row.pop('_coordinate_row_count', None)
|
||||
complete_rows.append(row)
|
||||
v2_rows = complete_rows
|
||||
if v2_rows:
|
||||
_validate_table_header_outputs(v2_rows, schema_fields=schema_fields)
|
||||
matches.append((raw_profile, v2_rows))
|
||||
continue
|
||||
if not str(raw_table.get('html') or '').strip():
|
||||
continue
|
||||
try:
|
||||
profile = _frozen_order_profile(raw_profile)
|
||||
source_html = _reconstructed_profile_html(layout=layout, raw_table=raw_table, profile=profile)
|
||||
@@ -343,6 +581,13 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
issues.append('order_profile_multiple_matches')
|
||||
continue
|
||||
raw_profile, parsed = matches[0]
|
||||
if isinstance(parsed, list):
|
||||
result_tables.append({
|
||||
'profile_code': str(raw_profile.get('profile_code') or ''), 'profile_version': int(raw_profile.get('version') or 0),
|
||||
'profile_checksum': str(raw_profile.get('checksum') or ''), 'table_id': table_id, 'page_no': int(raw_table.get('page_no') or 1),
|
||||
'auto_create_approved': bool(raw_profile.get('auto_create_approved')), 'rows': parsed,
|
||||
})
|
||||
continue
|
||||
if parsed.issues:
|
||||
issues.extend(parsed.issues)
|
||||
continue
|
||||
@@ -580,6 +825,15 @@ def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, An
|
||||
return [order] if order is not None else None
|
||||
|
||||
|
||||
def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfileV2:
|
||||
"""从 Run 快照恢复 v2 坐标契约,运行时不回读 Profile 数据库记录。"""
|
||||
definition = raw.get('definition') if isinstance(raw.get('definition'), dict) else {}
|
||||
return OrderCoordinateProfileV2(
|
||||
profile_code=str(raw.get('profile_code') or ''), version=int(raw.get('version') or 0),
|
||||
document_match=definition.get('document_match'), table_regions=definition.get('table_regions'),
|
||||
)
|
||||
|
||||
|
||||
def _build_approved_profile_order(
|
||||
*, unit: Any, intake: dict[str, Any], schema: dict[str, Any], definition: dict[str, Any],
|
||||
table: dict[str, Any],
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_schema/compatibility.py
|
||||
|
||||
用途:判断订单文档模板引用的稳定 field_id 是否能兼容新的订单 Schema。
|
||||
依赖:Schema definition JSON 与订单文档 Profile definition JSON。
|
||||
逻辑:字段身份按 field_id 对齐;新增字段兼容,缺失、作用域或类型变化属于破坏性变更。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _fields(definition: dict[str, Any] | None) -> dict[str, dict[str, Any]]:
|
||||
"""按稳定 field_id 提取 Schema 字段快照。"""
|
||||
return {
|
||||
str(item.get('field_id')): item
|
||||
for item in (definition or {}).get('fields') or []
|
||||
if isinstance(item, dict) and item.get('field_id')
|
||||
}
|
||||
|
||||
|
||||
def referenced_field_ids(profile_definition: dict[str, Any] | None) -> set[str]:
|
||||
"""读取模板所有坐标字段区域引用的稳定 field_id。"""
|
||||
result: set[str] = set()
|
||||
for table in (profile_definition or {}).get('table_regions') or []:
|
||||
if not isinstance(table, dict):
|
||||
continue
|
||||
for layout_key in ('header_layouts', 'line_layouts'):
|
||||
for layout in table.get(layout_key) or []:
|
||||
if not isinstance(layout, dict):
|
||||
continue
|
||||
for field in layout.get('field_regions') or []:
|
||||
if isinstance(field, dict) and field.get('field_id'):
|
||||
result.add(str(field['field_id']))
|
||||
for target in field.get('target_fields') or []:
|
||||
if isinstance(target, dict) and target.get('field_id'):
|
||||
result.add(str(target['field_id']))
|
||||
return result
|
||||
|
||||
|
||||
def is_replacement_compatible(
|
||||
source: dict[str, Any],
|
||||
candidate: dict[str, Any],
|
||||
*,
|
||||
source_field_id: str | None = None,
|
||||
candidate_field_id: str | None = None,
|
||||
) -> bool:
|
||||
"""判断迁移替代字段能否承接原坐标绑定;原字段不能替代自身。"""
|
||||
if source_field_id and candidate_field_id and source_field_id == candidate_field_id:
|
||||
return False
|
||||
return (
|
||||
candidate.get('enabled', True)
|
||||
and candidate.get('scope') == source.get('scope')
|
||||
and candidate.get('value_type') == source.get('value_type')
|
||||
and set(source.get('allowed_sources') or []).issubset(set(candidate.get('allowed_sources') or []))
|
||||
)
|
||||
|
||||
|
||||
def _replacement_candidates(
|
||||
source: dict[str, Any],
|
||||
target: dict[str, dict[str, Any]],
|
||||
*,
|
||||
source_field_id: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""返回服务端可再次校验的安全替代字段摘要。"""
|
||||
return [
|
||||
{
|
||||
'field_id': candidate_id,
|
||||
'field_code': candidate.get('field_code'),
|
||||
'display_name': candidate.get('display_name'),
|
||||
}
|
||||
for candidate_id, candidate in target.items()
|
||||
if is_replacement_compatible(
|
||||
source,
|
||||
candidate,
|
||||
source_field_id=source_field_id,
|
||||
candidate_field_id=candidate_id,
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def compare_profile_schema(
|
||||
profile_definition: dict[str, Any] | None,
|
||||
profile_schema_definition: dict[str, Any] | None,
|
||||
target_schema_definition: dict[str, Any] | None,
|
||||
) -> dict[str, Any]:
|
||||
"""按 field_id 计算模板从原 Schema 到目标 Schema 的兼容性。"""
|
||||
previous = _fields(profile_schema_definition)
|
||||
target = _fields(target_schema_definition)
|
||||
referenced = referenced_field_ids(profile_definition)
|
||||
breaking: list[dict[str, Any]] = []
|
||||
review: list[dict[str, Any]] = []
|
||||
unchanged: list[str] = []
|
||||
renamed: list[dict[str, Any]] = []
|
||||
for field_id in sorted(referenced):
|
||||
before = previous.get(field_id)
|
||||
after = target.get(field_id)
|
||||
if before is None:
|
||||
breaking.append({'field_id': field_id, 'reason': 'source_field_missing'})
|
||||
continue
|
||||
if after is None or after.get('enabled') is False:
|
||||
breaking.append({
|
||||
'field_id': field_id,
|
||||
'reason': 'removed_or_disabled',
|
||||
'replacement_candidates': _replacement_candidates(before, target, source_field_id=field_id),
|
||||
})
|
||||
continue
|
||||
if before is not None and before.get('scope') != after.get('scope'):
|
||||
breaking.append({
|
||||
'field_id': field_id,
|
||||
'reason': 'scope_changed',
|
||||
'before': before.get('scope'),
|
||||
'after': after.get('scope'),
|
||||
'replacement_candidates': _replacement_candidates(before, target, source_field_id=field_id),
|
||||
})
|
||||
continue
|
||||
if before is not None:
|
||||
for key, reason in (
|
||||
('value_type', 'value_type_changed'),
|
||||
('collection_mode', 'collection_mode_changed'),
|
||||
('field_category', 'field_category_changed'),
|
||||
('required', 'required_changed'),
|
||||
('normalizer_key', 'normalizer_changed'),
|
||||
('comparator_key', 'comparator_changed'),
|
||||
('allowed_sources', 'allowed_sources_changed'),
|
||||
):
|
||||
if before.get(key) != after.get(key):
|
||||
candidates = _replacement_candidates(before, target, source_field_id=field_id)
|
||||
breaking.append({'field_id': field_id, 'reason': reason, 'before': before.get(key), 'after': after.get(key), 'replacement_candidates': candidates})
|
||||
break
|
||||
if breaking and breaking[-1]['field_id'] == field_id:
|
||||
continue
|
||||
for key in (
|
||||
'validator_keys', 'enum_options', 'evidence_policy', 'extraction_instruction',
|
||||
'relation_role', 'business_purpose', 'auto_create_key_field', 'minimum_confidence',
|
||||
):
|
||||
if before.get(key) != after.get(key):
|
||||
review.append({
|
||||
'field_id': field_id, 'reason': f'{key}_changed',
|
||||
'before': before.get(key), 'after': after.get(key),
|
||||
})
|
||||
old_code = str(before.get('field_code') or '') if before else ''
|
||||
new_code = str(after.get('field_code') or '')
|
||||
if old_code and old_code != new_code:
|
||||
renamed.append({'field_id': field_id, 'from': old_code, 'to': new_code})
|
||||
else:
|
||||
unchanged.append(field_id)
|
||||
return {
|
||||
'status': 'breaking' if breaking else ('review_required' if review else 'compatible'),
|
||||
'auto_upgradable': not breaking,
|
||||
'referenced_field_ids': sorted(referenced),
|
||||
'unchanged_field_ids': unchanged,
|
||||
'renamed_fields': renamed,
|
||||
'breaking_changes': breaking,
|
||||
'review_changes': review,
|
||||
}
|
||||
|
||||
|
||||
def remap_profile_field_codes(
|
||||
profile_definition: dict[str, Any],
|
||||
target_schema_definition: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""复制模板定义并按目标版本 field_id 更新 field_code,不修改已发布原定义。"""
|
||||
import copy
|
||||
|
||||
result = copy.deepcopy(profile_definition)
|
||||
target = _fields(target_schema_definition)
|
||||
for table in result.get('table_regions') or []:
|
||||
if not isinstance(table, dict):
|
||||
continue
|
||||
for layout_key in ('header_layouts', 'line_layouts'):
|
||||
for layout in table.get(layout_key) or []:
|
||||
if not isinstance(layout, dict):
|
||||
continue
|
||||
code_map: dict[str, str] = {}
|
||||
for field in layout.get('field_regions') or []:
|
||||
if not isinstance(field, dict):
|
||||
continue
|
||||
field_id = str(field.get('field_id') or '')
|
||||
target_field = target.get(field_id)
|
||||
if not target_field:
|
||||
continue
|
||||
old_code = str(field.get('field_code') or '')
|
||||
field['field_code'] = target_field.get('field_code')
|
||||
code_map[old_code] = str(target_field.get('field_code') or '')
|
||||
for output in field.get('target_fields') or []:
|
||||
if isinstance(output, dict) and output.get('field_id') in target:
|
||||
output['field_code'] = target[str(output['field_id'])].get('field_code')
|
||||
for key in ('required_fields', 'allowed_empty_fields'):
|
||||
values = layout.get(key)
|
||||
if isinstance(values, list):
|
||||
layout[key] = [code_map.get(str(code), code) for code in values]
|
||||
return result
|
||||
@@ -17,7 +17,7 @@ _SCALAR_KEYS = (
|
||||
'relation_role', 'comparator_key', 'extraction_instruction', 'context_source',
|
||||
'sensitivity_level', 'dify_exposure_policy', 'available_for_customer_identity', 'sequence',
|
||||
)
|
||||
_SET_KEYS = ('aliases', 'validator_keys', 'enum_options')
|
||||
_SET_KEYS = ('aliases', 'validator_keys', 'enum_options', 'allowed_sources')
|
||||
_EVIDENCE_POLICY_KEYS = ('required', 'source_precedence', 'conflict_policy', 'allow_single_source')
|
||||
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ SOURCE_TYPES = {
|
||||
'attachment_table', 'attachment_text', 'email_body_table', 'email_body_text',
|
||||
'backend_table', 'dify_llm',
|
||||
}
|
||||
COORDINATE_SOURCES = {'pdf_coordinate', 'ocr_coordinate'}
|
||||
CONFLICT_POLICIES = {'block', 'review', 'prefer_attachment', 'prefer_email'}
|
||||
TYPE_NORMALIZERS = {
|
||||
'string': {'trim', 'uppercase_trim', 'lowercase_trim', 'reservation_id'},
|
||||
@@ -71,6 +72,7 @@ def catalog() -> dict[str, list[str] | dict[str, list[str]]]:
|
||||
'comparators': _admin_rules(COMPARATORS),
|
||||
'relation_roles': sorted(item for item in RELATION_ROLES if item),
|
||||
'source_types': sorted(SOURCE_TYPES),
|
||||
'coordinate_sources': sorted(COORDINATE_SOURCES),
|
||||
'conflict_policies': sorted(CONFLICT_POLICIES),
|
||||
'type_normalizers': {key: _admin_rules(value) for key, value in TYPE_NORMALIZERS.items()},
|
||||
'type_validators': {key: _admin_rules(value) for key, value in TYPE_VALIDATORS.items()},
|
||||
|
||||
@@ -28,6 +28,7 @@ from app.models import (
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaAuditEvent,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldObservation,
|
||||
ShippingOrderFieldDecision,
|
||||
@@ -39,6 +40,7 @@ from app.services.shipping_notice.context_fields.provider_registry import regist
|
||||
from app.services.shipping_notice.order_schema.registry import (
|
||||
COLLECTION_MODES,
|
||||
COMPARATORS,
|
||||
COORDINATE_SOURCES,
|
||||
CONFLICT_POLICIES,
|
||||
FIELD_SCOPES,
|
||||
FIELD_CATEGORIES,
|
||||
@@ -52,6 +54,7 @@ from app.services.shipping_notice.order_schema.registry import (
|
||||
VALIDATORS,
|
||||
catalog,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.compatibility import compare_profile_schema
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
from app.services.shipping_notice.order_schema.diff import compare_definitions
|
||||
|
||||
@@ -595,6 +598,53 @@ def get_version_usage(version_id: int, *, page: int = 1, page_size: int = 20) ->
|
||||
}
|
||||
|
||||
|
||||
def get_profile_impact(version_id: int) -> dict[str, Any]:
|
||||
"""评估目标 Schema 版本对已发布订单文档 Profile 的影响,不修改任何配置。"""
|
||||
schema = _require_schema()
|
||||
target = _require_version(version_id, schema=schema)
|
||||
profiles = ShippingOrderDocumentProfile.query.filter(
|
||||
ShippingOrderDocumentProfile.status.in_(['published', 'draft']),
|
||||
).order_by(
|
||||
ShippingOrderDocumentProfile.profile_code.asc(),
|
||||
ShippingOrderDocumentProfile.version.desc(),
|
||||
).all()
|
||||
items: list[dict[str, Any]] = []
|
||||
for profile in profiles:
|
||||
source = profile.schema_version
|
||||
compatibility = compare_profile_schema(
|
||||
profile.definition_json,
|
||||
source.definition_json if source is not None else None,
|
||||
target.definition_json,
|
||||
)
|
||||
items.append({
|
||||
'profile_id': profile.id,
|
||||
'profile_code': profile.profile_code,
|
||||
'profile_version': profile.version,
|
||||
'profile_status': profile.status,
|
||||
'source_schema_version_id': profile.schema_version_id,
|
||||
'source_schema_version': source.version if source is not None else None,
|
||||
'target_schema_version_id': target.id,
|
||||
'target_schema_version': target.version,
|
||||
'status': compatibility['status'],
|
||||
'auto_upgradable': compatibility['auto_upgradable'],
|
||||
'renamed_fields': compatibility['renamed_fields'],
|
||||
'breaking_changes': compatibility['breaking_changes'],
|
||||
'review_changes': compatibility['review_changes'],
|
||||
'referenced_field_ids': compatibility['referenced_field_ids'],
|
||||
})
|
||||
return {
|
||||
'target_version': _version_payload(target, include_definition=False),
|
||||
'summary': {
|
||||
'profile_count': len(items),
|
||||
'compatible_count': sum(1 for item in items if item['status'] == 'compatible'),
|
||||
'review_required_count': sum(1 for item in items if item['status'] == 'review_required'),
|
||||
'breaking_count': sum(1 for item in items if item['status'] == 'breaking' and item['profile_status'] == 'published'),
|
||||
'draft_impact_count': sum(1 for item in items if item['profile_status'] == 'draft' and item['status'] != 'compatible'),
|
||||
},
|
||||
'items': items,
|
||||
}
|
||||
|
||||
|
||||
def _field_identity_map(version: ShippingOrderSchemaVersion) -> dict[str, dict[str, Any]]:
|
||||
"""从提取时锁定的 Schema 快照读取字段身份,避免后续目录重命名污染运行审计。"""
|
||||
return {
|
||||
@@ -936,12 +986,25 @@ def _field_runtime_references(field_id: str) -> list[str]:
|
||||
)
|
||||
if parsing_reference:
|
||||
references.append('inventory_parsing_profile')
|
||||
order_profile_reference = any(
|
||||
any(
|
||||
def profile_references_field(profile: ShippingOrderDocumentProfile) -> bool:
|
||||
"""同时识别历史列规则和 v2 表头/明细字段区域,避免退役留下悬空模板。"""
|
||||
definition = profile.definition_json or {}
|
||||
legacy_reference = any(
|
||||
str(target.get('field_id') or '') == field_id
|
||||
for rule in (profile.definition_json or {}).get('column_rules', []) if isinstance(rule, dict)
|
||||
for rule in definition.get('column_rules', []) if isinstance(rule, dict)
|
||||
for target in rule.get('target_fields', []) if isinstance(target, dict)
|
||||
)
|
||||
coordinate_reference = any(
|
||||
str(field_region.get('field_id') or '') == field_id
|
||||
for table_region in definition.get('table_regions', []) if isinstance(table_region, dict)
|
||||
for layout in list(table_region.get('header_layouts') or []) + list(table_region.get('line_layouts') or [])
|
||||
if isinstance(layout, dict)
|
||||
for field_region in layout.get('field_regions', []) if isinstance(field_region, dict)
|
||||
)
|
||||
return legacy_reference or coordinate_reference
|
||||
|
||||
order_profile_reference = any(
|
||||
profile_references_field(profile)
|
||||
for profile in ShippingOrderDocumentProfile.query.filter(
|
||||
ShippingOrderDocumentProfile.status.in_(['draft', 'published'])
|
||||
).all()
|
||||
@@ -1050,6 +1113,17 @@ def _evidence_policy(value: Any) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _coordinate_sources(value: Any) -> list[str]:
|
||||
"""规范化字段允许的坐标来源;未显式配置时 v2 模板不可绑定该字段。"""
|
||||
sources = _string_list(value if value is not None else [], field='allowed_sources')
|
||||
if set(sources) - COORDINATE_SOURCES:
|
||||
raise ValidationError(
|
||||
'allowed_sources contains unsupported coordinate source',
|
||||
code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID',
|
||||
)
|
||||
return sources
|
||||
|
||||
|
||||
def save_draft(
|
||||
version_id: int, data: dict[str, Any], *, actor_id: int | None = None,
|
||||
request_id: str | None = None,
|
||||
@@ -1164,6 +1238,7 @@ def save_draft(
|
||||
'validator_keys': validators,
|
||||
'enum_options': enum_options,
|
||||
'evidence_policy': _evidence_policy(raw.get('evidence_policy', {})),
|
||||
'allowed_sources': _coordinate_sources(raw.get('allowed_sources')),
|
||||
'relation_role': relation_role,
|
||||
'comparator_key': comparator,
|
||||
'extraction_instruction': str(raw.get('extraction_instruction') or '').strip() or None,
|
||||
@@ -1192,7 +1267,7 @@ def save_draft(
|
||||
|
||||
def publish(
|
||||
version_id: int, *, actor_id: int | None, expected_lock_version: int | None = None,
|
||||
request_id: str | None = None,
|
||||
request_id: str | None = None, confirm_profile_impact: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""发布指定锁版本的草稿,生成不可变 checksum 并退役上一发布版本。"""
|
||||
version = db.session.get(ShippingOrderSchemaVersion, version_id)
|
||||
@@ -1230,6 +1305,13 @@ def publish(
|
||||
code='SHIPPING.ORDER_SCHEMA_PUBLISH_DEPENDENCY_BLOCKED',
|
||||
details={'fields': referenced_omissions},
|
||||
)
|
||||
impact = get_profile_impact(version.id)
|
||||
if impact['summary']['breaking_count'] and not confirm_profile_impact:
|
||||
raise ConflictError(
|
||||
'Schema publish has breaking order document profile impacts; explicit confirmation is required',
|
||||
code='SHIPPING.ORDER_SCHEMA_PROFILE_IMPACT_CONFIRM_REQUIRED',
|
||||
details={'summary': impact['summary'], 'items': impact['items']},
|
||||
)
|
||||
encoded = json.dumps(definition, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode('utf-8')
|
||||
now = datetime.utcnow()
|
||||
previous = ShippingOrderSchemaVersion.query.filter_by(schema_id=version.schema_id, status='published').first()
|
||||
|
||||
Reference in new issue
Block a user