feat(shipping-notice): 完善订单模板解析与库存 RPA 调度流程
- 新增行字段补充合并与订单模板匹配能力 - 优化运行时解析策略、签名校验及资料验证 - 完善库存 RPA 归档、收尾与 Worker 启动流程 - 补充前后端测试、多语言文案及功能文档
This commit is contained in:
1 parent
8f2f568f92
commit
dabf140e41
45 files changed
+2007
-151
No files matched your search
@@ -3,13 +3,61 @@ services/shipping_notice/document_layout/coordinate_region_text.py
|
||||
|
||||
用途:统一从页面坐标字符中读取受控区域文字,并恢复可靠的原始文本流空白。
|
||||
依赖:冻结 layout 的 page_glyphs/tables 字符坐标契约、PositionedCharacter 可选边界字段。
|
||||
逻辑:标注取字、模板匹配、字段抽取和版本诊断共享“原始边界优先、几何间距兜底”的渲染规则。
|
||||
逻辑:标注取字、模板匹配、字段抽取和版本诊断共享“原始边界优先、几何间距兜底”的渲染规则;
|
||||
另提供单逻辑表头折行合并(x 回退副标签并入最近列,不拆成新身份列)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal
|
||||
|
||||
# 单逻辑表头:列中心相对页宽回退超过该阈值,视为同列折行副标签。
|
||||
_HEADER_CENTER_X_REGRESSION_TOLERANCE = 0.02
|
||||
|
||||
|
||||
def merge_header_identity_wrap_tokens(
|
||||
tokens: list[str],
|
||||
centers: list[float] | None,
|
||||
widths: list[float] | None = None,
|
||||
) -> tuple[list[str], list[float] | None, list[float] | None]:
|
||||
"""
|
||||
将单逻辑表头中的折行副标签并入所属列,保留文案、不新增身份列。
|
||||
|
||||
核心逻辑:主行列中心近似单调递增;若下一 token 的中心明显回退,则并入与其
|
||||
x 最近的已有列(如 Part Number 下 Vendor Item#、Requested Arrival 下 Date)。
|
||||
多行正式表头不要调用本函数。
|
||||
|
||||
Args:
|
||||
tokens: 按阅读序的 header_tokens(可含第二视觉行)。
|
||||
centers: 与 tokens 对齐的列中心(0..1);缺失或长度不一致时原样返回。
|
||||
widths: 可选列宽比;对齐时随列保留(被并入列沿用主行宽度)。
|
||||
|
||||
Returns:
|
||||
合并后的 (tokens, centers, widths)。
|
||||
"""
|
||||
if not tokens or not centers or len(centers) != len(tokens):
|
||||
return tokens, centers, widths
|
||||
has_widths = isinstance(widths, list) and len(widths) == len(tokens)
|
||||
merged_tokens: list[str] = []
|
||||
merged_centers: list[float] = []
|
||||
merged_widths: list[float] | None = [] if has_widths else None
|
||||
max_center = float('-inf')
|
||||
for index, token in enumerate(tokens):
|
||||
center = float(centers[index])
|
||||
if merged_centers and center < max_center - _HEADER_CENTER_X_REGRESSION_TOLERANCE:
|
||||
parent = min(
|
||||
range(len(merged_centers)),
|
||||
key=lambda item: abs(merged_centers[item] - center),
|
||||
)
|
||||
merged_tokens[parent] = f'{merged_tokens[parent]} {token}'.strip()
|
||||
continue
|
||||
merged_tokens.append(str(token))
|
||||
merged_centers.append(center)
|
||||
if merged_widths is not None:
|
||||
merged_widths.append(float(widths[index]))
|
||||
max_center = max(max_center, center)
|
||||
return merged_tokens, merged_centers, merged_widths
|
||||
|
||||
|
||||
def render_positioned_row(
|
||||
glyphs: list[Any], *, geometry_gap_limit: float | None = None,
|
||||
|
||||
@@ -6,6 +6,7 @@ backend/app/services/shipping_notice/document_layout/order_profile.py
|
||||
逻辑:管理员保存稳定锚点、相对区域和 field_code 绑定;order_profile_matcher 消费
|
||||
DocumentMatchProfile 分项权重与 negative_anchors;order_profile_signature 生成
|
||||
matching_signature 供运行时硬门禁与维度比对。自动决胜 critical 仅 header+column。
|
||||
表区 region_role 区分主明细与同文档 LN 补料号补充表(line_field_supplement)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -259,6 +260,8 @@ class TableRegionProfile(OrderProfileModel):
|
||||
page_scope: Literal['first_page', 'all_pages', 'continuation_pages', 'exact_page'] = 'all_pages'
|
||||
page_no: int | None = Field(default=None, ge=1)
|
||||
region: RelativeRegion
|
||||
# business_lines=主明细命中源;line_field_supplement=同文档按 LN 补料号(如 COO),不进业务表匹配。
|
||||
region_role: Literal['business_lines', 'line_field_supplement'] = 'business_lines'
|
||||
# 逻辑明细起行锚点;默认客户 PO 行号,可使用任一已绑定明细字段。
|
||||
line_start_field_code: str | None = Field(default='customer_po_line_no', pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
# 默认沿用既有固定物理子行;自适应模式仅在模板显式选择时允许字段跨视觉行匹配。
|
||||
@@ -304,6 +307,22 @@ class TableRegionProfile(OrderProfileModel):
|
||||
field.field_code for field in self.line_layouts[0].field_regions
|
||||
}:
|
||||
raise ValueError('main line layout must bind the configured line-start field')
|
||||
if self.region_role == 'line_field_supplement':
|
||||
# 补充表只允许起行 + 客户料号/Vendor,禁止绑数量金额等以免误当业务明细。
|
||||
bound = {
|
||||
field.field_code
|
||||
for item in self.line_layouts
|
||||
for field in item.field_regions
|
||||
}
|
||||
if not self.line_start_field_code or self.line_start_field_code not in bound:
|
||||
raise ValueError('line_field_supplement requires the configured line-start field')
|
||||
allowed = {self.line_start_field_code, 'customer_part_number', 'part_number'}
|
||||
extra = sorted(bound - allowed)
|
||||
if extra:
|
||||
raise ValueError(
|
||||
'line_field_supplement may only bind line-start and part number fields; '
|
||||
f'unexpected: {", ".join(extra)}'
|
||||
)
|
||||
# A physical text band must have exactly one layout interpretation. Allowing
|
||||
# overlapping header/line regions would reintroduce the cross-row ambiguity
|
||||
# that v2 coordinate profiles are intended to eliminate.
|
||||
@@ -505,6 +524,11 @@ class OrderCoordinateProfile(OrderProfileModel):
|
||||
ids = [item.region_id for item in self.table_regions]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError('table region ids must be unique')
|
||||
if not any(
|
||||
str(getattr(item, 'region_role', None) or 'business_lines') == 'business_lines'
|
||||
for item in self.table_regions
|
||||
):
|
||||
raise ValueError('at least one business_lines table region is required')
|
||||
for index, left in enumerate(self.table_regions):
|
||||
for right in self.table_regions[index + 1:]:
|
||||
# Different exact pages may use identical coordinates without competing at runtime.
|
||||
|
||||
@@ -6,7 +6,8 @@ services/shipping_notice/document_layout/order_profile_matcher.py
|
||||
逻辑:硬门禁(签名/必选锚点/排除锚点)→ 三态维度比对 → evidence_coverage 与相似度决胜;
|
||||
table_geometry 只比顶边/宽度(忽略 MinerU 脏 y1);critical 仅 header+column;
|
||||
主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表;
|
||||
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁。
|
||||
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁;
|
||||
单逻辑表头将折行副标签按 x 并入所属列(保留文案),不拆成新身份列。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,6 +20,7 @@ from typing import Any, Literal
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import (
|
||||
merge_header_identity_wrap_tokens,
|
||||
positioned_token_spans,
|
||||
read_coordinate_region_text,
|
||||
visual_glyph_rows,
|
||||
@@ -960,13 +962,11 @@ def _score_header_semantic_position(
|
||||
"""比对真实表头 token、横向顺序和位置。
|
||||
|
||||
核心逻辑:无必选锚点时先做表头原子硬互斥;有必选锚点则只走软评分。
|
||||
期望侧先截断单逻辑表头的折行副标签污染。
|
||||
"""
|
||||
if signature is None:
|
||||
return MatchDimensionResult(state='unavailable', score=0.0)
|
||||
expected_tokens: list[str] = []
|
||||
for table in signature.get('table_patterns') or []:
|
||||
if isinstance(table, dict):
|
||||
expected_tokens.extend(str(item).casefold() for item in table.get('header_tokens') or [])
|
||||
expected_tokens = [str(item).casefold() for item in _signature_identity_header_tokens(signature)]
|
||||
observed_tokens = [str(item).casefold() for item in observed.get('header_tokens') or []]
|
||||
required_ratio = (sum(required_hits) / len(required_hits)) if required_hits else 1.0
|
||||
if not expected_tokens:
|
||||
@@ -986,7 +986,7 @@ def _score_header_semantic_position(
|
||||
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 []]
|
||||
expected_order = [str(item).casefold() for item in _signature_identity_header_order(signature)]
|
||||
observed_order = observed.get('header_tokens') or []
|
||||
shared = [item for item in expected_order if item in observed_order]
|
||||
order_ratio = 1.0
|
||||
@@ -1008,6 +1008,63 @@ _HEADER_ATOM_STOPWORDS = frozenset({'and', 'the', 'of', 'or', 'to', 'for', 'with
|
||||
_HEADER_ATOM_MIN_LEN = 3
|
||||
|
||||
|
||||
def _sanitize_signature_table_identity(
|
||||
pattern: dict[str, Any],
|
||||
) -> tuple[list[str], list[float] | None, list[float] | None]:
|
||||
"""
|
||||
按需合并单逻辑表头签名中的折行副标签。
|
||||
|
||||
核心逻辑:header_row_count==1 时按 column_centers 回退把副标签并入最近列;
|
||||
多行正式表头原样返回。兼容尚未重冻、仍把 Vendor Item#/Date 列为独立 token 的旧签名。
|
||||
"""
|
||||
raw_tokens = [str(item) for item in pattern.get('header_tokens') or []]
|
||||
centers = pattern.get('column_centers') if isinstance(pattern.get('column_centers'), list) else None
|
||||
widths = pattern.get('column_width_ratios') if isinstance(pattern.get('column_width_ratios'), list) else None
|
||||
try:
|
||||
center_values = [float(item) for item in centers] if centers is not None else None
|
||||
except (TypeError, ValueError):
|
||||
center_values = None
|
||||
try:
|
||||
width_values = [float(item) for item in widths] if widths is not None else None
|
||||
except (TypeError, ValueError):
|
||||
width_values = None
|
||||
if int(pattern.get('header_row_count') or 1) > 1:
|
||||
return raw_tokens, center_values, width_values
|
||||
return merge_header_identity_wrap_tokens(raw_tokens, center_values, width_values)
|
||||
|
||||
|
||||
def _signature_identity_header_tokens(signature: dict[str, Any] | None) -> list[str]:
|
||||
"""读取截断折行副标签后的签名表头身份 token。"""
|
||||
tokens: list[str] = []
|
||||
for pattern in (signature or {}).get('table_patterns') or []:
|
||||
if isinstance(pattern, dict):
|
||||
trimmed, _, _ = _sanitize_signature_table_identity(pattern)
|
||||
tokens.extend(trimmed)
|
||||
return tokens
|
||||
|
||||
|
||||
def _signature_identity_header_order(signature: dict[str, Any] | None) -> list[str]:
|
||||
"""读取合并折行后的 header_order;与身份 token 对齐。"""
|
||||
ordered: list[str] = []
|
||||
for pattern in (signature or {}).get('table_patterns') or []:
|
||||
if not isinstance(pattern, dict):
|
||||
continue
|
||||
tokens, _, _ = _sanitize_signature_table_identity(pattern)
|
||||
ordered.extend(tokens)
|
||||
return ordered
|
||||
|
||||
|
||||
def _signature_single_logical_header(signature: dict[str, Any] | None) -> bool:
|
||||
"""签名是否全部为逻辑一行表头(可含格内折行)。"""
|
||||
patterns = [
|
||||
item for item in (signature or {}).get('table_patterns') or []
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
if not patterns:
|
||||
return True
|
||||
return all(int(item.get('header_row_count') or 1) <= 1 for item in patterns)
|
||||
|
||||
|
||||
def _header_token_atoms(tokens: list[str]) -> frozenset[str]:
|
||||
"""
|
||||
将表头 token 拆成稳定原子,供无锚点近亲模板互斥。
|
||||
@@ -1031,10 +1088,7 @@ def _header_discriminator_atoms_conflict(
|
||||
"""签名与观测表头原子集合不一致时视为互斥冲突(仅无必选锚点路径调用)。"""
|
||||
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 [])
|
||||
expected_tokens = _signature_identity_header_tokens(signature)
|
||||
observed_tokens = [str(item) for item in observed.get('header_tokens') or []]
|
||||
if not expected_tokens or not observed_tokens:
|
||||
return False
|
||||
@@ -1075,9 +1129,15 @@ def _score_column_topology(
|
||||
for pattern, expected in zip(patterns, expected_counts):
|
||||
if expected <= 0:
|
||||
continue
|
||||
count_score = min(observed_count, expected) / max(observed_count, expected)
|
||||
expected_centers = pattern.get('column_centers') if isinstance(pattern.get('column_centers'), list) else []
|
||||
expected_widths = pattern.get('column_width_ratios') if isinstance(pattern.get('column_width_ratios'), list) else []
|
||||
tokens, expected_centers_raw, expected_widths_raw = _sanitize_signature_table_identity(pattern)
|
||||
expected_identity_count = len(tokens) or expected
|
||||
count_score = min(observed_count, expected_identity_count) / max(observed_count, expected_identity_count)
|
||||
expected_centers = expected_centers_raw if isinstance(expected_centers_raw, list) else []
|
||||
expected_widths = expected_widths_raw if isinstance(expected_widths_raw, list) else []
|
||||
if not expected_centers and isinstance(pattern.get('column_centers'), list):
|
||||
expected_centers = pattern.get('column_centers') or []
|
||||
if not expected_widths and isinstance(pattern.get('column_width_ratios'), list):
|
||||
expected_widths = pattern.get('column_width_ratios') or []
|
||||
if expected_centers and observed_centers:
|
||||
center_score = _sequence_similarity(expected_centers, observed_centers, tolerance=0.08)
|
||||
width_score = _sequence_similarity(expected_widths, observed_widths, tolerance=0.16) if expected_widths and observed_widths else 0.0
|
||||
@@ -1373,18 +1433,8 @@ 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_tokens = [str(token).casefold() for token in _signature_identity_header_tokens(signature)]
|
||||
expected_order = [str(token).casefold() for token in _signature_identity_header_order(signature)]
|
||||
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:
|
||||
@@ -1573,14 +1623,9 @@ def _band_headers_match_signature(
|
||||
|
||||
只有当固定带读到的表头 token 与签名 header_tokens 覆盖达到阈值时才视为“带仍有效”,
|
||||
直接沿用;否则(表体因上方内容折行/加行而上移或下移,固定带读空或读到错误行)
|
||||
需要回退到表体顶部的结构搜索。
|
||||
需要回退到表体顶部的结构搜索。期望侧先截断折行副标签污染。
|
||||
"""
|
||||
expected = [
|
||||
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 = [str(token).casefold() for token in _signature_identity_header_tokens(signature)]
|
||||
if not expected or not band_tokens:
|
||||
return False
|
||||
observed = [str(token).casefold() for token in band_tokens]
|
||||
@@ -1598,10 +1643,8 @@ def _observe_primary_table_header(
|
||||
) -> tuple[list[str], list[float], list[float]]:
|
||||
"""从实际主表顶部观测表头,与签名生成保持同一证据口径。
|
||||
|
||||
先读模板冻结的表头带;若该带仍能读出与签名一致的表头 token,则直接沿用(保持既有行为,
|
||||
不影响正常模板)。若固定带失准(表体因上方内容折行/加行而上移或下移,带读空或读到
|
||||
错误行),则基于已定位表体顶部做表头行搜索(与压缩快照路径一致的候选行选择逻辑),
|
||||
从而对上移/下移/任意行数位移都健壮,且不依赖上方可变内容。
|
||||
先读模板冻结的表头带;若该带仍能读出与签名一致的表头 token,则直接沿用。
|
||||
若固定带失准,则基于表体顶部做表头行搜索。单逻辑表头时把折行副标签按 x 并入所属列。
|
||||
"""
|
||||
if not primary_bbox or len(primary_bbox) != 4:
|
||||
return [], [], []
|
||||
@@ -1634,26 +1677,85 @@ def _observe_primary_table_header(
|
||||
band_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)
|
||||
band_widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans]
|
||||
# 固定带有效 → 直接沿用(对正常模板零影响)。
|
||||
single_logical = _signature_single_logical_header(signature)
|
||||
if single_logical:
|
||||
merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens(
|
||||
band_tokens, band_centers, band_widths,
|
||||
)
|
||||
band_tokens = [str(item).casefold() for item in merged_tokens]
|
||||
band_centers = list(merged_centers or [])
|
||||
band_widths = list(merged_widths or [])
|
||||
# 固定带有效 → 直接沿用。
|
||||
if _band_headers_match_signature(band_tokens=band_tokens, signature=signature):
|
||||
return band_tokens, band_centers, band_widths
|
||||
# 固定带失准(位移场景)→ 基于已定位表体顶部做表头行搜索,选与签名最匹配的一行。
|
||||
candidates = [{
|
||||
'bbox': primary_bbox,
|
||||
'header_candidates': _observe_header_candidates(
|
||||
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, primary_bbox=primary_bbox,
|
||||
),
|
||||
}]
|
||||
selected = _select_persisted_header_candidate(candidates=candidates, signature=signature)
|
||||
# 固定带失准 → 表体顶部候选行;单逻辑表头时把下一视觉行折行副标签并入。
|
||||
header_candidates = _observe_header_candidates(
|
||||
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, primary_bbox=primary_bbox,
|
||||
)
|
||||
selected = _select_persisted_header_candidate(
|
||||
candidates=[{'bbox': primary_bbox, 'header_candidates': header_candidates}],
|
||||
signature=signature,
|
||||
)
|
||||
if selected is not None:
|
||||
header, _ = selected
|
||||
return (
|
||||
[str(token).casefold() for token in header['header_tokens']],
|
||||
header['column_centers'], header['column_width_ratios'],
|
||||
)
|
||||
tokens = [str(token).casefold() for token in header['header_tokens']]
|
||||
centers = list(header['column_centers'])
|
||||
widths = list(header['column_width_ratios'])
|
||||
if single_logical:
|
||||
tokens, centers, widths = _merge_following_wrap_candidate(
|
||||
header=header,
|
||||
header_candidates=header_candidates,
|
||||
)
|
||||
return tokens, centers, widths
|
||||
return band_tokens, band_centers, band_widths
|
||||
|
||||
|
||||
def _merge_following_wrap_candidate(
|
||||
*,
|
||||
header: dict[str, Any],
|
||||
header_candidates: list[dict[str, Any]],
|
||||
) -> tuple[list[str], list[float], list[float]]:
|
||||
"""
|
||||
将选中主表头行与紧邻下一视觉行合并(折行副标签)。
|
||||
|
||||
核心逻辑:下一行 token 的列中心若相对主行回退,merge_header_identity_wrap_tokens
|
||||
会把它们并入所属列;若不构成回退则合并结果与主行等价或略增列,仍可安全返回。
|
||||
"""
|
||||
tokens = [str(token).casefold() for token in header.get('header_tokens') or []]
|
||||
centers = [float(item) for item in header.get('column_centers') or []]
|
||||
widths = [float(item) for item in header.get('column_width_ratios') or []]
|
||||
header_y1 = float((header.get('bbox') or [0, 0, 0, 0])[3])
|
||||
following = None
|
||||
for candidate in header_candidates:
|
||||
if candidate is header:
|
||||
continue
|
||||
bbox = candidate.get('bbox') if isinstance(candidate.get('bbox'), list) else None
|
||||
if not bbox or len(bbox) != 4:
|
||||
continue
|
||||
y0 = float(bbox[1])
|
||||
if y0 + 1e-6 < header_y1:
|
||||
continue
|
||||
if following is None or y0 < float(following['bbox'][1]):
|
||||
following = candidate
|
||||
if following is None:
|
||||
return tokens, centers, widths
|
||||
wrap_tokens = [str(token).casefold() for token in following.get('header_tokens') or []]
|
||||
wrap_centers = [float(item) for item in following.get('column_centers') or []]
|
||||
wrap_widths = [float(item) for item in following.get('column_width_ratios') or []]
|
||||
if not wrap_tokens or len(wrap_tokens) != len(wrap_centers):
|
||||
return tokens, centers, widths
|
||||
merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens(
|
||||
tokens + wrap_tokens,
|
||||
centers + wrap_centers,
|
||||
widths + wrap_widths if len(widths) == len(tokens) else None,
|
||||
)
|
||||
return (
|
||||
[str(item).casefold() for item in merged_tokens],
|
||||
list(merged_centers or []),
|
||||
list(merged_widths or []),
|
||||
)
|
||||
|
||||
|
||||
def _signature_header_bbox(signature: dict[str, Any] | None) -> list[float] | None:
|
||||
"""读取候选签名冻结的表头标注区域;每个候选独立取证,禁止共享整页猜测结果。"""
|
||||
for pattern in (signature or {}).get('table_patterns') or []:
|
||||
@@ -1690,9 +1792,15 @@ def _usable_observed_header_token(token: str) -> bool:
|
||||
|
||||
|
||||
def _signature_column_values(signature: dict[str, Any], key: str) -> list[float]:
|
||||
"""读取签名中首个可用表格的列结构向量。"""
|
||||
"""读取签名中首个可用表格的列结构向量,单逻辑表头时合并折行副标签后再取。"""
|
||||
for pattern in signature.get('table_patterns') or []:
|
||||
if isinstance(pattern, dict) and isinstance(pattern.get(key), list):
|
||||
if not isinstance(pattern, dict):
|
||||
continue
|
||||
_, centers, widths = _sanitize_signature_table_identity(pattern)
|
||||
selected = centers if key == 'column_centers' else widths if key == 'column_width_ratios' else None
|
||||
if isinstance(selected, list) and selected:
|
||||
return list(selected)
|
||||
if isinstance(pattern.get(key), list):
|
||||
try:
|
||||
return [float(item) for item in pattern[key]]
|
||||
except (TypeError, ValueError):
|
||||
|
||||
+18
-6
@@ -5,6 +5,7 @@ services/shipping_notice/document_layout/order_profile_parse_validation.py
|
||||
依赖:OrderCoordinateProfile、coordinate_region_text、order_profile 契约。
|
||||
逻辑:由 order_extraction_workflow 在 matcher 硬门禁后调用;确定性/idempotent;
|
||||
返回 passed/reason_codes/metrics 供 unique_match 二次裁决。
|
||||
类型 sanity 接受 MM/DD/YY;字段覆盖仅统计 business_lines。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,8 +27,9 @@ from app.services.shipping_notice.document_layout.coordinate_table_reconstructio
|
||||
|
||||
|
||||
_NUMERIC_PATTERN = re.compile(r'^-?\d+([.,]\d+)?$')
|
||||
# Hyve 等 PO 常见 MM/DD/YY;亦接受 YYYY-MM-DD / MM/DD/YYYY。
|
||||
_DATE_PATTERN = re.compile(
|
||||
r'^(?:\d{4}[-/\.]\d{1,2}[-/\.]\d{1,2}|\d{1,2}[-/\.]\d{1,2}[-/\.]\d{4})$',
|
||||
r'^(?:\d{4}[-/\.]\d{1,2}[-/\.]\d{1,2}|\d{1,2}[-/\.]\d{1,2}[-/\.]\d{2,4})$',
|
||||
)
|
||||
|
||||
|
||||
@@ -94,8 +96,13 @@ def validate_profile_parse_candidate(
|
||||
)
|
||||
|
||||
# [STEP 2] Line 字段覆盖(位移容忍:与行重建同源,避免 legacy 绝对坐标位移误报)
|
||||
# 补充表不参与发布解析门禁的字段覆盖/类型检查(正式路径另行按 LN 合并)。
|
||||
business_tables = [
|
||||
table for table in profile.table_regions
|
||||
if str(getattr(table, 'region_role', None) or 'business_lines') == 'business_lines'
|
||||
]
|
||||
line_fields = [
|
||||
field for table in profile.table_regions for layout in table.line_layouts
|
||||
field for table in business_tables for layout in table.line_layouts
|
||||
for field in layout.field_regions if field.scope == 'line'
|
||||
]
|
||||
line_coverage = _line_region_coverage_shift_tolerant(
|
||||
@@ -130,7 +137,7 @@ def validate_profile_parse_candidate(
|
||||
|
||||
required_line_codes = {
|
||||
field.field_code
|
||||
for table in profile.table_regions
|
||||
for table in business_tables
|
||||
for layout in table.line_layouts
|
||||
for field in layout.field_regions
|
||||
if field.scope == 'line'
|
||||
@@ -245,8 +252,13 @@ def _line_region_coverage_shift_tolerant(
|
||||
"""
|
||||
if not profile.table_regions:
|
||||
return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0}
|
||||
business_tables = [
|
||||
table for table in profile.table_regions
|
||||
if str(getattr(table, 'region_role', None) or 'business_lines') == 'business_lines'
|
||||
]
|
||||
tables_for_lines = business_tables or list(profile.table_regions)
|
||||
line_fields = [
|
||||
field for table in profile.table_regions for layout_item in table.line_layouts
|
||||
field for table in tables_for_lines for layout_item in table.line_layouts
|
||||
for field in layout_item.field_regions if field.scope == 'line'
|
||||
]
|
||||
if not line_fields:
|
||||
@@ -254,9 +266,9 @@ def _line_region_coverage_shift_tolerant(
|
||||
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
page_glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
|
||||
# 定位与主表区(首个含 line_layouts 的表区)重叠且在 page 上的物理表;取重叠面积最大者。
|
||||
# 定位与主表区(首个 business_lines 且含 line_layouts)重叠且在 page 上的物理表;取重叠面积最大者。
|
||||
primary_region = next(
|
||||
(table for table in profile.table_regions if table.line_layouts), None,
|
||||
(table for table in tables_for_lines if table.line_layouts), None,
|
||||
)
|
||||
raw_table = _locate_overlapping_raw_table(
|
||||
primary_region=primary_region, layout=layout, page=page, profile=profile,
|
||||
|
||||
@@ -5,6 +5,7 @@ services/shipping_notice/document_layout/order_profile_signature.py
|
||||
依赖:order_profile 契约、coordinate_region_text、标准库 hashlib/json/statistics。
|
||||
逻辑:由 validation_service 在发布检查前调用;本模块不负责数据库提交或 Profile 引用更新。
|
||||
另提供 clip_table_bbox_to_business_rows,供签名观测与运行时 matcher 共用。
|
||||
单逻辑表头行将格内折行副标签按 x 并入所属列,保留文案、不拆成新身份列。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,6 +17,7 @@ import statistics
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import (
|
||||
merge_header_identity_wrap_tokens,
|
||||
positioned_token_spans,
|
||||
read_coordinate_region_text,
|
||||
visual_glyph_rows,
|
||||
@@ -353,12 +355,15 @@ def _build_table_pattern(*, table: Any, sample_layouts: list[dict[str, Any]]) ->
|
||||
default=0,
|
||||
)
|
||||
|
||||
# 1 个 header_layout = 逻辑一行表头(可含格内折行);多 layout 才是多行正式表头。
|
||||
single_logical_header_row = len(header_layouts) <= 1
|
||||
for layout in sample_layouts:
|
||||
observed = _observe_sample_table(
|
||||
layout,
|
||||
target_region=region,
|
||||
header_region=header_region,
|
||||
table_region=table,
|
||||
single_logical_header_row=single_logical_header_row,
|
||||
)
|
||||
if observed is None:
|
||||
continue
|
||||
@@ -433,6 +438,7 @@ def _observe_sample_table(
|
||||
layout: dict[str, Any], *, target_region: RelativeRegion,
|
||||
header_region: RelativeRegion | None,
|
||||
table_region: Any | None = None,
|
||||
single_logical_header_row: bool = True,
|
||||
) -> dict[str, Any] | None:
|
||||
"""读取样本中与标注区域重叠最高的真实表格及其页级字符几何。"""
|
||||
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
|
||||
@@ -469,7 +475,10 @@ def _observe_sample_table(
|
||||
table_glyphs, page=page, bbox=bbox, header_bbox=header_bbox,
|
||||
)
|
||||
header_tokens, centers, widths = _header_observation(
|
||||
header_glyphs, page=page, bbox=bbox,
|
||||
header_glyphs,
|
||||
page=page,
|
||||
bbox=bbox,
|
||||
single_logical_header_row=single_logical_header_row,
|
||||
)
|
||||
header_y1 = header_bbox[3] if isinstance(header_bbox, list) and len(header_bbox) == 4 else None
|
||||
termination_rules = [
|
||||
@@ -556,9 +565,18 @@ def _union_relative_regions(regions: list[RelativeRegion]) -> RelativeRegion | N
|
||||
|
||||
|
||||
def _header_observation(
|
||||
glyphs: list[dict[str, Any]], *, page: dict[str, Any], bbox: list[float],
|
||||
glyphs: list[dict[str, Any]],
|
||||
*,
|
||||
page: dict[str, Any],
|
||||
bbox: list[float],
|
||||
single_logical_header_row: bool = True,
|
||||
) -> tuple[list[str], list[float], list[float]]:
|
||||
"""从表头 token 边界生成文本、中心和宽度,禁止按单字符连续间距伪造业务列。"""
|
||||
"""
|
||||
从表头 token 边界生成文本、中心和宽度,禁止按单字符连续间距伪造业务列。
|
||||
|
||||
核心逻辑:读出带内全部视觉行后,对逻辑一行表头按列中心回退把折行副标签并入
|
||||
所属列(保留 Vendor Item# / Date 文案);多行正式表头不做合并。
|
||||
"""
|
||||
try:
|
||||
page_width = float(page['width'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
@@ -571,6 +589,15 @@ def _header_observation(
|
||||
centers = [round((float(item['x0']) + float(item['x1'])) / 2 / page_width, 4) for item in spans]
|
||||
span = max(bbox[2] - bbox[0], 0.0001)
|
||||
widths = [round((float(item['x1']) - float(item['x0'])) / page_width / span, 4) for item in spans]
|
||||
if single_logical_header_row:
|
||||
merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens(
|
||||
tokens, centers, widths,
|
||||
)
|
||||
return (
|
||||
list(merged_tokens),
|
||||
list(merged_centers or []),
|
||||
list(merged_widths or []),
|
||||
)
|
||||
return tokens, centers, widths
|
||||
|
||||
|
||||
|
||||
@@ -3,7 +3,8 @@ services/shipping_notice/document_layout/runtime_parse_strategy.py
|
||||
|
||||
用途:为已唯一命中的 Coordinate/OCR 订单模板按当前文档证据选择页范围与明细行重建方式。
|
||||
依赖:仅标准库;由正式抽取与模板质量验证共同调用。
|
||||
逻辑:不修改模板,不猜测业务值;固定/自适应重建结果只有唯一可用时才被采用,冲突统一转 Review。
|
||||
逻辑:不修改模板,不猜测业务值;固定/自适应重建结果只有唯一可用时才被采用;
|
||||
二者业务值冲突时,若动态列能单侧确认其一则采用该侧(或更完整的动态结果),否则转 Review。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -75,6 +76,15 @@ def resolve_runtime_parse_strategy(
|
||||
baseline_rows = fixed_valid
|
||||
baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ())
|
||||
else:
|
||||
# [STEP] 固定/自适应业务值冲突:不得静默猜一侧;若动态列能单侧确认,再落选。
|
||||
resolved = _resolve_fixed_adaptive_ambiguity_with_dynamic(
|
||||
page_nos=page_nos,
|
||||
fixed_rows=fixed_valid,
|
||||
adaptive_rows=adaptive_valid,
|
||||
dynamic_rows=dynamic_valid,
|
||||
)
|
||||
if resolved is not None:
|
||||
return resolved
|
||||
return RuntimeParseStrategy(
|
||||
'needs_review', page_nos, None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',),
|
||||
)
|
||||
@@ -103,6 +113,67 @@ def resolve_runtime_parse_strategy(
|
||||
)
|
||||
|
||||
|
||||
def _resolve_fixed_adaptive_ambiguity_with_dynamic(
|
||||
*,
|
||||
page_nos: tuple[int, ...],
|
||||
fixed_rows: list[dict[str, Any]],
|
||||
adaptive_rows: list[dict[str, Any]],
|
||||
dynamic_rows: list[dict[str, Any]],
|
||||
) -> RuntimeParseStrategy | None:
|
||||
"""
|
||||
固定与自适应冲突时,用动态列做单侧确认。
|
||||
|
||||
核心逻辑:动态相对某一侧可覆盖(baseline/dynamic preferred),且相对另一侧
|
||||
仍 ambiguous,则采用被确认的一侧;两侧都被动态确认且动态更完整时采用动态。
|
||||
无动态证据或仍双边不清时返回 None,由调用方转 Review。
|
||||
|
||||
Args:
|
||||
page_nos: 当前有坐标证据的页码。
|
||||
fixed_rows: 有效固定子行。
|
||||
adaptive_rows: 有效自适应行。
|
||||
dynamic_rows: 有效动态列行;空则无法仲裁。
|
||||
|
||||
Returns:
|
||||
可安全选中的策略;无法仲裁时为 None。
|
||||
"""
|
||||
if not dynamic_rows:
|
||||
return None
|
||||
fixed_vs_dyn = _compare_dynamic_row_coverage(
|
||||
baseline_rows=fixed_rows, dynamic_rows=dynamic_rows,
|
||||
)
|
||||
adaptive_vs_dyn = _compare_dynamic_row_coverage(
|
||||
baseline_rows=adaptive_rows, dynamic_rows=dynamic_rows,
|
||||
)
|
||||
fixed_ok = fixed_vs_dyn != 'ambiguous'
|
||||
adaptive_ok = adaptive_vs_dyn != 'ambiguous'
|
||||
if fixed_ok and adaptive_ok:
|
||||
if fixed_vs_dyn == 'dynamic_preferred' or adaptive_vs_dyn == 'dynamic_preferred':
|
||||
return RuntimeParseStrategy(
|
||||
'selected', page_nos, 'dynamic_x_columns',
|
||||
('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',),
|
||||
)
|
||||
# 动态完整覆盖两侧且无额外行:冲突本身未消除,不能借动态消歧。
|
||||
return None
|
||||
if fixed_ok and not adaptive_ok:
|
||||
if fixed_vs_dyn == 'dynamic_preferred':
|
||||
return RuntimeParseStrategy(
|
||||
'selected', page_nos, 'dynamic_x_columns',
|
||||
('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',),
|
||||
)
|
||||
return RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ())
|
||||
if adaptive_ok and not fixed_ok:
|
||||
if adaptive_vs_dyn == 'dynamic_preferred':
|
||||
return RuntimeParseStrategy(
|
||||
'selected', page_nos, 'dynamic_x_columns',
|
||||
('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',),
|
||||
)
|
||||
return RuntimeParseStrategy(
|
||||
'selected', page_nos, 'adaptive_record_columns',
|
||||
('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',),
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def select_runtime_region_ids(*, table_regions: list[dict[str, Any]], page_no: int) -> tuple[str, ...]:
|
||||
"""为当前页选择候选表区,专属页优先,续页才回退到稳定基础表区。
|
||||
|
||||
@@ -210,29 +281,33 @@ def _compare_row_field_completeness(
|
||||
def _compare_dynamic_row_coverage(
|
||||
*, baseline_rows: list[dict[str, Any]], dynamic_rows: list[dict[str, Any]],
|
||||
) -> Literal['baseline_preferred', 'dynamic_preferred', 'ambiguous']:
|
||||
"""仅当动态结果无冲突地覆盖基线每条记录并额外恢复记录时才切换策略。"""
|
||||
"""仅当动态结果无冲突地覆盖基线,并额外恢复记录或严格加长字段值时才切换策略。"""
|
||||
if len(dynamic_rows) < len(baseline_rows):
|
||||
return 'baseline_preferred'
|
||||
remaining = [_row_fields(row) for row in dynamic_rows]
|
||||
extended = False
|
||||
for baseline in baseline_rows:
|
||||
baseline_fields = _row_fields(baseline)
|
||||
matches = []
|
||||
for index, dynamic_fields in enumerate(remaining):
|
||||
if not baseline_fields.keys() <= dynamic_fields.keys():
|
||||
continue
|
||||
if all(
|
||||
dynamic_fields[code] == value
|
||||
or (
|
||||
dynamic_fields[code].startswith(value)
|
||||
and len(dynamic_fields[code]) > len(value)
|
||||
)
|
||||
for code, value in baseline_fields.items()
|
||||
):
|
||||
compatible = True
|
||||
for code, value in baseline_fields.items():
|
||||
dyn_value = dynamic_fields[code]
|
||||
if dyn_value == value:
|
||||
continue
|
||||
if dyn_value.startswith(value) and len(dyn_value) > len(value):
|
||||
extended = True
|
||||
continue
|
||||
compatible = False
|
||||
break
|
||||
if compatible:
|
||||
matches.append(index)
|
||||
if len(matches) != 1:
|
||||
return 'ambiguous' if len(dynamic_rows) >= len(baseline_rows) else 'baseline_preferred'
|
||||
remaining.pop(matches[0])
|
||||
return 'dynamic_preferred' if remaining else 'baseline_preferred'
|
||||
return 'dynamic_preferred' if remaining or extended else 'baseline_preferred'
|
||||
|
||||
|
||||
def _row_fields(row: dict[str, Any]) -> dict[str, str]:
|
||||
|
||||
Reference in new issue
Block a user