feat(shipping-notice): 升级货代发货流程为五阶段,完善业务校验
将货代发货流程从四阶段扩展为五阶段,拆分上传相关逻辑至独立的货代上传阶段; 统一多语言文案修正客户状态语义,将"客户尚未识别"调整为符合业务的"客户尚未确认"; 新增严格的上传成功验证谓词,需同时满足任务状态、全部预约单上传成功、存在有效成功上传尝试三个条件方可标记为完成; 新增坐标取值模型配置,支持Legacy冻结绝对坐标和锚点框架受限平移两种模式; 更新全链路相关文档、前端组件、后端服务与测试用例,确保业务逻辑对齐新业务规则。
This commit is contained in:
1 parent
1b6483a4ea
commit
935bf26fa6
86 files changed
+2743
-311
No files matched your search
+93
@@ -8,6 +8,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
import math
|
||||
import re
|
||||
from statistics import median
|
||||
from typing import Any, Literal
|
||||
@@ -269,6 +271,7 @@ def reconstruct_coordinate_profile_rows(
|
||||
line_start_field_code: str | None = None,
|
||||
include_unanchored_rows: bool = False,
|
||||
row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns'] = 'fixed_subrows',
|
||||
coordinate_transform: dict[str, Any] | None = None,
|
||||
) -> list[CoordinateProfileLogicalRow]:
|
||||
"""
|
||||
按 v2 物理行和字段区域合并逻辑明细,不使用 MinerU 的行列结果。
|
||||
@@ -279,7 +282,22 @@ def reconstruct_coordinate_profile_rows(
|
||||
才是已授权的删除证据;未授权删除文字会被忽略。``include_deleted`` 仅供标注预览
|
||||
返回删除行证据;正式解析保持默认值,删除行不会进入业务结果。仅管理员预览可开启
|
||||
``include_unanchored_rows``,在没有任何有效起行值时返回待复核的主行字段,不能用于正式解析。
|
||||
``coordinate_transform`` 只能接收共同 matcher 已确认的 ``status=applied`` 平移;
|
||||
它只在当前调用的内存副本投影表区、物理行和字段区域,绝不修改冻结 Profile。
|
||||
"""
|
||||
projected = _project_coordinate_profile_regions(
|
||||
table_region=table_region,
|
||||
line_layouts=line_layouts,
|
||||
termination_rules=termination_rules,
|
||||
exclusion_regions=exclusion_regions,
|
||||
coordinate_transform=coordinate_transform,
|
||||
)
|
||||
if projected is None:
|
||||
return []
|
||||
table_region = projected['table_region']
|
||||
line_layouts = projected['line_layouts']
|
||||
termination_rules = projected['termination_rules']
|
||||
exclusion_regions = projected['exclusion_regions']
|
||||
start_field_code = resolve_line_start_field_code(line_start_field_code)
|
||||
bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox)
|
||||
ordered_layouts = sorted((item for item in line_layouts if isinstance(item, dict)), key=lambda item: item.get('row_offset', -1))
|
||||
@@ -451,6 +469,81 @@ def reconstruct_coordinate_profile_rows(
|
||||
return results if include_deleted else [row for row in results if row.role != 'deleted']
|
||||
|
||||
|
||||
def _project_coordinate_profile_regions(
|
||||
*,
|
||||
table_region: dict[str, Any] | None,
|
||||
line_layouts: list[dict[str, Any]],
|
||||
termination_rules: list[dict[str, Any]] | None,
|
||||
exclusion_regions: list[dict[str, Any]] | None,
|
||||
coordinate_transform: dict[str, Any] | None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""对当前重建调用复制并投影受 matcher 证明的相对坐标平移。
|
||||
|
||||
未传变换时保留 legacy 行为。传入变换必须是有限、页面内的 ``applied``
|
||||
变换;任何伪造、过界或未知状态都返回 ``None``,由调用方保持 Review,
|
||||
不能静默回退到旧绝对坐标。
|
||||
"""
|
||||
if coordinate_transform is None:
|
||||
return {
|
||||
'table_region': table_region,
|
||||
'line_layouts': line_layouts,
|
||||
'termination_rules': termination_rules,
|
||||
'exclusion_regions': exclusion_regions,
|
||||
}
|
||||
if not isinstance(coordinate_transform, dict) or coordinate_transform.get('status') != 'applied':
|
||||
return None
|
||||
try:
|
||||
translate_x = float(coordinate_transform['translate_x'])
|
||||
translate_y = float(coordinate_transform['translate_y'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
if not math.isfinite(translate_x) or not math.isfinite(translate_y):
|
||||
return None
|
||||
|
||||
def translate_region(region: Any) -> bool:
|
||||
if not isinstance(region, dict):
|
||||
return False
|
||||
try:
|
||||
x0, y0 = float(region['x0']) + translate_x, float(region['y0']) + translate_y
|
||||
x1, y1 = float(region['x1']) + translate_x, float(region['y1']) + translate_y
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return False
|
||||
if not (0 <= x0 < x1 <= 1 and 0 <= y0 < y1 <= 1):
|
||||
return False
|
||||
region.update({'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1})
|
||||
return True
|
||||
|
||||
projected_table = deepcopy(table_region) if table_region is not None else None
|
||||
projected_layouts = deepcopy(line_layouts)
|
||||
projected_terminations = deepcopy(termination_rules) if termination_rules is not None else None
|
||||
projected_exclusions = deepcopy(exclusion_regions) if exclusion_regions is not None else None
|
||||
if projected_table is not None and not translate_region(projected_table):
|
||||
return None
|
||||
for layout in projected_layouts:
|
||||
if not isinstance(layout, dict):
|
||||
return None
|
||||
region = layout.get('region')
|
||||
if region is not None and not translate_region(region):
|
||||
return None
|
||||
for field in layout.get('field_regions') or []:
|
||||
if not isinstance(field, dict) or not translate_region(field.get('region')):
|
||||
return None
|
||||
for rule in projected_terminations or []:
|
||||
anchor = rule.get('anchor') if isinstance(rule, dict) else None
|
||||
region = anchor.get('region') if isinstance(anchor, dict) else None
|
||||
if region is not None and not translate_region(region):
|
||||
return None
|
||||
for region in projected_exclusions or []:
|
||||
if not translate_region(region):
|
||||
return None
|
||||
return {
|
||||
'table_region': projected_table,
|
||||
'line_layouts': projected_layouts,
|
||||
'termination_rules': projected_terminations,
|
||||
'exclusion_regions': projected_exclusions,
|
||||
}
|
||||
|
||||
|
||||
def _reconstruct_adaptive_record_columns_profile_rows(
|
||||
*,
|
||||
glyphs: list[tuple[int, PositionedCharacter]],
|
||||
|
||||
@@ -188,6 +188,13 @@ def _fit_layout_payload_to_budget(
|
||||
|
||||
coordinate_evidence = candidate.get('coordinate_evidence')
|
||||
if isinstance(coordinate_evidence, dict):
|
||||
# [STEP] 仅在即将删除逐字符坐标时固定模板身份特征,避免改变未压缩快照的
|
||||
# checksum;后续 matcher 只能读取此投影,不能退化为页面/表框高分猜测。
|
||||
if coordinate_evidence.get('page_glyphs') is not None or coordinate_evidence.get('tables') is not None:
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
build_layout_matching_features,
|
||||
)
|
||||
candidate['matching_features'] = build_layout_matching_features(layout=candidate)
|
||||
if coordinate_evidence.pop('page_glyphs', None) is not None:
|
||||
issues.append('shipping_document_layout_page_glyphs_compacted')
|
||||
if coordinate_evidence.pop('tables', None) is not None:
|
||||
|
||||
+26
-6
@@ -44,8 +44,24 @@ def ensure_on_demand_coordinate_evidence(
|
||||
sources = _coordinate_mapping(evidence.get('sources'))
|
||||
source_pages = _coordinate_mapping(sources.get('pages'))
|
||||
tables = _coordinate_mapping(evidence.get('tables'))
|
||||
if page_nos is not None and page_nos.issubset({int(p) for p in page_glyphs if str(p).isdigit()}):
|
||||
return layout
|
||||
available_page_nos = {
|
||||
int(page_no) for page_no, glyphs in page_glyphs.items()
|
||||
if str(page_no).isdigit() and isinstance(glyphs, list) and glyphs
|
||||
}
|
||||
if page_nos is not None and page_nos.issubset(available_page_nos):
|
||||
# 当前 Layout 可能补齐了 Run 冻结快照中已被压缩的坐标证据。必须返回
|
||||
# 合并后的运行期 Layout;返回原 layout 会让调用方重新丢失这些字符坐标,
|
||||
# 从而使同版式 PDF 因快照压缩路径不同进入不同的匹配分支。
|
||||
next_layout = dict(layout)
|
||||
merged_evidence = {**evidence, 'pages': pages}
|
||||
if page_glyphs:
|
||||
merged_evidence['page_glyphs'] = page_glyphs
|
||||
if tables:
|
||||
merged_evidence['tables'] = tables
|
||||
if sources or source_pages:
|
||||
merged_evidence['sources'] = {**sources, 'pages': source_pages}
|
||||
next_layout['coordinate_evidence'] = merged_evidence
|
||||
return next_layout
|
||||
tables_by_page: dict[int, list[dict[str, Any]]] = {}
|
||||
for raw_table in layout.get('tables') or []:
|
||||
if not isinstance(raw_table, dict):
|
||||
@@ -108,8 +124,12 @@ def ensure_on_demand_coordinate_evidence(
|
||||
if table_id and chars:
|
||||
tables[table_id] = chars
|
||||
next_layout = dict(layout)
|
||||
next_layout['coordinate_evidence'] = {
|
||||
**evidence, 'pages': pages, 'page_glyphs': page_glyphs,
|
||||
'tables': tables, 'sources': {**sources, 'pages': source_pages},
|
||||
}
|
||||
merged_evidence = {**evidence, 'pages': pages}
|
||||
if page_glyphs:
|
||||
merged_evidence['page_glyphs'] = page_glyphs
|
||||
if tables:
|
||||
merged_evidence['tables'] = tables
|
||||
if sources or source_pages:
|
||||
merged_evidence['sources'] = {**sources, 'pages': source_pages}
|
||||
next_layout['coordinate_evidence'] = merged_evidence
|
||||
return next_layout
|
||||
@@ -49,6 +49,7 @@ class OrderFieldExtraction(BaseModel):
|
||||
def extract_order_fields(
|
||||
*, profile: OrderCoordinateProfile, schema_fields: dict[str, dict[str, Any]],
|
||||
coordinate_evidence: dict[str, Any], allow_ocr_preview_fallback: bool = False,
|
||||
coordinate_transform: dict[str, Any] | None = None,
|
||||
) -> list[OrderFieldExtraction]:
|
||||
"""
|
||||
用唯一文字锚点和相对值区读取订单字段,缺少页级证据时严格失败关闭。
|
||||
@@ -63,6 +64,12 @@ def extract_order_fields(
|
||||
Returns:
|
||||
每个已绑定布局对应一个候选,按模板声明顺序返回。
|
||||
"""
|
||||
effective_profile = _project_coordinate_transform(profile, coordinate_transform)
|
||||
if effective_profile is None:
|
||||
return [
|
||||
_unavailable(layout, 'order_field_coordinate_transform_invalid')
|
||||
for layout in profile.order_field_layouts
|
||||
]
|
||||
return [
|
||||
_extract_layout(
|
||||
layout=layout,
|
||||
@@ -70,10 +77,49 @@ def extract_order_fields(
|
||||
coordinate_evidence=coordinate_evidence,
|
||||
allow_ocr_preview_fallback=allow_ocr_preview_fallback,
|
||||
)
|
||||
for layout in profile.order_field_layouts
|
||||
for layout in effective_profile.order_field_layouts
|
||||
]
|
||||
|
||||
|
||||
def _project_coordinate_transform(
|
||||
profile: OrderCoordinateProfile, coordinate_transform: dict[str, Any] | None,
|
||||
) -> OrderCoordinateProfile | None:
|
||||
"""把 matcher 唯一确认的平移一次性投影到订单头布局,禁止二次估算。"""
|
||||
if coordinate_transform is None:
|
||||
return profile
|
||||
if not isinstance(coordinate_transform, dict) or coordinate_transform.get('status') != 'applied':
|
||||
return None
|
||||
try:
|
||||
dx, dy = float(coordinate_transform['translate_x']), float(coordinate_transform['translate_y'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
if not all(value == value and abs(value) != float('inf') for value in (dx, dy)):
|
||||
return None
|
||||
payload = profile.model_dump(mode='python')
|
||||
for layout in payload.get('order_field_layouts') or []:
|
||||
if not isinstance(layout, dict):
|
||||
continue
|
||||
for key in ('absolute_value_region', 'fallback_value_region'):
|
||||
region = layout.get(key)
|
||||
if isinstance(region, dict):
|
||||
_translate_region_dict(region, dx=dx, dy=dy)
|
||||
anchor = layout.get('anchor')
|
||||
if isinstance(anchor, dict) and isinstance(anchor.get('region'), dict):
|
||||
_translate_region_dict(anchor['region'], dx=dx, dy=dy)
|
||||
try:
|
||||
return OrderCoordinateProfile.model_validate(payload)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _translate_region_dict(region: dict[str, Any], *, dx: float, dy: float) -> None:
|
||||
"""原地平移归一化区域并拒绝越界;调用方随后重新校验 Profile。"""
|
||||
region['x0'] = float(region['x0']) + dx
|
||||
region['x1'] = float(region['x1']) + dx
|
||||
region['y0'] = float(region['y0']) + dy
|
||||
region['y1'] = float(region['y1']) + dy
|
||||
|
||||
|
||||
def _extract_layout(
|
||||
*, layout: OrderFieldLayout, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any],
|
||||
allow_ocr_preview_fallback: bool = False,
|
||||
|
||||
@@ -427,6 +427,46 @@ class DocumentMatchProfile(OrderProfileModel):
|
||||
return self
|
||||
|
||||
|
||||
class AnchorFrameCoordinateModel(OrderProfileModel):
|
||||
"""声明以稳定静态文字建立运行时平移坐标框架的 Profile 能力。"""
|
||||
|
||||
type: Literal['anchor_frame']
|
||||
anchors: list[AnchorRule] = Field(min_length=1, max_length=4)
|
||||
max_translate_x: float = Field(default=.03, ge=0, le=.15)
|
||||
max_translate_y: float = Field(default=.06, ge=0, le=.20)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_anchor_frame(self) -> 'AnchorFrameCoordinateModel':
|
||||
"""要求每个框架锚点都有基线区域且身份唯一,避免运行时从全文猜测基准。"""
|
||||
if any(anchor.region is None for anchor in self.anchors):
|
||||
raise ValueError('anchor frame anchors require baseline regions')
|
||||
ids = [anchor.anchor_id for anchor in self.anchors]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError('anchor frame anchor ids must be unique')
|
||||
return self
|
||||
|
||||
|
||||
class CoordinateModel(OrderProfileModel):
|
||||
"""定义坐标模板是否启用锚点框架;legacy 保持既有绝对坐标行为。"""
|
||||
|
||||
type: Literal['legacy', 'anchor_frame'] = 'legacy'
|
||||
anchors: list[AnchorRule] = Field(default_factory=list, max_length=4)
|
||||
max_translate_x: float = Field(default=.03, ge=0, le=.15)
|
||||
max_translate_y: float = Field(default=.06, ge=0, le=.20)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_coordinate_model(self) -> 'CoordinateModel':
|
||||
"""仅 anchor_frame 允许锚点配置;legacy 必须是空声明以保证路径隔离。"""
|
||||
if self.type == 'legacy' and self.anchors:
|
||||
raise ValueError('legacy coordinate model must not define frame anchors')
|
||||
if self.type == 'anchor_frame':
|
||||
AnchorFrameCoordinateModel(
|
||||
type='anchor_frame', anchors=self.anchors,
|
||||
max_translate_x=self.max_translate_x, max_translate_y=self.max_translate_y,
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class OrderCoordinateProfile(OrderProfileModel):
|
||||
"""唯一的订单坐标模板定义;运行时和管理端只消费这一种契约。"""
|
||||
profile_code: str = Field(pattern=r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
|
||||
@@ -435,6 +475,7 @@ class OrderCoordinateProfile(OrderProfileModel):
|
||||
table_regions: list[TableRegionProfile] = Field(min_length=1)
|
||||
order_field_layouts: list[OrderFieldLayout] = Field(default_factory=list)
|
||||
draft_unbound_order_field_layouts: list[DraftUnboundOrderFieldLayout] = Field(default_factory=list)
|
||||
coordinate_model: CoordinateModel = Field(default_factory=CoordinateModel)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_profile_rules(self) -> 'OrderCoordinateProfile':
|
||||
|
||||
@@ -9,6 +9,7 @@ services/shipping_notice/document_layout/order_profile_matcher.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
import re
|
||||
from typing import Any, Literal
|
||||
|
||||
@@ -17,8 +18,10 @@ from pydantic import BaseModel, ConfigDict, Field
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import (
|
||||
positioned_token_spans,
|
||||
read_coordinate_region_text,
|
||||
visual_glyph_rows,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
AnchorRule,
|
||||
CRITICAL_STRUCTURE_DIMENSION_KEYS,
|
||||
MatchDimensionResult,
|
||||
MatchDimensionState,
|
||||
@@ -31,6 +34,9 @@ from app.services.shipping_notice.document_layout.order_profile_signature import
|
||||
)
|
||||
|
||||
|
||||
LAYOUT_MATCHING_FEATURES_VERSION = 'shipping-layout-matching-features.v2'
|
||||
|
||||
|
||||
def _anchor_comparable_text(value: Any) -> str:
|
||||
"""规范化锚点比较文本,兼容 PDF 字符逐字拼接后丢失的版面空白。"""
|
||||
return ''.join(str(value or '').casefold().split())
|
||||
@@ -66,6 +72,7 @@ class ProfileMatchCandidate(BaseModel):
|
||||
dimension_scores: ProfileMatchDimensionScores | None = None
|
||||
dimension_states: dict[str, MatchDimensionState] = Field(default_factory=dict)
|
||||
margin_to_next: float | None = Field(default=None, ge=0, le=1)
|
||||
coordinate_transform: dict[str, Any] | None = None
|
||||
|
||||
|
||||
class ProfileMatchResult(BaseModel):
|
||||
@@ -136,15 +143,23 @@ def match_frozen_coordinate_profiles(
|
||||
document_match=definition.get('document_match'),
|
||||
table_regions=definition.get('table_regions'),
|
||||
order_field_layouts=definition.get('order_field_layouts') or [],
|
||||
coordinate_model=definition.get('coordinate_model') or {},
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
|
||||
reason_codes: list[str] = []
|
||||
signature_body, signature_meta = _extract_matching_signature(raw)
|
||||
coordinate_transform, transform_reasons = _resolve_coordinate_transform(
|
||||
profile=profile, pages=pages, page_glyphs=page_glyphs,
|
||||
)
|
||||
reason_codes.extend(transform_reasons)
|
||||
observed_signature = _translate_signature(
|
||||
signature=signature_body, coordinate_transform=coordinate_transform,
|
||||
)
|
||||
observed = _observe_layout_features(
|
||||
layout=layout, tables=tables, pages=pages, glyph_tables=glyph_tables,
|
||||
page_glyphs=page_glyphs, signature=signature_body,
|
||||
page_glyphs=page_glyphs, signature=observed_signature,
|
||||
)
|
||||
if signature_body is None:
|
||||
reason_codes.append('profile_signature_missing')
|
||||
@@ -190,7 +205,7 @@ def match_frozen_coordinate_profiles(
|
||||
|
||||
dimension_results, hard_conflict_codes = _compute_dimension_results(
|
||||
profile=profile,
|
||||
signature=signature_body,
|
||||
signature=observed_signature,
|
||||
observed=observed,
|
||||
tables=tables,
|
||||
pages=pages,
|
||||
@@ -200,6 +215,11 @@ def match_frozen_coordinate_profiles(
|
||||
customer_hint_id=customer_hint_id,
|
||||
)
|
||||
reason_codes.extend(hard_conflict_codes)
|
||||
if _profile_requires_unavailable_structure_evidence(
|
||||
signature=observed_signature,
|
||||
dimension_results=dimension_results,
|
||||
):
|
||||
reason_codes.append('profile_coordinate_evidence_unavailable')
|
||||
|
||||
weights = profile.document_match.scoring_weights
|
||||
score, evidence_coverage = _aggregate_dimension_score(weights=weights, dimension_results=dimension_results)
|
||||
@@ -223,6 +243,7 @@ def match_frozen_coordinate_profiles(
|
||||
matched_anchor_count=sum(required_hits) + sum(optional_hits),
|
||||
dimension_scores=dimension_scores,
|
||||
dimension_states=dimension_states,
|
||||
coordinate_transform=coordinate_transform,
|
||||
)))
|
||||
|
||||
rendered = sorted(
|
||||
@@ -251,6 +272,11 @@ def match_frozen_coordinate_profiles(
|
||||
candidate.margin_to_next = round(max(0.0, candidate.score - next_score), 6)
|
||||
|
||||
if not hard_valid:
|
||||
if any('profile_coordinate_evidence_unavailable' in item.reason_codes for item in rendered):
|
||||
return ProfileMatchResult(
|
||||
status='evidence_insufficient', candidates=rendered,
|
||||
top1_score=top1_score, top2_score=top2_score, margin=margin,
|
||||
)
|
||||
if not rendered:
|
||||
return ProfileMatchResult(
|
||||
status='no_match', candidates=rendered,
|
||||
@@ -305,6 +331,138 @@ def match_frozen_coordinate_profiles(
|
||||
)
|
||||
|
||||
|
||||
def build_layout_matching_features(*, layout: dict[str, Any]) -> dict[str, Any]:
|
||||
"""从完整坐标证据派生可持久化的候选表头特征,不保留逐字符正文。
|
||||
|
||||
特征生成不依赖任何 Profile;保存所有候选视觉行,运行时再由冻结签名选择,
|
||||
避免“无 Profile 时猜一条表头”导致压缩后永久保存错误列拓扑。
|
||||
"""
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
|
||||
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
|
||||
first_page = pages.get('1') or pages.get(1) or next(iter(pages.values()), None)
|
||||
aspect_ratio = 0.0
|
||||
if isinstance(first_page, dict):
|
||||
try:
|
||||
width, height = float(first_page.get('width') or 0), float(first_page.get('height') or 0)
|
||||
aspect_ratio = round(width / height, 6) if width > 0 and height > 0 else 0.0
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
rendered_tables: list[dict[str, Any]] = []
|
||||
for table in tables:
|
||||
bbox = _normalized_table_bbox(table=table, pages=pages)
|
||||
if bbox is None:
|
||||
continue
|
||||
candidates = _observe_header_candidates(
|
||||
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
|
||||
primary_bbox=bbox,
|
||||
)
|
||||
first = candidates[0] if candidates else {}
|
||||
rendered_tables.append({
|
||||
'bbox': bbox,
|
||||
'header_candidates': candidates,
|
||||
'header_tokens': first.get('header_tokens', []),
|
||||
'column_centers': first.get('column_centers', []),
|
||||
'column_width_ratios': first.get('column_width_ratios', []),
|
||||
})
|
||||
result = {
|
||||
'version': LAYOUT_MATCHING_FEATURES_VERSION,
|
||||
'page_structure': {
|
||||
'aspect_ratio': aspect_ratio,
|
||||
'page_count': len(pages),
|
||||
'table_count': len(tables),
|
||||
},
|
||||
'tables': rendered_tables,
|
||||
'static_text_centers': _observe_static_text_centers(
|
||||
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
|
||||
),
|
||||
}
|
||||
if not result['static_text_centers']:
|
||||
result.pop('static_text_centers')
|
||||
return result
|
||||
|
||||
|
||||
def _observe_header_candidates(
|
||||
*, glyph_tables: dict[str, Any], page_glyphs: dict[str, Any],
|
||||
pages: dict[str, Any], primary_bbox: list[float],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""提取主表顶部视觉行候选;不把数据行固化成唯一表头。"""
|
||||
if not primary_bbox or len(primary_bbox) != 4:
|
||||
return []
|
||||
page = pages.get('1') or pages.get(1)
|
||||
glyphs = page_glyphs.get('1') or page_glyphs.get(1)
|
||||
if not isinstance(glyphs, list):
|
||||
glyphs = [g for values in glyph_tables.values() if isinstance(values, list) for g in values]
|
||||
if not isinstance(page, dict) or not glyphs:
|
||||
return []
|
||||
width, height = float(page.get('width') or 0), float(page.get('height') or 0)
|
||||
if width <= 0 or height <= 0:
|
||||
return []
|
||||
table_height = max(0.001, primary_bbox[3] - primary_bbox[1])
|
||||
rows = visual_glyph_rows(glyphs)
|
||||
candidates: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
centers_y = [
|
||||
((float(g['bbox']['y0']) + float(g['bbox']['y1'])) / 2) / height
|
||||
for g in row if isinstance(g.get('bbox'), dict)
|
||||
]
|
||||
if not centers_y:
|
||||
continue
|
||||
y = sum(centers_y) / len(centers_y)
|
||||
if y < primary_bbox[1] or y > primary_bbox[1] + table_height * 0.30:
|
||||
continue
|
||||
spans = [
|
||||
item for item in positioned_token_spans(row, respect_explicit_spaces=False)
|
||||
if _usable_observed_header_token(str(item.get('text') or ''))
|
||||
][:32]
|
||||
if not spans:
|
||||
continue
|
||||
tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
|
||||
centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans]
|
||||
table_span = max(primary_bbox[2] - primary_bbox[0], 0.0001)
|
||||
widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans]
|
||||
bbox = [
|
||||
round(min(float(g['bbox']['x0']) for g in row if isinstance(g.get('bbox'), dict)) / width, 6),
|
||||
round(min(float(g['bbox']['y0']) for g in row if isinstance(g.get('bbox'), dict)) / height, 6),
|
||||
round(max(float(g['bbox']['x1']) for g in row if isinstance(g.get('bbox'), dict)) / width, 6),
|
||||
round(max(float(g['bbox']['y1']) for g in row if isinstance(g.get('bbox'), dict)) / height, 6),
|
||||
]
|
||||
candidates.append({'bbox': bbox, 'header_tokens': tokens, 'column_centers': centers, 'column_width_ratios': widths})
|
||||
candidates.sort(key=lambda item: (item['bbox'][1], -len(item['header_tokens'])))
|
||||
return candidates[:8]
|
||||
|
||||
|
||||
def _normalized_table_bbox(*, table: dict[str, Any], pages: dict[str, Any]) -> list[float] | None:
|
||||
"""将 Layout 表框转为页内归一化坐标;缺页尺寸时仅接受已经归一化的表框。"""
|
||||
bbox = table.get('bbox') if isinstance(table.get('bbox'), dict) else None
|
||||
if bbox is None:
|
||||
return None
|
||||
try:
|
||||
values = [float(bbox[key]) for key in ('x0', 'y0', 'x1', 'y1')]
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
if values[2] <= values[0] or values[3] <= values[1]:
|
||||
return None
|
||||
if max(values) <= 1:
|
||||
return [round(value, 6) for value in values]
|
||||
page_no = table.get('page_no') or 1
|
||||
page = pages.get(str(page_no)) or pages.get(page_no)
|
||||
if not isinstance(page, dict):
|
||||
return None
|
||||
try:
|
||||
width, height = float(page.get('width') or 0), float(page.get('height') or 0)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if width <= 0 or height <= 0:
|
||||
return None
|
||||
return [
|
||||
round(values[0] / width, 6), round(values[1] / height, 6),
|
||||
round(values[2] / width, 6), round(values[3] / height, 6),
|
||||
]
|
||||
|
||||
|
||||
def _selected_result(
|
||||
*,
|
||||
raw: dict[str, Any],
|
||||
@@ -343,6 +501,212 @@ def _extract_matching_signature(raw: dict[str, Any]) -> tuple[dict[str, Any] | N
|
||||
return signature, matching if isinstance(matching, dict) else {}
|
||||
|
||||
|
||||
def _resolve_coordinate_transform(
|
||||
*, profile: OrderCoordinateProfile, pages: dict[str, Any], page_glyphs: dict[str, Any],
|
||||
) -> tuple[dict[str, Any] | None, list[str]]:
|
||||
"""根据 Profile 声明的唯一静态锚点求受限平移,任何不确定性都返回硬失败原因。
|
||||
|
||||
Args:
|
||||
profile: 当前冻结坐标 Profile;仅 ``anchor_frame`` 启用此能力。
|
||||
pages: 当前 Layout 的页尺寸证据。
|
||||
page_glyphs: 当前 Layout 的页级 PDF/OCR 字符坐标。
|
||||
|
||||
Returns:
|
||||
``(transform, reason_codes)``。legacy 返回 ``(None, [])``;anchor_frame 仅在
|
||||
所有锚点唯一且变换位于声明上限内时返回 ``status=applied``。
|
||||
"""
|
||||
model = profile.coordinate_model
|
||||
if model.type != 'anchor_frame':
|
||||
return None, []
|
||||
|
||||
deltas: list[tuple[float, float]] = []
|
||||
anchor_ids: list[str] = []
|
||||
for anchor in model.anchors:
|
||||
found = _find_anchor_rule_matches(
|
||||
anchor=anchor, pages=pages, page_glyphs=page_glyphs,
|
||||
max_translate_x=min(.30, model.max_translate_x * 2),
|
||||
max_translate_y=min(.30, model.max_translate_y * 2),
|
||||
)
|
||||
if not found:
|
||||
return None, ['profile_anchor_frame_anchor_missing']
|
||||
if len(found) != 1:
|
||||
return None, ['profile_anchor_frame_anchor_ambiguous']
|
||||
page_no, bbox = found[0]
|
||||
page = pages.get(str(page_no)) or pages.get(page_no)
|
||||
if not isinstance(page, dict) or anchor.region is None:
|
||||
return None, ['profile_anchor_frame_coordinate_evidence_unavailable']
|
||||
try:
|
||||
width, height = float(page['width']), float(page['height'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None, ['profile_anchor_frame_coordinate_evidence_unavailable']
|
||||
if width <= 0 or height <= 0:
|
||||
return None, ['profile_anchor_frame_coordinate_evidence_unavailable']
|
||||
observed_x = (bbox[0] + bbox[2]) / 2 / width
|
||||
observed_y = (bbox[1] + bbox[3]) / 2 / height
|
||||
expected_x = (anchor.region.x0 + anchor.region.x1) / 2
|
||||
expected_y = (anchor.region.y0 + anchor.region.y1) / 2
|
||||
deltas.append((observed_x - expected_x, observed_y - expected_y))
|
||||
anchor_ids.append(anchor.anchor_id)
|
||||
|
||||
first_x, first_y = deltas[0]
|
||||
if any(abs(x - first_x) > .01 or abs(y - first_y) > .01 for x, y in deltas[1:]):
|
||||
return None, ['profile_anchor_frame_anchor_inconsistent']
|
||||
if abs(first_x) > model.max_translate_x or abs(first_y) > model.max_translate_y:
|
||||
return None, ['profile_anchor_frame_transform_out_of_range']
|
||||
return {
|
||||
'status': 'applied',
|
||||
'translate_x': round(first_x, 6),
|
||||
'translate_y': round(first_y, 6),
|
||||
'anchor_ids': anchor_ids,
|
||||
'reason_codes': [],
|
||||
}, []
|
||||
|
||||
|
||||
def _find_anchor_rule_matches(
|
||||
*, anchor: AnchorRule, pages: dict[str, Any], page_glyphs: dict[str, Any],
|
||||
max_translate_x: float, max_translate_y: float,
|
||||
) -> list[tuple[int, list[float]]]:
|
||||
"""在基线区加声明平移窗口内寻找唯一锚点,绝不退化为全文弱匹配。"""
|
||||
if anchor.region is None:
|
||||
return []
|
||||
expected = [_anchor_comparable_text(value) for value in [anchor.text, *anchor.aliases]]
|
||||
rendered: list[tuple[int, list[float]]] = []
|
||||
for raw_page_no, page in pages.items():
|
||||
try:
|
||||
page_no, width, height = int(raw_page_no), float(page['width']), float(page['height'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
glyphs = page_glyphs.get(str(page_no)) or page_glyphs.get(page_no)
|
||||
if width <= 0 or height <= 0 or not isinstance(glyphs, list):
|
||||
continue
|
||||
for line in _group_glyph_lines(glyphs):
|
||||
ordered = sorted(line, key=lambda item: float((item.get('bbox') or {}).get('x0') or 0))
|
||||
comparable_parts: list[str] = []
|
||||
glyph_spans: list[tuple[int, int, dict[str, Any]]] = []
|
||||
for item in ordered:
|
||||
part = _anchor_comparable_text(item.get('text') or '')
|
||||
if not part:
|
||||
continue
|
||||
start = len(''.join(comparable_parts))
|
||||
comparable_parts.append(part)
|
||||
glyph_spans.append((start, start + len(part), item))
|
||||
text = ''.join(comparable_parts)
|
||||
if not text:
|
||||
continue
|
||||
matched_box_sets: list[list[dict[str, Any]]] = []
|
||||
for value in expected:
|
||||
if not value:
|
||||
continue
|
||||
starts: list[int] = []
|
||||
offset = text.find(value)
|
||||
while offset >= 0:
|
||||
starts.append(offset)
|
||||
offset = text.find(value, offset + 1)
|
||||
if anchor.match_mode == 'exact' and not _anchor_rule_text_matches(value, text, mode='contains'):
|
||||
starts = []
|
||||
for start in starts:
|
||||
end = start + len(value)
|
||||
matched_box_sets.append([
|
||||
item for span_start, span_end, item in glyph_spans
|
||||
if span_start < end and span_end > start
|
||||
])
|
||||
if matched_box_sets:
|
||||
break
|
||||
if len(matched_box_sets) != 1 or not matched_box_sets[0]:
|
||||
if len(matched_box_sets) > 1:
|
||||
rendered.extend((page_no, [
|
||||
min(float(item['bbox']['x0']) for item in boxes if isinstance(item.get('bbox'), dict)),
|
||||
min(float(item['bbox']['y0']) for item in boxes if isinstance(item.get('bbox'), dict)),
|
||||
max(float(item['bbox']['x1']) for item in boxes if isinstance(item.get('bbox'), dict)),
|
||||
max(float(item['bbox']['y1']) for item in boxes if isinstance(item.get('bbox'), dict)),
|
||||
]) for boxes in matched_box_sets if boxes)
|
||||
continue
|
||||
matched_boxes = matched_box_sets[0]
|
||||
if not matched_boxes:
|
||||
continue
|
||||
boxes = [item.get('bbox') for item in matched_boxes if isinstance(item.get('bbox'), dict)]
|
||||
if not boxes:
|
||||
continue
|
||||
bbox = [
|
||||
min(float(item['x0']) for item in boxes), min(float(item['y0']) for item in boxes),
|
||||
max(float(item['x1']) for item in boxes), max(float(item['y1']) for item in boxes),
|
||||
]
|
||||
center_x, center_y = (bbox[0] + bbox[2]) / 2 / width, (bbox[1] + bbox[3]) / 2 / height
|
||||
if (
|
||||
max(0, anchor.region.x0 - max_translate_x) <= center_x <= min(1, anchor.region.x1 + max_translate_x)
|
||||
and max(0, anchor.region.y0 - max_translate_y) <= center_y <= min(1, anchor.region.y1 + max_translate_y)
|
||||
):
|
||||
rendered.append((page_no, bbox))
|
||||
return rendered
|
||||
|
||||
|
||||
def _group_glyph_lines(glyphs: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
|
||||
"""按字符中心 Y 聚合视觉行,供框架锚点精确匹配,不改变既有字段提取逻辑。"""
|
||||
lines: list[list[dict[str, Any]]] = []
|
||||
for glyph in sorted((item for item in glyphs if isinstance(item, dict) and isinstance(item.get('bbox'), dict)), key=lambda item: (float(item['bbox'].get('y0') or 0), float(item['bbox'].get('x0') or 0))):
|
||||
bbox = glyph['bbox']
|
||||
try:
|
||||
center_y = (float(bbox['y0']) + float(bbox['y1'])) / 2
|
||||
glyph_height = max(.01, float(bbox['y1']) - float(bbox['y0']))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if lines:
|
||||
previous = lines[-1][0]['bbox']
|
||||
previous_y = (float(previous['y0']) + float(previous['y1'])) / 2
|
||||
previous_height = max(.01, float(previous['y1']) - float(previous['y0']))
|
||||
if abs(center_y - previous_y) <= max(glyph_height, previous_height) * .65:
|
||||
lines[-1].append(glyph)
|
||||
continue
|
||||
lines.append([glyph])
|
||||
return lines
|
||||
|
||||
|
||||
def _anchor_rule_text_matches(expected: str, observed: str, *, mode: str) -> bool:
|
||||
"""按 AnchorRule 的 exact/contains 合约比较已规范化文本。"""
|
||||
return expected == observed if mode == 'exact' else expected in observed
|
||||
|
||||
|
||||
def _translate_signature(
|
||||
*, signature: dict[str, Any] | None, coordinate_transform: dict[str, Any] | None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""将当前 Profile 的签名副本映射到同一运行时框架,绝不回写冻结签名。"""
|
||||
if not signature or not coordinate_transform or coordinate_transform.get('status') != 'applied':
|
||||
return signature
|
||||
try:
|
||||
dx, dy = float(coordinate_transform['translate_x']), float(coordinate_transform['translate_y'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return signature
|
||||
translated = deepcopy(signature)
|
||||
for pattern in translated.get('table_patterns') or []:
|
||||
if not isinstance(pattern, dict):
|
||||
continue
|
||||
bbox = pattern.get('bbox') if isinstance(pattern.get('bbox'), dict) else {}
|
||||
median = bbox.get('median') if isinstance(bbox.get('median'), list) else None
|
||||
if median and len(median) == 4:
|
||||
bbox['median'] = [median[0] + dx, median[1] + dy, median[2] + dx, median[3] + dy]
|
||||
header = pattern.get('header_bbox')
|
||||
if isinstance(header, list) and len(header) == 4:
|
||||
pattern['header_bbox'] = [header[0] + dx, header[1] + dy, header[2] + dx, header[3] + dy]
|
||||
for relation in translated.get('field_relation_graph') or []:
|
||||
if isinstance(relation, dict):
|
||||
# 同一平移不会改变两锚点的相对关系,特意不修改 dx/dy。
|
||||
continue
|
||||
return translated
|
||||
|
||||
|
||||
def _profile_requires_unavailable_structure_evidence(
|
||||
*, signature: dict[str, Any] | None,
|
||||
dimension_results: dict[str, MatchDimensionResult],
|
||||
) -> bool:
|
||||
"""关键模板结构维度缺证据即禁止自动选中,不能靠缩小评分分母获得 hard match。"""
|
||||
if not signature:
|
||||
return False
|
||||
return any(
|
||||
dimension_results[key].state == 'unavailable'
|
||||
for key in CRITICAL_STRUCTURE_DIMENSION_KEYS
|
||||
)
|
||||
|
||||
|
||||
def _aggregate_dimension_score(
|
||||
*,
|
||||
weights: Any,
|
||||
@@ -664,6 +1028,17 @@ def _observe_layout_features(
|
||||
signature: dict[str, Any] | None,
|
||||
) -> dict[str, Any]:
|
||||
"""从冻结 layout 聚合非敏感结构特征供维度比对。"""
|
||||
persisted = layout.get('matching_features')
|
||||
# 完整坐标存在时必须以当前证据重算;压缩快照才允许使用 v2 投影。
|
||||
if isinstance(page_glyphs, dict) and any(isinstance(value, list) and value for value in page_glyphs.values()):
|
||||
persisted = None
|
||||
if isinstance(persisted, dict) and persisted.get('version') == LAYOUT_MATCHING_FEATURES_VERSION:
|
||||
observed = _observed_features_from_persisted_projection(
|
||||
features=persisted, signature=signature,
|
||||
)
|
||||
if observed is not None:
|
||||
return observed
|
||||
|
||||
first_page = pages.get('1') or pages.get(1) or next(iter(pages.values()), None)
|
||||
aspect_ratio = 0.0
|
||||
if isinstance(first_page, dict):
|
||||
@@ -699,6 +1074,53 @@ def _observe_layout_features(
|
||||
}
|
||||
|
||||
|
||||
def _observed_features_from_persisted_projection(
|
||||
*, features: dict[str, Any], signature: dict[str, Any] | None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""将压缩前持久化的轻量特征恢复为 matcher 输入,绝不读取逐字符正文。"""
|
||||
page_structure = features.get('page_structure')
|
||||
tables = features.get('tables')
|
||||
if not isinstance(page_structure, dict) or not isinstance(tables, list):
|
||||
return None
|
||||
candidates = [item for item in tables if isinstance(item, dict) and isinstance(item.get('bbox'), list)]
|
||||
if not candidates:
|
||||
return None
|
||||
expected = _signature_column_values(signature or {}, 'column_centers')
|
||||
primary = candidates[0]
|
||||
if expected:
|
||||
def distance(item: dict[str, Any]) -> tuple[float, int]:
|
||||
options = item.get('header_candidates') if isinstance(item.get('header_candidates'), list) else [item]
|
||||
best = min((abs(len(option.get('column_centers') or []) - len(expected)) for option in options if isinstance(option, dict)), default=999)
|
||||
return best, abs(len(item.get('column_centers') or []) - len(expected))
|
||||
primary = min(candidates, key=distance)
|
||||
options = primary.get('header_candidates') if isinstance(primary.get('header_candidates'), list) else []
|
||||
if options:
|
||||
primary = min(options, key=lambda item: abs(len(item.get('column_centers') or []) - len(expected))) | {'bbox': candidates[0].get('bbox')}
|
||||
bbox = primary.get('bbox')
|
||||
centers = primary.get('column_centers')
|
||||
widths = primary.get('column_width_ratios')
|
||||
tokens = primary.get('header_tokens')
|
||||
if not (
|
||||
isinstance(bbox, list) and len(bbox) == 4
|
||||
and isinstance(centers, list) and isinstance(widths, list) and isinstance(tokens, list)
|
||||
):
|
||||
return None
|
||||
return {
|
||||
'aspect_ratio': float(page_structure.get('aspect_ratio') or 0),
|
||||
'table_count': int(page_structure.get('table_count') or len(candidates)),
|
||||
'page_count': int(page_structure.get('page_count') or 0),
|
||||
'primary_table_bbox': bbox,
|
||||
'header_tokens': tokens,
|
||||
'column_count': len(centers),
|
||||
'column_centers': centers,
|
||||
'column_width_ratios': widths,
|
||||
'static_text_centers': (
|
||||
features.get('static_text_centers')
|
||||
if isinstance(features.get('static_text_centers'), dict) else {}
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _select_signature_primary_table_bbox(
|
||||
*, tables: list[dict[str, Any]], pages: dict[str, Any], signature: dict[str, Any] | None,
|
||||
) -> list[float] | None:
|
||||
@@ -881,11 +1303,13 @@ def _observe_static_text_centers(
|
||||
result: dict[str, list[float]] = {}
|
||||
for row in rows:
|
||||
ordered = sorted(row, key=lambda item: item['bbox'].get('x0', 0))
|
||||
text = _anchor_comparable_text(''.join(str(item.get('text') or '') for item in ordered))
|
||||
if not text:
|
||||
text = _anchor_comparable_text(''.join(str(item.get('text') or '') for item in ordered))[:80]
|
||||
if not text or len(text) >= 80:
|
||||
continue
|
||||
xs = [(float(item['bbox'].get('x0', 0)) + float(item['bbox'].get('x1', 0))) / 2 / width for item in ordered]
|
||||
ys = [(float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 / height for item in ordered]
|
||||
if len(result) >= 32:
|
||||
break
|
||||
result[text] = [round(sum(xs) / len(xs), 4), round(sum(ys) / len(ys), 4)]
|
||||
return result
|
||||
|
||||
|
||||
Reference in new issue
Block a user