feat(shipping-notice): 新增通用解析能力,优化性能并清理遗留废弃代码

This commit is contained in:
hugo committed 2026-08-23 00:27:18 +08:00
1 parent 935bf26fa6
commit 7cfd5d167e
230 files changed
+9337 -10989

No files matched your search

@@ -8,7 +8,6 @@
from __future__ import annotations
from copy import deepcopy
import math
import re
from statistics import median
@@ -17,6 +16,9 @@ from typing import Any, Literal
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.coordinate_transform import (
apply_coordinate_transform_to_region,
)
from app.services.shipping_notice.document_layout.coordinate_region_text import render_positioned_row
from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter
from app.services.shipping_notice.document_layout.order_profile_extractors import extract_profile_field_value
@@ -111,7 +113,7 @@ _HEADER_TERMS = frozenset({
'brand', 'manufacturer', 'delivery', 'shipping', 'drawing', 'rev',
})
_SUMMARY_PATTERN = re.compile(
r'(?:total\s*amount|incl\.?\s*tax|subtotal|invoice\s*bill|terms?\s*and\s*conditions?)',
r'(?:\btotal(?:\s*amount)?\b|incl\.?\s*tax|subtotal|invoice\s*bill|terms?\s*and\s*conditions?)',
re.IGNORECASE,
)
@@ -477,65 +479,64 @@ def _project_coordinate_profile_regions(
exclusion_regions: list[dict[str, Any]] | None,
coordinate_transform: dict[str, Any] | None,
) -> dict[str, Any] | None:
"""对当前重建调用复制并投影受 matcher 证明的相对坐标平移。
"""对当前重建调用复制并投影受 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:
def project_region(region: Any) -> dict[str, float] | None:
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
return None
return apply_coordinate_transform_to_region(region, coordinate_transform=coordinate_transform)
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):
projected_table = project_region(table_region) if table_region is not None else None
projected_layouts = []
projected_terminations: list[dict[str, Any]] | None = [] if termination_rules is not None else None
projected_exclusions: list[dict[str, float]] | None = [] if exclusion_regions is not None else None
if table_region is not None and projected_table is None:
return None
for layout in projected_layouts:
for layout in line_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')):
copied = dict(layout)
region = copied.get('region')
if region is not None:
projected_region = project_region(region)
if projected_region is None:
return None
for rule in projected_terminations or []:
anchor = rule.get('anchor') if isinstance(rule, dict) else None
copied['region'] = projected_region
fields = []
for field in copied.get('field_regions') or []:
if not isinstance(field, dict):
return None
projected_field = dict(field)
projected_region = project_region(field.get('region'))
if projected_region is None:
return None
projected_field['region'] = projected_region
fields.append(projected_field)
copied['field_regions'] = fields
projected_layouts.append(copied)
for rule in termination_rules or []:
if not isinstance(rule, dict):
return None
copied = dict(rule)
anchor = copied.get('anchor')
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):
if region is not None:
projected_region = project_region(region)
if projected_region is None:
return None
copied['anchor'] = {**anchor, 'region': projected_region}
assert projected_terminations is not None
projected_terminations.append(copied)
for region in exclusion_regions or []:
projected_region = project_region(region)
if projected_region is None:
return None
assert projected_exclusions is not None
projected_exclusions.append(projected_region)
return {
'table_region': projected_table,
'line_layouts': projected_layouts,
@@ -912,6 +913,86 @@ def suggest_multi_subrow_layouts(
return suggestions
def derive_incomplete_table_bbox(
*,
characters: list[PositionedCharacter | dict[str, Any]],
table_bbox: LayoutBBox | dict[str, Any],
) -> dict[str, float] | None:
"""从页级字符证据修复只覆盖表头的候选表格框。
该函数只允许沿原候选框的纵向向下扩展:必须先看到可靠的明细起行锚点,
并在其后遇到明确的合计/终止行;否则返回 ``None``。横向边界始终继承原候选,
因而不会把页面上的其他表格或普通文本合并进来。
Args:
characters: 同页完整 PDF/OCR 字符坐标,而不是已按错误表框截取的字符。
table_bbox: MinerU 或其他结构引擎产出的原始表格候选框。
Returns:
可验证的派生绝对表格框;证据不唯一或缺失时返回 ``None``。
"""
bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox)
if bbox.x1 <= bbox.x0 or bbox.y1 <= bbox.y0:
return None
try:
positioned = [
(
index,
item if isinstance(item, PositionedCharacter)
else PositionedCharacter.model_validate(item),
)
for index, item in enumerate(characters)
]
except Exception:
return None
# 只取原表横向范围内的字符,纵向上限使用页面证据的最大 y 值。
candidates = [
item for item in positioned
if bbox.x0 <= (item[1].bbox.x0 + item[1].bbox.x1) / 2 <= bbox.x1
and (item[1].bbox.y0 + item[1].bbox.y1) / 2 >= bbox.y0
]
if not candidates:
return None
bands = _group_visual_rows(candidates)
anchor_bands: list[list[tuple[int, PositionedCharacter]]] = []
summary_y0: float | None = None
for band in bands:
band_bbox = _band_bbox(band)
text = ''.join(
glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)
).strip()
if band_bbox.y1 <= bbox.y1:
continue
if _SUMMARY_PATTERN.search(text):
if anchor_bands:
summary_y0 = band_bbox.y0
break
continue
if _band_starts_item(band, bbox):
anchor_bands.append(band)
if not anchor_bands:
return None
last_data_y1 = max(glyph.bbox.y1 for band in anchor_bands for _, glyph in band)
# 续行属于同一表格,但不能将其误当成新的表格边界;取终止行前的最后字符。
for band in bands:
band_bbox = _band_bbox(band)
if band_bbox.y0 < anchor_bands[0][0][1].bbox.y0:
continue
text = ''.join(
glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)
).strip()
if _SUMMARY_PATTERN.search(text):
break
last_data_y1 = max(last_data_y1, band_bbox.y1)
end_y = summary_y0 if summary_y0 is not None else last_data_y1
if end_y <= bbox.y1:
return None
return {
'x0': float(bbox.x0), 'y0': float(bbox.y0),
'x1': float(bbox.x1), 'y1': float(end_y),
}
def suggest_header_regions(
*,
characters: list[PositionedCharacter | dict[str, Any]],
@@ -0,0 +1,133 @@
"""
services/shipping_notice/document_layout/coordinate_transform.py
用途:对冻结 Profile 的归一化几何区域应用 matcher 已证明的受限坐标变换。
依赖:标准库数学运算;由 Profile matcher 求解、订单头和订单行解析共同消费。
逻辑:默认保持 legacy 绝对坐标;仅接受已应用且通过残差/边界门禁的平移或仿射矩阵,
任何无效、过界或无法由稳定锚点证明的变换都返回 None 以进入 Review。
"""
from __future__ import annotations
import math
from copy import deepcopy
from typing import Any
def apply_coordinate_transform_to_region(
region: dict[str, Any], *, coordinate_transform: dict[str, Any] | None,
) -> dict[str, float] | None:
"""将 Profile 相对区域投影到当前文档坐标系,非法变换 fail-closed。
Args:
region: 含 x0/y0/x1/y1 的冻结归一化矩形。
coordinate_transform: Matcher 唯一候选附带的 ``status=applied`` 变换;None 表示 legacy。
Returns:
投影后的页内 bbox;矩阵将矩形四角包络,旋转后仍保留完整证据范围。
"""
try:
corners = [
(float(region['x0']), float(region['y0'])),
(float(region['x0']), float(region['y1'])),
(float(region['x1']), float(region['y0'])),
(float(region['x1']), float(region['y1'])),
]
except (KeyError, TypeError, ValueError):
return None
if not all(math.isfinite(value) for pair in corners for value in pair):
return None
if coordinate_transform is None:
return _bounded_bbox(corners)
matrix = coordinate_transform_matrix(coordinate_transform)
if matrix is None:
return None
return _bounded_bbox([_apply_matrix(matrix, x=x, y=y) for x, y in corners])
def coordinate_transform_matrix(value: dict[str, Any]) -> tuple[float, float, float, float, float, float] | None:
"""解析并校验 matcher 输出;无 matrix 的历史 applied 结果仅视为平移。"""
if not isinstance(value, dict) or value.get('status') != 'applied':
return None
raw = value.get('matrix')
if isinstance(raw, list) and len(raw) == 6:
try:
matrix = tuple(float(item) for item in raw)
except (TypeError, ValueError):
return None
else:
try:
matrix = (1.0, 0.0, float(value['translate_x']), 0.0, 1.0, float(value['translate_y']))
except (KeyError, TypeError, ValueError):
return None
if not all(math.isfinite(item) for item in matrix):
return None
a, b, _tx, d, e, _ty = matrix
determinant = a * e - b * d
if determinant <= 0 or determinant < .50 or determinant > 1.50:
return None
return matrix
def project_coordinate_profile_payload(
payload: dict[str, Any], *, coordinate_transform: dict[str, Any] | None,
) -> dict[str, Any] | None:
"""复制并统一投影 Profile 的订单头、表区、行区、字段和终止区,不回写冻结定义。"""
if coordinate_transform is None:
return deepcopy(payload)
projected = deepcopy(payload)
def project(region: Any) -> bool:
if not isinstance(region, dict):
return False
next_region = apply_coordinate_transform_to_region(region, coordinate_transform=coordinate_transform)
if next_region is None:
return False
region.clear()
region.update(next_region)
return True
for layout in projected.get('order_field_layouts') or []:
if not isinstance(layout, dict):
return None
for key in ('absolute_value_region', 'fallback_value_region'):
region = layout.get(key)
if region is not None and not project(region):
return None
anchor = layout.get('anchor')
if isinstance(anchor, dict) and anchor.get('region') is not None and not project(anchor['region']):
return None
for table in projected.get('table_regions') or []:
if not isinstance(table, dict) or not project(table.get('region')):
return None
for layout in [*(table.get('header_layouts') or []), *(table.get('line_layouts') or [])]:
if not isinstance(layout, dict) or not project(layout.get('region')):
return None
for field in layout.get('field_regions') or []:
if not isinstance(field, dict) or not project(field.get('region')):
return None
for rule in table.get('termination_rules') or []:
anchor = rule.get('anchor') if isinstance(rule, dict) else None
if isinstance(anchor, dict) and anchor.get('region') is not None and not project(anchor['region']):
return None
for region in table.get('exclusion_regions') or []:
if not project(region):
return None
return projected
def _apply_matrix(matrix: tuple[float, float, float, float, float, float], *, x: float, y: float) -> tuple[float, float]:
"""应用二维仿射矩阵,输入输出均为页内归一化坐标。"""
a, b, tx, d, e, ty = matrix
return a * x + b * y + tx, d * x + e * y + ty
def _bounded_bbox(corners: list[tuple[float, float]]) -> dict[str, float] | None:
"""将投影角点收敛为页内 bbox;旋转后越页的区域必须 Review。"""
if not corners or not all(math.isfinite(value) for pair in corners for value in pair):
return None
x0, x1 = min(x for x, _ in corners), max(x for x, _ in corners)
y0, y1 = min(y for _, y in corners), max(y for _, y in corners)
if not (0 <= x0 < x1 <= 1 and 0 <= y0 < y1 <= 1):
return None
return {'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1}
@@ -29,13 +29,32 @@ def ensure_on_demand_coordinate_evidence(
for key in legacy_keys
if isinstance(layout.get(key), dict)
}
# Run 快照可能早于最近一次布局重试;读取当前成功/失败版本仅作本次内存补充。
# Run 快照可能早于最近一次布局重试;当前 Layout 是最新解析事实,同页坐标必须
# 优先于 Run 快照,后者只能补齐当前 Layout 尚未保存的页或表。
current_version = getattr(document, 'current_layout_version', None)
current_payload = getattr(current_version, 'payload_json', None)
if isinstance(current_payload, dict):
current_evidence = current_payload.get('coordinate_evidence')
if isinstance(current_evidence, dict):
evidence = {**current_evidence, **evidence}
merged_current = dict(evidence)
for key in ('pages', 'page_glyphs', 'tables'):
snapshot_mapping = _coordinate_mapping(evidence.get(key))
current_mapping = _coordinate_mapping(current_evidence.get(key))
# 仅合并实际存在的坐标类别。空 tables 不得写入轻量快照,否则会让
# 顶层业务 tables 列表与坐标表映射的边界在后续调用中变得模糊。
if snapshot_mapping or current_mapping:
merged_current[key] = {**snapshot_mapping, **current_mapping}
snapshot_sources = _coordinate_mapping(evidence.get('sources'))
current_sources = _coordinate_mapping(current_evidence.get('sources'))
merged_current['sources'] = {
**snapshot_sources,
**current_sources,
'pages': {
**_coordinate_mapping(snapshot_sources.get('pages')),
**_coordinate_mapping(current_sources.get('pages')),
},
}
evidence = merged_current
for key in ('pages', 'page_glyphs', 'sources', 'tables'):
if key not in evidence and isinstance(current_payload.get(key), dict):
evidence[key] = current_payload[key]
@@ -14,6 +14,9 @@ from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
from app.services.shipping_notice.document_layout.coordinate_transform import (
project_coordinate_profile_payload,
)
from app.services.shipping_notice.document_layout.coordinate_region_text import render_positioned_row
from app.services.shipping_notice.document_layout.order_profile import (
AnchorRelativeRegion,
@@ -84,42 +87,20 @@ def extract_order_fields(
def _project_coordinate_transform(
profile: OrderCoordinateProfile, coordinate_transform: dict[str, Any] | None,
) -> OrderCoordinateProfile | None:
"""把 matcher 唯一确认的平移一次性投影到订单头布局,禁止二次估算。"""
"""把 matcher 唯一确认的统一变换投影到订单头布局,禁止二次估算。"""
if coordinate_transform is None:
return profile
if not isinstance(coordinate_transform, dict) or coordinate_transform.get('status') != 'applied':
payload = project_coordinate_profile_payload(
profile.model_dump(mode='python'), coordinate_transform=coordinate_transform,
)
if payload is None:
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,
@@ -428,12 +428,16 @@ class DocumentMatchProfile(OrderProfileModel):
class AnchorFrameCoordinateModel(OrderProfileModel):
"""声明以稳定静态文字建立运行时平移坐标框架的 Profile 能力。"""
"""声明以稳定静态文字建立运行时受限几何坐标框架的 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)
transform_mode: Literal['translate', 'affine'] = 'translate'
max_scale_delta: float = Field(default=.03, ge=0, le=.10)
max_rotation_degrees: float = Field(default=2.0, ge=0, le=5.0)
max_residual: float = Field(default=.01, gt=0, le=.05)
@model_validator(mode='after')
def validate_anchor_frame(self) -> 'AnchorFrameCoordinateModel':
@@ -443,6 +447,8 @@ class AnchorFrameCoordinateModel(OrderProfileModel):
ids = [anchor.anchor_id for anchor in self.anchors]
if len(ids) != len(set(ids)):
raise ValueError('anchor frame anchor ids must be unique')
if self.transform_mode == 'affine' and len(self.anchors) < 3:
raise ValueError('affine coordinate model requires at least three frame anchors')
return self
@@ -453,6 +459,10 @@ class CoordinateModel(OrderProfileModel):
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)
transform_mode: Literal['translate', 'affine'] = 'translate'
max_scale_delta: float = Field(default=.03, ge=0, le=.10)
max_rotation_degrees: float = Field(default=2.0, ge=0, le=5.0)
max_residual: float = Field(default=.01, gt=0, le=.05)
@model_validator(mode='after')
def validate_coordinate_model(self) -> 'CoordinateModel':
@@ -463,6 +473,8 @@ class CoordinateModel(OrderProfileModel):
AnchorFrameCoordinateModel(
type='anchor_frame', anchors=self.anchors,
max_translate_x=self.max_translate_x, max_translate_y=self.max_translate_y,
transform_mode=self.transform_mode, max_scale_delta=self.max_scale_delta,
max_rotation_degrees=self.max_rotation_degrees, max_residual=self.max_residual,
)
return self
@@ -10,6 +10,7 @@ services/shipping_notice/document_layout/order_profile_matcher.py
from __future__ import annotations
from copy import deepcopy
import math
import re
from typing import Any, Literal
@@ -20,6 +21,9 @@ from app.services.shipping_notice.document_layout.coordinate_region_text import
read_coordinate_region_text,
visual_glyph_rows,
)
from app.services.shipping_notice.document_layout.coordinate_transform import (
apply_coordinate_transform_to_region,
)
from app.services.shipping_notice.document_layout.order_profile import (
AnchorRule,
CRITICAL_STRUCTURE_DIMENSION_KEYS,
@@ -34,7 +38,9 @@ from app.services.shipping_notice.document_layout.order_profile_signature import
)
LAYOUT_MATCHING_FEATURES_VERSION = 'shipping-layout-matching-features.v2'
# 当前项目尚无历史运行数据;保持既有 v1 标识并在现版本一次性修正其事实投影语义,
# 避免无意义的版本兼容分支。
LAYOUT_MATCHING_FEATURES_VERSION = 'v1'
def _anchor_comparable_text(value: Any) -> str:
@@ -359,13 +365,9 @@ def build_layout_matching_features(*, layout: dict[str, Any]) -> dict[str, Any]:
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,
@@ -520,6 +522,7 @@ def _resolve_coordinate_transform(
return None, []
deltas: list[tuple[float, float]] = []
anchor_points: list[tuple[float, float, float, float]] = []
anchor_ids: list[str] = []
for anchor in model.anchors:
found = _find_anchor_rule_matches(
@@ -546,8 +549,15 @@ def _resolve_coordinate_transform(
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_points.append((expected_x, expected_y, observed_x, observed_y))
anchor_ids.append(anchor.anchor_id)
if model.transform_mode == 'affine':
transform, reason = _resolve_affine_coordinate_transform(
anchor_points=anchor_points, anchor_ids=anchor_ids, model=model,
)
return transform, [] if transform is not None else [reason]
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']
@@ -562,6 +572,92 @@ def _resolve_coordinate_transform(
}, []
def _resolve_affine_coordinate_transform(
*, anchor_points: list[tuple[float, float, float, float]], anchor_ids: list[str], model: Any,
) -> tuple[dict[str, Any] | None, str]:
"""以 Profile 显式声明的三个以上稳定锚点求受限仿射,无法证明即失败关闭。"""
if len(anchor_points) < 3:
return None, 'profile_anchor_frame_affine_anchor_insufficient'
matrix_x = _least_squares_affine_axis(anchor_points, observed_index=2)
matrix_y = _least_squares_affine_axis(anchor_points, observed_index=3)
if matrix_x is None or matrix_y is None:
return None, 'profile_anchor_frame_affine_anchor_degenerate'
a, b, tx = matrix_x
d, e, ty = matrix_y
determinant = a * e - b * d
scale_x, scale_y = math.hypot(a, d), math.hypot(b, e)
rotation_degrees = abs(math.degrees(math.atan2(d, a)))
residual = max(
math.hypot(a * x + b * y + tx - observed_x, d * x + e * y + ty - observed_y)
for x, y, observed_x, observed_y in anchor_points
)
if not all(math.isfinite(value) for value in (determinant, scale_x, scale_y, rotation_degrees, residual)):
return None, 'profile_anchor_frame_affine_invalid'
if determinant <= 0:
return None, 'profile_anchor_frame_affine_invalid'
if max(abs(scale_x - 1), abs(scale_y - 1)) > model.max_scale_delta:
return None, 'profile_anchor_frame_affine_scale_out_of_range'
if rotation_degrees > model.max_rotation_degrees:
return None, 'profile_anchor_frame_affine_rotation_out_of_range'
if residual > model.max_residual:
return None, 'profile_anchor_frame_affine_residual_out_of_range'
if abs(tx) > model.max_translate_x or abs(ty) > model.max_translate_y:
return None, 'profile_anchor_frame_transform_out_of_range'
return {
'status': 'applied',
'matrix': [round(value, 6) for value in (a, b, tx, d, e, ty)],
'translate_x': round(tx, 6),
'translate_y': round(ty, 6),
'anchor_ids': anchor_ids,
'residual': round(residual, 6),
'reason_codes': [],
}, ''
def _least_squares_affine_axis(
points: list[tuple[float, float, float, float]], *, observed_index: int,
) -> tuple[float, float, float] | None:
"""用正规方程拟合单个仿射轴;共线锚点会因奇异矩阵而被拒绝。"""
count = float(len(points))
sum_x = sum(item[0] for item in points)
sum_y = sum(item[1] for item in points)
sum_xx = sum(item[0] * item[0] for item in points)
sum_xy = sum(item[0] * item[1] for item in points)
sum_yy = sum(item[1] * item[1] for item in points)
sum_z = sum(item[observed_index] for item in points)
sum_xz = sum(item[0] * item[observed_index] for item in points)
sum_yz = sum(item[1] * item[observed_index] for item in points)
determinant = (
sum_xx * (sum_yy * count - sum_y * sum_y)
- sum_xy * (sum_xy * count - sum_y * sum_x)
+ sum_x * (sum_xy * sum_y - sum_yy * sum_x)
)
if not math.isfinite(determinant) or abs(determinant) < 1e-9:
return None
matrix = ((sum_xx, sum_xy, sum_x), (sum_xy, sum_yy, sum_y), (sum_x, sum_y, count))
target = (sum_xz, sum_yz, sum_z)
values = []
for column in range(3):
replaced = tuple(
tuple(target[row] if index == column else matrix[row][index] for index in range(3))
for row in range(3)
)
value = _determinant_3x3(replaced) / determinant
if not math.isfinite(value):
return None
values.append(value)
return values[0], values[1], values[2]
def _determinant_3x3(matrix: tuple[tuple[float, float, float], ...]) -> float:
"""返回 3x3 矩阵行列式,供无额外数值依赖的仿射拟合使用。"""
return (
matrix[0][0] * (matrix[1][1] * matrix[2][2] - matrix[1][2] * matrix[2][1])
- matrix[0][1] * (matrix[1][0] * matrix[2][2] - matrix[1][2] * matrix[2][0])
+ matrix[0][2] * (matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0])
)
def _find_anchor_rule_matches(
*, anchor: AnchorRule, pages: dict[str, Any], page_glyphs: dict[str, Any],
max_translate_x: float, max_translate_y: float,
@@ -669,24 +765,38 @@ def _anchor_rule_text_matches(expected: str, observed: str, *, mode: str) -> boo
def _translate_signature(
*, signature: dict[str, Any] | None, coordinate_transform: dict[str, Any] | None,
) -> dict[str, Any] | None:
"""将当前 Profile 的签名副本映射到同一运行时框架,绝不回写冻结签名。"""
"""将当前 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)
def project_bbox(value: Any) -> list[float] | None:
if not isinstance(value, list) or len(value) != 4:
return None
projected = apply_coordinate_transform_to_region(
{'x0': value[0], 'y0': value[1], 'x1': value[2], 'y1': value[3]},
coordinate_transform=coordinate_transform,
)
if projected is None:
return None
return [projected['x0'], projected['y0'], projected['x1'], projected['y1']]
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]
if median:
projected = project_bbox(median)
if projected is None:
return None
bbox['median'] = projected
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]
if header is not None:
projected = project_bbox(header)
if projected is None:
return None
pattern['header_bbox'] = projected
for relation in translated.get('field_relation_graph') or []:
if isinstance(relation, dict):
# 同一平移不会改变两锚点的相对关系,特意不修改 dx/dy。
@@ -1029,7 +1139,7 @@ def _observe_layout_features(
) -> dict[str, Any]:
"""从冻结 layout 聚合非敏感结构特征供维度比对。"""
persisted = layout.get('matching_features')
# 完整坐标存在时必须以当前证据重算;压缩快照才允许使用 v2 投影。
# 完整坐标存在时必须以当前证据重算;压缩快照才允许使用 v1 投影。
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:
@@ -1077,26 +1187,26 @@ def _observe_layout_features(
def _observed_features_from_persisted_projection(
*, features: dict[str, Any], signature: dict[str, Any] | None,
) -> dict[str, Any] | None:
"""将压缩前持久化的轻量特征恢复为 matcher 输入,绝不读取逐字符正文。"""
"""将完整的事实投影恢复为 matcher 输入,缺任一关键结构则拒绝匹配。
投影生成时没有 Profile 上下文,因此会保留同一主表的多个视觉行候选。运行期只能
根据冻结签名的 token、顺序和列几何联合选择;按列数选最近候选会把数据行误作表头。
"""
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)]
candidates = [
item for item in tables
if isinstance(item, dict)
and _is_complete_persisted_table_candidate(item)
]
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')
selected = _select_persisted_header_candidate(candidates=candidates, signature=signature)
if selected is None:
return None
primary, bbox = selected
centers = primary.get('column_centers')
widths = primary.get('column_width_ratios')
tokens = primary.get('header_tokens')
@@ -1121,6 +1231,80 @@ def _observed_features_from_persisted_projection(
}
def _is_complete_persisted_table_candidate(candidate: dict[str, Any]) -> bool:
"""校验 v1 投影的表和表头候选契约,防止不完整旧数据参与高分匹配。"""
bbox = candidate.get('bbox')
headers = candidate.get('header_candidates')
if not isinstance(bbox, list) or len(bbox) != 4 or not isinstance(headers, list):
return False
return any(_is_complete_persisted_header_candidate(item) for item in headers if isinstance(item, dict))
def _is_complete_persisted_header_candidate(candidate: dict[str, Any]) -> bool:
"""候选行必须同时保留 token、列中心和列宽,不能用残缺结构猜测。"""
tokens = candidate.get('header_tokens')
centers = candidate.get('column_centers')
widths = candidate.get('column_width_ratios')
return (
isinstance(tokens, list)
and isinstance(centers, list)
and isinstance(widths, list)
and bool(tokens)
and bool(centers)
and len(centers) == len(widths)
)
def _select_persisted_header_candidate(
*, candidates: list[dict[str, Any]], signature: dict[str, Any] | None,
) -> tuple[dict[str, Any], list[float]] | None:
"""按冻结签名联合选择投影表头,证据不足时返回 None 而非按列数猜测。"""
expected_tokens = [
str(token).casefold()
for pattern in (signature or {}).get('table_patterns') or []
if isinstance(pattern, dict)
for token in pattern.get('header_tokens') or []
]
expected_order = [
str(token).casefold()
for pattern in (signature or {}).get('table_patterns') or []
if isinstance(pattern, dict)
for token in pattern.get('header_order') or []
]
expected_centers = _signature_column_values(signature or {}, 'column_centers')
expected_widths = _signature_column_values(signature or {}, 'column_width_ratios')
if not expected_tokens or not expected_centers:
return None
scored: list[tuple[float, float, float, int, dict[str, Any], list[float]]] = []
for table in candidates:
bbox = table['bbox']
for header in table['header_candidates']:
if not isinstance(header, dict) or not _is_complete_persisted_header_candidate(header):
continue
tokens = [str(token).casefold() for token in header['header_tokens']]
centers = header['column_centers']
widths = header['column_width_ratios']
token_ratio = sum(token in tokens for token in expected_tokens) / len(expected_tokens)
shared = [token for token in expected_order if token in tokens]
order_ratio = 1.0
if len(shared) > 1:
positions = [tokens.index(token) for token in shared]
order_ratio = sum(left < right for left, right in zip(positions, positions[1:])) / (len(positions) - 1)
center_ratio = _sequence_similarity(expected_centers, centers, tolerance=0.08)
width_ratio = _sequence_similarity(expected_widths, widths, tolerance=0.16) if expected_widths else 1.0
count_ratio = min(len(expected_centers), len(centers)) / max(len(expected_centers), len(centers))
score = .50 * token_ratio + .15 * order_ratio + .25 * center_ratio + .05 * width_ratio + .05 * count_ratio
# token 语义或几何任一缺失都不足以把压缩投影作为结构事实。
if token_ratio < .50 or center_ratio < .50:
continue
scored.append((score, token_ratio, center_ratio, len(tokens), header, bbox))
if not scored:
return None
_, _, _, _, header, bbox = max(scored, key=lambda item: item[:4])
return header, bbox
def _select_signature_primary_table_bbox(
*, tables: list[dict[str, Any]], pages: dict[str, Any], signature: dict[str, Any] | None,
) -> list[float] | None: