fix(shipping-notice): 修复模板签名误杀 Qty.Req 并加固订单抽取链路
收紧动态 token 过滤避免列名被剔除;同步表区裁剪、物理表门禁、邮件补充合并与对话附件折叠展示。
This commit is contained in:
1 parent
e40743871c
commit
5ce9221476
29 files changed
+1702
-108
No files matched your search
+35
-10
@@ -1965,14 +1965,25 @@ def _profile_field_band_score(*, raw: str, field_code: str, extractor_key: str)
|
||||
|
||||
|
||||
def _is_structured_part_identifier(raw: str) -> bool:
|
||||
"""仅将带数字或连接符的料号作为纠偏证据,普通描述词保持原框位。"""
|
||||
"""
|
||||
判断文本是否可作为内部料号纠偏证据。
|
||||
|
||||
核心逻辑:去首尾空白后仍须是无空格的紧凑标识(字母数字 + ._:/-),且含数字或
|
||||
连接符;含空格的贸易条款/描述串一律拒绝,避免去空格后误匹配。
|
||||
|
||||
Args:
|
||||
raw: 候选原文。
|
||||
|
||||
Returns:
|
||||
True 表示可作为 structured 料号证据。
|
||||
"""
|
||||
value = str(raw or '').strip()
|
||||
compact = re.sub(r'\s+', '', value)
|
||||
if not value or re.search(r'\s', value):
|
||||
return False
|
||||
return bool(
|
||||
not re.match(r'^(?:revision|rev)\s*:', value, re.IGNORECASE)
|
||||
and
|
||||
re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._:/-]{2,}', compact)
|
||||
and re.search(r'\d|[._:/-]', compact)
|
||||
not re.match(r'^(?:revision|rev):', value, re.IGNORECASE)
|
||||
and re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._:/-]{2,}', value)
|
||||
and re.search(r'\d|[._:/-]', value)
|
||||
)
|
||||
|
||||
|
||||
@@ -1983,11 +1994,22 @@ def _resolve_shifted_part_number_candidates(
|
||||
table_bbox: LayoutBBox,
|
||||
line_start_field_code: str,
|
||||
) -> list[CoordinateProfileLogicalRow]:
|
||||
"""在多子行模板中跳过描述折行,裁决后续唯一结构化内部料号。
|
||||
"""
|
||||
在多子行模板中跳过描述折行,裁决后续唯一结构化内部料号。
|
||||
|
||||
固定/自适应/动态三种重建都可能先把描述折行绑定到内部料号框;这里复核当前
|
||||
逻辑记录的后续候选,唯一高置信候选才替换,多个候选则保留 Review,避免改变
|
||||
没有折行的其他模板。
|
||||
核心逻辑:仅当当前位置读到的值不是 structured 料号(多为描述折行)时,才扫描
|
||||
后续视觉行;唯一高置信候选可替换,多候选则 Review。当前位置已是 structured
|
||||
时保持原值,禁止被后续条款行无条件覆盖。
|
||||
|
||||
Args:
|
||||
rows: 三种重建模式产出的逻辑明细。
|
||||
glyphs: 表区内带索引的字符。
|
||||
ordered_layouts: 按 row_offset 排序的子行布局。
|
||||
table_bbox: 重建坐标系下的表/页框。
|
||||
line_start_field_code: 起行锚点字段编码。
|
||||
|
||||
Returns:
|
||||
纠偏后的逻辑明细列表(原地更新 fields/issues)。
|
||||
"""
|
||||
part_fields = [
|
||||
field for layout in ordered_layouts
|
||||
@@ -2025,6 +2047,9 @@ def _resolve_shifted_part_number_candidates(
|
||||
current = str(row.fields.get('part_number') or '').strip()
|
||||
if not current or not row.source_row_indices:
|
||||
continue
|
||||
# 当前位置已是结构化料号:纠偏只服务描述折行,不得再扫后续条款行覆盖。
|
||||
if _is_structured_part_identifier(current):
|
||||
continue
|
||||
record_start = min(row.source_row_indices)
|
||||
record_end = (
|
||||
min(min(next_row.source_row_indices) for next_row in rows[row_position + 1:])
|
||||
|
||||
@@ -5,7 +5,7 @@ backend/app/services/shipping_notice/document_layout/order_profile.py
|
||||
依赖:Pydantic、坐标 bbox 契约、订单字段规则和已注册解析器。
|
||||
逻辑:管理员保存稳定锚点、相对区域和 field_code 绑定;order_profile_matcher 消费
|
||||
DocumentMatchProfile 分项权重与 negative_anchors;order_profile_signature 生成
|
||||
matching_signature 供运行时硬门禁与维度比对。
|
||||
matching_signature 供运行时硬门禁与维度比对。自动决胜 critical 仅 header+column。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -329,10 +329,10 @@ SCORING_DIMENSION_KEYS = (
|
||||
'optional_static_text',
|
||||
'trusted_business_context',
|
||||
)
|
||||
# table_geometry 保留为软分;MinerU 脏高度不得作为自动决胜硬门禁。
|
||||
CRITICAL_STRUCTURE_DIMENSION_KEYS = (
|
||||
'header_semantic_position',
|
||||
'column_topology',
|
||||
'table_geometry',
|
||||
)
|
||||
# 历史 v1 权重键 → v2 键;供 model_validator 迁移旧模板配置。
|
||||
_LEGACY_SCORING_WEIGHT_KEYS: dict[str, str] = {
|
||||
|
||||
@@ -4,7 +4,9 @@ services/shipping_notice/document_layout/order_profile_matcher.py
|
||||
用途:以冻结版面签名与坐标证据唯一匹配订单坐标模板,按统一七维权重做确定性综合评分。
|
||||
依赖:OrderCoordinateProfile、order_profile_signature.MATCHER_POLICY_ID、coordinate_region_text。
|
||||
逻辑:硬门禁(签名/必选锚点/排除锚点)→ 三态维度比对 → evidence_coverage 与相似度决胜;
|
||||
页存在≠page_structure 命中;line_layout 存在≠结构匹配;缺失锚点/客户提示不得满分。
|
||||
table_geometry 只比顶边/宽度(忽略 MinerU 脏 y1);critical 仅 header+column;
|
||||
主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表;
|
||||
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -34,6 +36,7 @@ from app.services.shipping_notice.document_layout.order_profile import (
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.order_profile_signature import (
|
||||
MATCHER_POLICY_ID,
|
||||
clip_table_bbox_to_business_rows,
|
||||
signature_checksum,
|
||||
)
|
||||
|
||||
@@ -167,6 +170,8 @@ def match_frozen_coordinate_profiles(
|
||||
observed = _observe_layout_features(
|
||||
layout=layout, tables=tables, pages=pages, glyph_tables=glyph_tables,
|
||||
page_glyphs=page_glyphs, signature=observed_signature,
|
||||
termination_rules=_profile_termination_rules(profile),
|
||||
exclusion_regions=_profile_exclusion_regions(profile),
|
||||
)
|
||||
if signature_body is None:
|
||||
reason_codes.append('profile_signature_missing')
|
||||
@@ -882,11 +887,20 @@ def _compute_dimension_results(
|
||||
results: dict[str, MatchDimensionResult] = {}
|
||||
|
||||
# [STEP 1] header_semantic_position:表头语义和位置必须独立于锚点硬门禁。
|
||||
# 有 required_anchors 时不做表头原子硬互斥——唯一身份由锚点承担,避免噪声表头误杀。
|
||||
enforce_header_atoms = _should_enforce_header_atom_discriminator(required_hits)
|
||||
header_result = _score_header_semantic_position(
|
||||
signature=signature, observed=observed, required_hits=required_hits,
|
||||
enforce_atom_discriminator=enforce_header_atoms,
|
||||
)
|
||||
results['header_semantic_position'] = header_result
|
||||
if (
|
||||
enforce_header_atoms
|
||||
and header_result.state == 'mismatched'
|
||||
and _header_discriminator_atoms_conflict(signature=signature, observed=observed)
|
||||
):
|
||||
hard_conflicts.append('profile_header_discriminator_conflict')
|
||||
elif (
|
||||
header_result.state == 'mismatched'
|
||||
and signature
|
||||
and signature.get('table_patterns')
|
||||
@@ -926,13 +940,27 @@ def _compute_dimension_results(
|
||||
return results, hard_conflicts
|
||||
|
||||
|
||||
def _should_enforce_header_atom_discriminator(required_hits: list[bool]) -> bool:
|
||||
"""
|
||||
判断是否启用表头原子硬互斥。
|
||||
|
||||
核心逻辑:模板若已配置必选锚点,身份由锚点门禁承担,不再用表头原子硬杀;
|
||||
仅「无必选锚点」的近亲模板才启用原子互斥。
|
||||
"""
|
||||
return not required_hits
|
||||
|
||||
|
||||
def _score_header_semantic_position(
|
||||
*,
|
||||
signature: dict[str, Any] | None,
|
||||
observed: dict[str, Any],
|
||||
required_hits: list[bool],
|
||||
enforce_atom_discriminator: bool = True,
|
||||
) -> MatchDimensionResult:
|
||||
"""比对真实表头 token、横向顺序和位置;锚点命中不替代表头结构证据。"""
|
||||
"""比对真实表头 token、横向顺序和位置。
|
||||
|
||||
核心逻辑:无必选锚点时先做表头原子硬互斥;有必选锚点则只走软评分。
|
||||
"""
|
||||
if signature is None:
|
||||
return MatchDimensionResult(state='unavailable', score=0.0)
|
||||
expected_tokens: list[str] = []
|
||||
@@ -951,6 +979,11 @@ def _score_header_semantic_position(
|
||||
)
|
||||
if not observed_tokens:
|
||||
return MatchDimensionResult(state='unavailable', score=0.0)
|
||||
if (
|
||||
enforce_atom_discriminator
|
||||
and _header_token_atoms(expected_tokens) != _header_token_atoms(observed_tokens)
|
||||
):
|
||||
return MatchDimensionResult(state='mismatched', score=0.0)
|
||||
matched = sum(1 for token in expected_tokens if token in observed_tokens)
|
||||
token_ratio = matched / len(expected_tokens)
|
||||
expected_order = [str(item).casefold() for table in signature.get('table_patterns') or [] if isinstance(table, dict) for item in table.get('header_order') or []]
|
||||
@@ -971,6 +1004,43 @@ def _score_header_semantic_position(
|
||||
)
|
||||
|
||||
|
||||
_HEADER_ATOM_STOPWORDS = frozenset({'and', 'the', 'of', 'or', 'to', 'for', 'with', 'by'})
|
||||
_HEADER_ATOM_MIN_LEN = 3
|
||||
|
||||
|
||||
def _header_token_atoms(tokens: list[str]) -> frozenset[str]:
|
||||
"""
|
||||
将表头 token 拆成稳定原子,供无锚点近亲模板互斥。
|
||||
|
||||
核心逻辑:去撇号后按非字母数字切分;过滤过短词与虚词,避免 Q'TY/No. 噪声。
|
||||
"""
|
||||
atoms: set[str] = set()
|
||||
for token in tokens:
|
||||
normalized = re.sub(r"['’]", '', str(token).casefold())
|
||||
for part in re.split(r'[^a-z0-9]+', normalized):
|
||||
if len(part) >= _HEADER_ATOM_MIN_LEN and part not in _HEADER_ATOM_STOPWORDS:
|
||||
atoms.add(part)
|
||||
return frozenset(atoms)
|
||||
|
||||
|
||||
def _header_discriminator_atoms_conflict(
|
||||
*,
|
||||
signature: dict[str, Any] | None,
|
||||
observed: dict[str, Any],
|
||||
) -> bool:
|
||||
"""签名与观测表头原子集合不一致时视为互斥冲突(仅无必选锚点路径调用)。"""
|
||||
if signature is None or not signature.get('table_patterns'):
|
||||
return False
|
||||
expected_tokens: list[str] = []
|
||||
for table in signature.get('table_patterns') or []:
|
||||
if isinstance(table, dict):
|
||||
expected_tokens.extend(str(item) for item in table.get('header_tokens') or [])
|
||||
observed_tokens = [str(item) for item in observed.get('header_tokens') or []]
|
||||
if not expected_tokens or not observed_tokens:
|
||||
return False
|
||||
return _header_token_atoms(expected_tokens) != _header_token_atoms(observed_tokens)
|
||||
|
||||
|
||||
def _score_column_topology(
|
||||
*,
|
||||
signature: dict[str, Any] | None,
|
||||
@@ -1025,7 +1095,8 @@ def _score_table_geometry(
|
||||
observed: dict[str, Any],
|
||||
profile: OrderCoordinateProfile,
|
||||
) -> MatchDimensionResult:
|
||||
"""比对表区 bbox 中位数与容差。"""
|
||||
"""比对主表身份几何:顶边与左右宽度;忽略底边高度(MinerU 粘连备注会拉高 y1)。"""
|
||||
_ = profile
|
||||
if signature is None:
|
||||
return MatchDimensionResult(state='unavailable', score=0.0)
|
||||
patterns = [item for item in signature.get('table_patterns') or [] if isinstance(item, dict)]
|
||||
@@ -1045,11 +1116,30 @@ def _score_table_geometry(
|
||||
if isinstance(tolerance, list) and len(tolerance) == 4
|
||||
else [float(tolerance[0]) if isinstance(tolerance, list) and tolerance else 0.05] * 4
|
||||
)
|
||||
best = max(best, _bbox_similarity(median, reference_bbox, tolerances=tolerances))
|
||||
best = max(
|
||||
best,
|
||||
_identity_table_geometry_similarity(
|
||||
median, reference_bbox, tolerances=tolerances,
|
||||
),
|
||||
)
|
||||
score = round(best, 6)
|
||||
return MatchDimensionResult(state='matched' if score >= 0.65 else 'mismatched', score=score)
|
||||
|
||||
|
||||
def _identity_table_geometry_similarity(
|
||||
expected: list[float], observed: list[float], *, tolerances: list[float],
|
||||
) -> float:
|
||||
"""只比较 x0/y0/x1(顶边+宽度);y1 不参与身份分,避免脏表高绑架模板匹配。"""
|
||||
# indices: 0=x0, 1=y0, 2=x1, 3=y1(忽略)
|
||||
identity_indices = (0, 1, 2)
|
||||
hits = 0
|
||||
for index in identity_indices:
|
||||
tolerance = float(tolerances[index]) if index < len(tolerances) else 0.05
|
||||
if abs(float(expected[index]) - float(observed[index])) <= tolerance:
|
||||
hits += 1
|
||||
return round(hits / len(identity_indices), 6)
|
||||
|
||||
|
||||
def _score_page_structure(
|
||||
*,
|
||||
signature: dict[str, Any] | None,
|
||||
@@ -1140,15 +1230,6 @@ def _score_trusted_business_context(
|
||||
)
|
||||
|
||||
|
||||
def _bbox_similarity(expected: list[float], observed: list[float], *, tolerances: list[float]) -> float:
|
||||
"""分别使用 x0/y0/x1/y1 容差评估表区几何。"""
|
||||
deltas = [abs(float(a) - float(b)) for a, b in zip(expected, observed)]
|
||||
if not deltas:
|
||||
return 0.0
|
||||
within = sum(1 for delta, tolerance in zip(deltas, tolerances) if delta <= tolerance)
|
||||
return round(within / len(deltas), 6)
|
||||
|
||||
|
||||
def _observe_layout_features(
|
||||
*,
|
||||
layout: dict[str, Any],
|
||||
@@ -1157,6 +1238,8 @@ def _observe_layout_features(
|
||||
glyph_tables: dict[str, Any],
|
||||
page_glyphs: dict[str, Any],
|
||||
signature: dict[str, Any] | None,
|
||||
termination_rules: list[dict[str, Any]] | None = None,
|
||||
exclusion_regions: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""从冻结 layout 聚合非敏感结构特征供维度比对。"""
|
||||
persisted = layout.get('matching_features')
|
||||
@@ -1183,6 +1266,16 @@ def _observe_layout_features(
|
||||
primary_bbox = _select_signature_primary_table_bbox(
|
||||
tables=tables, pages=pages, signature=signature,
|
||||
)
|
||||
# [STEP 1b] 业务行裁剪:仅按模板 termination/exclusion 截断粘连高度。
|
||||
primary_bbox = _clip_observed_primary_table_bbox(
|
||||
primary_bbox,
|
||||
tables=tables,
|
||||
pages=pages,
|
||||
page_glyphs=page_glyphs,
|
||||
signature=signature,
|
||||
termination_rules=termination_rules,
|
||||
exclusion_regions=exclusion_regions,
|
||||
)
|
||||
|
||||
header_tokens, column_centers, column_width_ratios = _observe_primary_table_header(
|
||||
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
|
||||
@@ -1371,6 +1464,96 @@ def _select_signature_primary_table_bbox(
|
||||
return best_bbox
|
||||
|
||||
|
||||
def _clip_observed_primary_table_bbox(
|
||||
primary_bbox: list[float] | None,
|
||||
*,
|
||||
tables: list[dict[str, Any]],
|
||||
pages: dict[str, Any],
|
||||
page_glyphs: dict[str, Any],
|
||||
signature: dict[str, Any] | None,
|
||||
termination_rules: list[dict[str, Any]] | None = None,
|
||||
exclusion_regions: list[dict[str, Any]] | None = None,
|
||||
) -> list[float] | None:
|
||||
"""对运行时主表框做业务行裁剪;无模板终止声明或定位失败时 fail-open。"""
|
||||
if not isinstance(primary_bbox, list) or len(primary_bbox) != 4:
|
||||
return primary_bbox
|
||||
page_no, page = _page_for_primary_table_bbox(
|
||||
primary_bbox, tables=tables, pages=pages,
|
||||
)
|
||||
if not isinstance(page, dict):
|
||||
return primary_bbox
|
||||
glyphs = page_glyphs.get(str(page_no)) or page_glyphs.get(page_no) or []
|
||||
header_y1 = None
|
||||
for pattern in (signature or {}).get('table_patterns') or []:
|
||||
if not isinstance(pattern, dict):
|
||||
continue
|
||||
header_bbox = pattern.get('header_bbox')
|
||||
if isinstance(header_bbox, list) and len(header_bbox) == 4:
|
||||
try:
|
||||
header_y1 = float(header_bbox[3])
|
||||
except (TypeError, ValueError):
|
||||
header_y1 = None
|
||||
break
|
||||
clipped = clip_table_bbox_to_business_rows(
|
||||
primary_bbox,
|
||||
page=page,
|
||||
glyphs=glyphs if isinstance(glyphs, list) else None,
|
||||
header_y1=header_y1,
|
||||
termination_rules=termination_rules,
|
||||
exclusion_regions=exclusion_regions,
|
||||
)
|
||||
return clipped if isinstance(clipped, list) else primary_bbox
|
||||
|
||||
|
||||
def _profile_termination_rules(profile: OrderCoordinateProfile) -> list[dict[str, Any]]:
|
||||
"""汇总模板全部表区的终止规则,供主表几何裁剪复用抽取侧契约。"""
|
||||
return [
|
||||
rule.model_dump()
|
||||
for table in profile.table_regions
|
||||
for rule in table.termination_rules
|
||||
]
|
||||
|
||||
|
||||
def _profile_exclusion_regions(profile: OrderCoordinateProfile) -> list[dict[str, Any]]:
|
||||
"""汇总模板全部表区的排除框。"""
|
||||
return [
|
||||
region.model_dump()
|
||||
for table in profile.table_regions
|
||||
for region in table.exclusion_regions
|
||||
]
|
||||
|
||||
|
||||
def _page_for_primary_table_bbox(
|
||||
primary_bbox: list[float],
|
||||
*,
|
||||
tables: list[dict[str, Any]],
|
||||
pages: dict[str, Any],
|
||||
) -> tuple[Any, dict[str, Any] | None]:
|
||||
"""按与主表框重叠最大的 layout 表定位页对象。"""
|
||||
best: tuple[float, Any, dict[str, Any]] | None = None
|
||||
for table in tables:
|
||||
page_no = table.get('page_no') or 1
|
||||
page = pages.get(str(page_no)) or pages.get(page_no)
|
||||
bbox = table.get('bbox') if isinstance(table.get('bbox'), dict) else None
|
||||
if not isinstance(page, dict) or not isinstance(bbox, dict):
|
||||
continue
|
||||
try:
|
||||
raw = [float(bbox[key]) for key in ('x0', 'y0', 'x1', 'y1')]
|
||||
width, height = float(page.get('width') or 0), float(page.get('height') or 0)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if width <= 0 or height <= 0 or raw[2] <= raw[0] or raw[3] <= raw[1]:
|
||||
continue
|
||||
normalized = raw if max(raw) <= 1 else [raw[0] / width, raw[1] / height, raw[2] / width, raw[3] / height]
|
||||
overlap = _bbox_overlap(primary_bbox, normalized)
|
||||
if best is None or overlap > best[0]:
|
||||
best = (overlap, page_no, page)
|
||||
if best is None:
|
||||
fallback = pages.get('1') or pages.get(1)
|
||||
return 1, fallback if isinstance(fallback, dict) else None
|
||||
return best[1], best[2]
|
||||
|
||||
|
||||
def _bbox_overlap(left: list[float], right: list[float]) -> float:
|
||||
"""计算两个归一化矩形的 IoU,供签名表区与实际表选择使用。"""
|
||||
x0, y0 = max(left[0], right[0]), max(left[1], right[1])
|
||||
|
||||
@@ -4,6 +4,7 @@ services/shipping_notice/document_layout/order_profile_signature.py
|
||||
用途:从模板定义与冻结样本坐标证据生成不可变版面签名(统计摘要,不含正文/URL)。
|
||||
依赖:order_profile 契约、coordinate_region_text、标准库 hashlib/json/statistics。
|
||||
逻辑:由 validation_service 在发布检查前调用;本模块不负责数据库提交或 Profile 引用更新。
|
||||
另提供 clip_table_bbox_to_business_rows,供签名观测与运行时 matcher 共用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,6 +18,7 @@ from typing import Any
|
||||
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 OrderCoordinateProfile, RelativeRegion
|
||||
from app.services.shipping_notice.order_extraction_route_contract import PROFILE_SCORING_POLICY_ID
|
||||
@@ -27,15 +29,162 @@ LAYOUT_SIGNATURE_ID = 'order-profile-layout-signature'
|
||||
MATCHER_POLICY_ID = PROFILE_SCORING_POLICY_ID
|
||||
|
||||
# 动态业务值不得进入表头签名;仅保留多样本稳定出现的固定文字。
|
||||
# 最后一条只匹配「标签 + 显式分隔符/空白数字」的粘连值(如 Qty: 24、Qty 24),
|
||||
# 不得误杀 Qty.Req / Qty Req 这类列名(点号或纯字母后缀不是业务值)。
|
||||
_DYNAMIC_TOKEN_PATTERNS = (
|
||||
re.compile(r'^\d{4}[-/\.]\d{1,2}[-/\.]\d{1,2}$'),
|
||||
re.compile(r'^\d{1,2}[-/\.]\d{1,2}[-/\.]\d{2,4}$'),
|
||||
re.compile(r'^[A-Z]{0,4}\d{5,}[A-Z0-9\-]*$', re.IGNORECASE),
|
||||
re.compile(r'^\d+([.,]\d+)?$'),
|
||||
re.compile(r'^(po|p\.?o\.?|qty|quantity|amount|price|date|no\.?|#)\s*[:#-]?\s*\S+', re.IGNORECASE),
|
||||
re.compile(
|
||||
r'^(po|p\.?o\.?|qty|quantity|amount|price|date|no\.?|#)'
|
||||
r'(?:\s*[:#=\-]\s*\S+|\s+\d)',
|
||||
re.IGNORECASE,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def clip_table_bbox_to_business_rows(
|
||||
bbox: list[float] | None,
|
||||
*,
|
||||
page: dict[str, Any],
|
||||
glyphs: list[dict[str, Any]] | None,
|
||||
header_y1: float | None = None,
|
||||
termination_rules: list[dict[str, Any]] | None = None,
|
||||
exclusion_regions: list[dict[str, Any]] | None = None,
|
||||
) -> list[float] | None:
|
||||
"""
|
||||
将主表 bbox 底边裁到业务明细结束处,去掉 MinerU 粘连的表外备注区。
|
||||
|
||||
核心逻辑:只使用模板声明的 termination_rules 锚点文案与 exclusion_regions;
|
||||
在表框内、表头下方命中最早终止点则裁 y1。无模板声明或未命中时 fail-open。
|
||||
|
||||
Args:
|
||||
bbox: 归一化 [x0, y0, x1, y1]。
|
||||
page: 含 width/height 的页对象。
|
||||
glyphs: 该页 page_glyphs。
|
||||
header_y1: 可选表头下沿(归一化)。
|
||||
termination_rules: 表区 termination_rules 的 dict 列表(含 anchor.text/match_mode/region)。
|
||||
exclusion_regions: 表区 exclusion_regions 的相对框 dict 列表。
|
||||
|
||||
Returns:
|
||||
裁剪后的 bbox,或无法裁剪时的原 bbox。
|
||||
"""
|
||||
if not isinstance(bbox, list) or len(bbox) != 4:
|
||||
return bbox
|
||||
try:
|
||||
x0, y0, x1, y1 = (float(bbox[0]), float(bbox[1]), float(bbox[2]), float(bbox[3]))
|
||||
width, height = float(page.get('width') or 0), float(page.get('height') or 0)
|
||||
except (TypeError, ValueError):
|
||||
return bbox
|
||||
if width <= 0 or height <= 0 or x1 <= x0 or y1 <= y0:
|
||||
return bbox
|
||||
|
||||
floor = float(header_y1) if header_y1 is not None else (y0 + max(0.02, (y1 - y0) * 0.08))
|
||||
floor = min(max(floor, y0), y1)
|
||||
stop_ys: list[float] = []
|
||||
|
||||
for region in exclusion_regions or []:
|
||||
if not isinstance(region, dict):
|
||||
continue
|
||||
try:
|
||||
ey0 = float(region['y0'])
|
||||
ex0, ex1 = float(region['x0']), float(region['x1'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if ey0 <= floor or ey0 >= y1:
|
||||
continue
|
||||
if ex1 < x0 or ex0 > x1:
|
||||
continue
|
||||
stop_ys.append(ey0)
|
||||
|
||||
rules = [item for item in (termination_rules or []) if isinstance(item, dict)]
|
||||
if rules and isinstance(glyphs, list) and glyphs:
|
||||
for row in visual_glyph_rows(glyphs):
|
||||
row_meta = _normalized_glyph_row(row, width=width, height=height)
|
||||
if row_meta is None:
|
||||
continue
|
||||
row_y, row_x0, row_x1, text = row_meta
|
||||
if row_y <= floor or row_y >= y1:
|
||||
continue
|
||||
if row_x1 < x0 or row_x0 > x1:
|
||||
continue
|
||||
if _row_matches_termination_rules(
|
||||
text=text, row_y=row_y, table_bbox=[x0, y0, x1, y1], rules=rules,
|
||||
):
|
||||
stop_ys.append(row_y)
|
||||
|
||||
if not stop_ys:
|
||||
return bbox
|
||||
clipped_y1 = max(floor + 1e-3, min(stop_ys) - 0.008)
|
||||
if clipped_y1 >= y1 - 1e-3:
|
||||
return bbox
|
||||
return [x0, y0, x1, round(clipped_y1, 6)]
|
||||
|
||||
|
||||
def _normalized_glyph_row(
|
||||
row: list[dict[str, Any]], *, width: float, height: float,
|
||||
) -> tuple[float, float, float, str] | None:
|
||||
"""将视觉行折叠为归一化 y/x 范围与拼接文本。"""
|
||||
xs: list[float] = []
|
||||
ys: list[float] = []
|
||||
texts: list[str] = []
|
||||
for glyph in row:
|
||||
box = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else None
|
||||
if not box:
|
||||
continue
|
||||
try:
|
||||
gx0, gy0, gx1, gy1 = float(box['x0']), float(box['y0']), float(box['x1']), float(box['y1'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
xs.extend((gx0 / width, gx1 / width))
|
||||
ys.append(((gy0 + gy1) / 2) / height)
|
||||
texts.append(str(glyph.get('text') or ''))
|
||||
if not xs or not ys:
|
||||
return None
|
||||
return sum(ys) / len(ys), min(xs), max(xs), ''.join(texts)
|
||||
|
||||
|
||||
def _row_matches_termination_rules(
|
||||
*,
|
||||
text: str,
|
||||
row_y: float,
|
||||
table_bbox: list[float],
|
||||
rules: list[dict[str, Any]],
|
||||
) -> bool:
|
||||
"""按模板 termination_rules 判断视觉行是否为业务表结束锚点。"""
|
||||
compact = ' '.join(text.split())
|
||||
if not compact:
|
||||
return False
|
||||
compact_key = compact.casefold().replace(' ', '')
|
||||
x0, y0, x1, y1 = table_bbox
|
||||
for rule in rules:
|
||||
anchor = rule.get('anchor') if isinstance(rule.get('anchor'), 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):
|
||||
try:
|
||||
# region 相对表区;换算到页面归一化 y 再约束命中带。
|
||||
ry0 = y0 + (y1 - y0) * float(region['y0'])
|
||||
ry1 = y0 + (y1 - y0) * float(region['y1'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if not ry0 <= row_y <= ry1:
|
||||
continue
|
||||
mode = str(anchor.get('match_mode') or 'contains')
|
||||
expected_key = expected.casefold().replace(' ', '')
|
||||
if mode == 'exact':
|
||||
if compact == expected or compact_key == expected_key:
|
||||
return True
|
||||
elif expected in compact or (expected_key and expected_key in compact_key):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def build_layout_signature(
|
||||
*,
|
||||
definition: dict[str, Any],
|
||||
@@ -206,7 +355,10 @@ def _build_table_pattern(*, table: Any, sample_layouts: list[dict[str, Any]]) ->
|
||||
|
||||
for layout in sample_layouts:
|
||||
observed = _observe_sample_table(
|
||||
layout, target_region=region, header_region=header_region,
|
||||
layout,
|
||||
target_region=region,
|
||||
header_region=header_region,
|
||||
table_region=table,
|
||||
)
|
||||
if observed is None:
|
||||
continue
|
||||
@@ -280,6 +432,7 @@ def _build_field_relation_graph(
|
||||
def _observe_sample_table(
|
||||
layout: dict[str, Any], *, target_region: RelativeRegion,
|
||||
header_region: RelativeRegion | None,
|
||||
table_region: Any | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""读取样本中与标注区域重叠最高的真实表格及其页级字符几何。"""
|
||||
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
|
||||
@@ -318,8 +471,25 @@ def _observe_sample_table(
|
||||
header_tokens, centers, widths = _header_observation(
|
||||
header_glyphs, page=page, bbox=bbox,
|
||||
)
|
||||
header_y1 = header_bbox[3] if isinstance(header_bbox, list) and len(header_bbox) == 4 else None
|
||||
termination_rules = [
|
||||
rule.model_dump() if hasattr(rule, 'model_dump') else rule
|
||||
for rule in (getattr(table_region, 'termination_rules', None) or [])
|
||||
]
|
||||
exclusion_regions = [
|
||||
region.model_dump() if hasattr(region, 'model_dump') else region
|
||||
for region in (getattr(table_region, 'exclusion_regions', None) or [])
|
||||
]
|
||||
clipped = clip_table_bbox_to_business_rows(
|
||||
bbox,
|
||||
page=page,
|
||||
glyphs=glyphs if isinstance(glyphs, list) else None,
|
||||
header_y1=header_y1,
|
||||
termination_rules=termination_rules or None,
|
||||
exclusion_regions=exclusion_regions or None,
|
||||
)
|
||||
return {
|
||||
'bbox': bbox,
|
||||
'bbox': clipped if isinstance(clipped, list) else bbox,
|
||||
'header_tokens': header_tokens,
|
||||
'column_centers': centers,
|
||||
'column_width_ratios': widths,
|
||||
@@ -528,7 +698,12 @@ def _split_header_tokens(text: str) -> list[str]:
|
||||
|
||||
|
||||
def _is_dynamic_token(token: str) -> bool:
|
||||
"""判断 token 是否像 PO/日期/数量等动态值。"""
|
||||
"""
|
||||
判断 token 是否像 PO/日期/数量等动态值。
|
||||
|
||||
核心逻辑:日期、料号型编码、纯数字,以及「Qty:/PO: + 值」粘连串视为动态;
|
||||
Qty.Req 等列名不含显式分隔后的值或空白数字,不得判动态。
|
||||
"""
|
||||
compact = token.strip()
|
||||
if not compact or len(compact) <= 1:
|
||||
return True
|
||||
|
||||
Reference in new issue
Block a user