feat(shipping-notice): 完善库存源聚合与订单模板匹配
- 优化订单模板匹配、重放及库存配置测试 - 新增库存 RPA 源合并设计与相关测试 - 更新库存管理页面及四语言文案 - 同步需求、技术文档与测试配置
This commit is contained in:
1 parent
2bb7822247
commit
6052c46d88
14 files changed
+1056
-86
No files matched your search
@@ -5,6 +5,9 @@ services/shipping_notice/document_layout/order_profile_matcher.py
|
||||
依赖:OrderCoordinateProfile、order_profile_signature.MATCHER_POLICY_ID、coordinate_region_text。
|
||||
逻辑:硬门禁(签名/必选锚点/排除锚点)→ 三态维度比对 → evidence_coverage 与相似度决胜;
|
||||
table_geometry 只比顶边/宽度(忽略 MinerU 脏 y1);critical 仅 header+column;
|
||||
主表优先按签名表头原子亲和度选择(避免 MinerU 抬头 KV 小表抢主表),并列再比表区重叠;
|
||||
无 hard_valid 时仅当全部候选均坐标结构不可用才抬升 evidence_insufficient;
|
||||
身份表头只读「签名 header_bbox 按主表顶边 deltaY 对齐」后的窗口,禁止表顶宽带兜底;
|
||||
主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表;
|
||||
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁;
|
||||
单逻辑表头将折行副标签按 x 并入所属列(保留文案),不拆成新身份列。
|
||||
@@ -46,6 +49,8 @@ from app.services.shipping_notice.document_layout.order_profile_signature import
|
||||
# 当前项目尚无历史运行数据;保持既有 v1 标识并在现版本一次性修正其事实投影语义,
|
||||
# 避免无意义的版本兼容分支。
|
||||
LAYOUT_MATCHING_FEATURES_VERSION = 'v1'
|
||||
# 多表时签名表头原子交集占比达到该阈值才优先于纯 bbox 重叠选主表。
|
||||
_PRIMARY_TABLE_HEADER_AFFINITY_MINIMUM = 0.5
|
||||
|
||||
|
||||
def _anchor_comparable_text(value: Any) -> str:
|
||||
@@ -286,7 +291,12 @@ 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):
|
||||
# [STEP] 仅当全部候选都缺关键坐标结构时才抬升 evidence_insufficient;
|
||||
# 禁止无关远亲候选的坐标码掩盖近亲模板的真实 header/topology 冲突。
|
||||
if rendered and all(
|
||||
'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,
|
||||
@@ -1006,6 +1016,7 @@ def _score_header_semantic_position(
|
||||
|
||||
_HEADER_ATOM_STOPWORDS = frozenset({'and', 'the', 'of', 'or', 'to', 'for', 'with', 'by'})
|
||||
_HEADER_ATOM_MIN_LEN = 3
|
||||
_HEADER_PAREN_GLOSS = re.compile(r'[\((][^\))]*[\))]')
|
||||
|
||||
|
||||
def _sanitize_signature_table_identity(
|
||||
@@ -1069,14 +1080,16 @@ def _header_token_atoms(tokens: list[str]) -> frozenset[str]:
|
||||
"""
|
||||
将表头 token 拆成稳定原子,供无锚点近亲模板互斥。
|
||||
|
||||
核心逻辑:去撇号后按非字母数字切分;过滤过短词与虚词,避免 Q'TY/No. 噪声。
|
||||
核心逻辑:先拼接 token 再去掉括号注记(通用印刷 gloss,跨 token 空格切开时
|
||||
仍可剥除),再去撇号并按非字母数字切分;过滤过短词与虚词。签名侧与运行时共用。
|
||||
"""
|
||||
joined = ' '.join(str(token) for token in tokens)
|
||||
normalized = _HEADER_PAREN_GLOSS.sub(' ', joined.casefold())
|
||||
normalized = re.sub(r"['’]", '', normalized)
|
||||
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)
|
||||
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)
|
||||
|
||||
|
||||
@@ -1321,10 +1334,11 @@ def _observe_layout_features(
|
||||
if width > 0 and height > 0:
|
||||
aspect_ratio = width / height
|
||||
|
||||
# [STEP 1] 与签名生成一致,按签名表区选择实际业务表;MinerU 的 tables[0]
|
||||
# 可能是抬头/元数据表,不能作为运行时默认主表。
|
||||
# [STEP 1] 与签名生成一致,按签名表头亲和度与表区选择实际业务表;MinerU 的
|
||||
# tables[0] 可能是抬头/元数据 KV 表,不能作为运行时默认主表。
|
||||
primary_bbox = _select_signature_primary_table_bbox(
|
||||
tables=tables, pages=pages, signature=signature,
|
||||
page_glyphs=page_glyphs, glyph_tables=glyph_tables,
|
||||
)
|
||||
# [STEP 1b] 业务行裁剪:仅按模板 termination/exclusion 截断粘连高度。
|
||||
primary_bbox = _clip_observed_primary_table_bbox(
|
||||
@@ -1470,9 +1484,21 @@ def _select_persisted_header_candidate(
|
||||
|
||||
|
||||
def _select_signature_primary_table_bbox(
|
||||
*, tables: list[dict[str, Any]], pages: dict[str, Any], signature: dict[str, Any] | None,
|
||||
*,
|
||||
tables: list[dict[str, Any]],
|
||||
pages: dict[str, Any],
|
||||
signature: dict[str, Any] | None,
|
||||
page_glyphs: dict[str, Any] | None = None,
|
||||
glyph_tables: dict[str, Any] | None = None,
|
||||
) -> list[float] | None:
|
||||
"""按签名表区选取重叠最大的实际表;无可用签名时才保持首表兼容行为。"""
|
||||
"""
|
||||
选取运行时主表框:签名表头亲和度优先,其次表区重叠;无签名时首表兼容。
|
||||
|
||||
核心逻辑:MinerU 常把右上角 ORDER DATE/NO 等 KV 块拆成独立表且排在 tables[0];
|
||||
仅靠 bbox 重叠在全页 glyphs 场景下仍可能读错表头。对每个候选表顶部观测 header
|
||||
atoms,与签名 identity header 算交集占比;占比 ≥ 阈值时优先该表,并列再比
|
||||
table_patterns.bbox.median 重叠。
|
||||
"""
|
||||
normalized_tables: list[list[float]] = []
|
||||
for table in tables:
|
||||
page = pages.get(str(table.get('page_no') or 1)) or pages.get(table.get('page_no') or 1)
|
||||
@@ -1498,22 +1524,99 @@ def _select_signature_primary_table_bbox(
|
||||
and isinstance(item['bbox'].get('median'), list)
|
||||
and len(item['bbox']['median']) == 4
|
||||
]
|
||||
if not patterns:
|
||||
return normalized_tables[0]
|
||||
best_bbox = normalized_tables[0]
|
||||
best_overlap = -1.0
|
||||
for candidate in normalized_tables:
|
||||
expected_atoms = _header_token_atoms(_signature_identity_header_tokens(signature))
|
||||
glyph_pages = page_glyphs if isinstance(page_glyphs, dict) else {}
|
||||
table_glyph_map = glyph_tables if isinstance(glyph_tables, dict) else {}
|
||||
|
||||
def _best_pattern_overlap(candidate: list[float]) -> float:
|
||||
best = -1.0
|
||||
for pattern in patterns:
|
||||
try:
|
||||
expected = [float(value) for value in pattern['bbox']['median']]
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
overlap = _bbox_overlap(expected, candidate)
|
||||
if overlap > best_overlap:
|
||||
best_overlap, best_bbox = overlap, candidate
|
||||
best = max(best, _bbox_overlap(expected, candidate))
|
||||
return best
|
||||
|
||||
if expected_atoms and (glyph_pages or table_glyph_map):
|
||||
affinity_scored: list[tuple[float, float, list[float]]] = []
|
||||
for candidate in normalized_tables:
|
||||
tokens = _header_tokens_for_table_bbox(
|
||||
bbox=candidate,
|
||||
tables=tables,
|
||||
pages=pages,
|
||||
page_glyphs=glyph_pages,
|
||||
glyph_tables=table_glyph_map,
|
||||
)
|
||||
observed_atoms = _header_token_atoms(tokens)
|
||||
affinity = (
|
||||
len(observed_atoms & expected_atoms) / len(expected_atoms)
|
||||
if expected_atoms else 0.0
|
||||
)
|
||||
affinity_scored.append((affinity, _best_pattern_overlap(candidate), candidate))
|
||||
affinity_scored.sort(key=lambda item: (item[0], item[1]))
|
||||
best_affinity, best_overlap, best_bbox = affinity_scored[-1]
|
||||
if best_affinity >= _PRIMARY_TABLE_HEADER_AFFINITY_MINIMUM:
|
||||
return best_bbox
|
||||
if not patterns:
|
||||
return best_bbox if best_affinity > 0 else normalized_tables[0]
|
||||
|
||||
if not patterns:
|
||||
return normalized_tables[0]
|
||||
best_bbox = normalized_tables[0]
|
||||
best_overlap = -1.0
|
||||
for candidate in normalized_tables:
|
||||
overlap = _best_pattern_overlap(candidate)
|
||||
if overlap > best_overlap:
|
||||
best_overlap, best_bbox = overlap, candidate
|
||||
return best_bbox
|
||||
|
||||
|
||||
def _header_tokens_for_table_bbox(
|
||||
*,
|
||||
bbox: list[float],
|
||||
tables: list[dict[str, Any]],
|
||||
pages: dict[str, Any],
|
||||
page_glyphs: dict[str, Any],
|
||||
glyph_tables: dict[str, Any],
|
||||
) -> list[str]:
|
||||
"""
|
||||
在候选表顶部条带观测表头 token,供主表亲和度打分。
|
||||
|
||||
核心逻辑:取相对坐标表框顶边向下 max(6%, 18% 表高) 的条带,用页级 glyphs
|
||||
(不足时回退 table glyphs)拼 token;不做折行合并,仅服务选表。
|
||||
"""
|
||||
if not isinstance(bbox, list) or len(bbox) != 4:
|
||||
return []
|
||||
page_no, page = _page_for_primary_table_bbox(bbox, tables=tables, pages=pages)
|
||||
if not isinstance(page, dict):
|
||||
return []
|
||||
glyphs = None
|
||||
if page_no is not None:
|
||||
glyphs = page_glyphs.get(str(page_no)) or page_glyphs.get(page_no)
|
||||
if not isinstance(glyphs, list) or not glyphs:
|
||||
glyphs = page_glyphs.get('1') or page_glyphs.get(1) or []
|
||||
if not isinstance(glyphs, list) or not glyphs:
|
||||
glyphs = []
|
||||
for table_glyphs in glyph_tables.values():
|
||||
if isinstance(table_glyphs, list):
|
||||
glyphs.extend(table_glyphs)
|
||||
if not glyphs:
|
||||
return []
|
||||
region = {
|
||||
'x0': float(bbox[0]),
|
||||
'y0': float(bbox[1]),
|
||||
'x1': float(bbox[2]),
|
||||
'y1': float(bbox[1]) + max(0.06, (float(bbox[3]) - float(bbox[1])) * 0.18),
|
||||
}
|
||||
header_glyphs = _glyphs_in_relative_region(glyphs, page=page, region=region)
|
||||
spans = [
|
||||
item for item in positioned_token_spans(header_glyphs, respect_explicit_spaces=False)
|
||||
if _usable_observed_header_token(str(item.get('text') or ''))
|
||||
][:32]
|
||||
return [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
|
||||
|
||||
|
||||
def _clip_observed_primary_table_bbox(
|
||||
primary_bbox: list[float] | None,
|
||||
*,
|
||||
@@ -1616,21 +1719,62 @@ def _bbox_overlap(left: list[float], right: list[float]) -> float:
|
||||
_HEADER_TOKEN_SPLIT = re.compile(r'[\s|/]+')
|
||||
|
||||
|
||||
def _band_headers_match_signature(
|
||||
*, band_tokens: list[str], signature: dict[str, Any] | None,
|
||||
) -> bool:
|
||||
"""判断冻结表头带读到的 token 是否足以代表签名表头。
|
||||
def _signature_table_bbox_median(signature: dict[str, Any] | None) -> list[float] | None:
|
||||
"""读取签名首个可用 table_patterns.bbox.median(归一化四点)。"""
|
||||
for pattern in (signature or {}).get('table_patterns') or []:
|
||||
if not isinstance(pattern, dict):
|
||||
continue
|
||||
bbox = pattern.get('bbox') if isinstance(pattern.get('bbox'), dict) else None
|
||||
if not isinstance(bbox, dict):
|
||||
continue
|
||||
median = bbox.get('median')
|
||||
if isinstance(median, list) and len(median) == 4:
|
||||
try:
|
||||
return [float(item) for item in median]
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
return None
|
||||
|
||||
只有当固定带读到的表头 token 与签名 header_tokens 覆盖达到阈值时才视为“带仍有效”,
|
||||
直接沿用;否则(表体因上方内容折行/加行而上移或下移,固定带读空或读到错误行)
|
||||
需要回退到表体顶部的结构搜索。期望侧先截断折行副标签污染。
|
||||
|
||||
def _align_signature_header_bbox_to_primary(
|
||||
*,
|
||||
signature: dict[str, Any] | None,
|
||||
primary_bbox: list[float],
|
||||
) -> list[float] | None:
|
||||
"""
|
||||
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]
|
||||
matched = sum(1 for token in expected if token in observed)
|
||||
return matched / len(expected) >= 0.5
|
||||
将签名冻结的表头框按当前主表顶边做整体 deltaY 对齐。
|
||||
|
||||
核心逻辑:x/高度保持签名 header_bbox;只用 primary_bbox.y0 - signature_table.y0
|
||||
平移;再把 y 夹在主表竖向范围内,避免落到明细数据行。无 header_bbox 时返回 None。
|
||||
"""
|
||||
if not isinstance(primary_bbox, list) or len(primary_bbox) != 4:
|
||||
return None
|
||||
header_bbox = _signature_header_bbox(signature)
|
||||
if header_bbox is None:
|
||||
return None
|
||||
table_median = _signature_table_bbox_median(signature)
|
||||
try:
|
||||
hx0, hy0, hx1, hy1 = (float(header_bbox[i]) for i in range(4))
|
||||
py0, py1 = float(primary_bbox[1]), float(primary_bbox[3])
|
||||
except (TypeError, ValueError, IndexError):
|
||||
return None
|
||||
if hy1 <= hy0 or py1 <= py0:
|
||||
return None
|
||||
delta_y = 0.0
|
||||
if table_median is not None:
|
||||
try:
|
||||
delta_y = py0 - float(table_median[1])
|
||||
except (TypeError, ValueError, IndexError):
|
||||
delta_y = 0.0
|
||||
aligned_y0 = hy0 + delta_y
|
||||
aligned_y1 = hy1 + delta_y
|
||||
# [STEP] 夹在主表内;保持最小可读高度。
|
||||
height = max(0.02, aligned_y1 - aligned_y0)
|
||||
clipped_y0 = min(max(aligned_y0, py0), max(py0, py1 - height))
|
||||
clipped_y1 = min(clipped_y0 + height, py1)
|
||||
if clipped_y1 <= clipped_y0:
|
||||
return None
|
||||
return [hx0, clipped_y0, hx1, clipped_y1]
|
||||
|
||||
|
||||
def _observe_primary_table_header(
|
||||
@@ -1641,10 +1785,12 @@ def _observe_primary_table_header(
|
||||
primary_bbox: list[float] | None,
|
||||
signature: dict[str, Any] | None,
|
||||
) -> tuple[list[str], list[float], list[float]]:
|
||||
"""从实际主表顶部观测表头,与签名生成保持同一证据口径。
|
||||
"""
|
||||
从对齐身份窗口观测表头,与签名生成保持同一证据口径。
|
||||
|
||||
先读模板冻结的表头带;若该带仍能读出与签名一致的表头 token,则直接沿用。
|
||||
若固定带失准,则基于表体顶部做表头行搜索。单逻辑表头时把折行副标签按 x 并入所属列。
|
||||
核心逻辑:有签名 header_bbox 时按主表顶边 deltaY 对齐后只读该窗口;无签名表头框
|
||||
时才用主表顶 18% 保守带(与签名生成兜底一致)。禁止固定带失准后改走表顶多行
|
||||
宽带搜索,避免印刷括号注记污染身份原子。
|
||||
"""
|
||||
if not primary_bbox or len(primary_bbox) != 4:
|
||||
return [], [], []
|
||||
@@ -1657,14 +1803,23 @@ def _observe_primary_table_header(
|
||||
page = pages.get('1') or pages.get(1)
|
||||
if not isinstance(glyphs, list) or not glyphs or not isinstance(page, dict):
|
||||
return [], [], []
|
||||
header_bbox = _signature_header_bbox(signature)
|
||||
region = (
|
||||
{'x0': header_bbox[0], 'y0': header_bbox[1], 'x1': header_bbox[2], 'y1': header_bbox[3]}
|
||||
if header_bbox is not None else {
|
||||
'x0': primary_bbox[0], 'y0': primary_bbox[1], 'x1': primary_bbox[2],
|
||||
'y1': primary_bbox[1] + max(0.06, (primary_bbox[3] - primary_bbox[1]) * 0.18),
|
||||
}
|
||||
aligned = _align_signature_header_bbox_to_primary(
|
||||
signature=signature, primary_bbox=primary_bbox,
|
||||
)
|
||||
if aligned is not None:
|
||||
region = {
|
||||
'x0': float(aligned[0]), 'y0': float(aligned[1]),
|
||||
'x1': float(aligned[2]), 'y1': float(aligned[3]),
|
||||
}
|
||||
else:
|
||||
region = {
|
||||
'x0': float(primary_bbox[0]),
|
||||
'y0': float(primary_bbox[1]),
|
||||
'x1': float(primary_bbox[2]),
|
||||
'y1': float(primary_bbox[1]) + max(
|
||||
0.06, (float(primary_bbox[3]) - float(primary_bbox[1])) * 0.18,
|
||||
),
|
||||
}
|
||||
width = float(page.get('width') or 0)
|
||||
if width <= 0:
|
||||
return [], [], []
|
||||
@@ -1675,38 +1830,19 @@ def _observe_primary_table_header(
|
||||
][:32]
|
||||
band_tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
|
||||
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:
|
||||
table_span = max(float(primary_bbox[2]) - float(primary_bbox[0]), 0.0001)
|
||||
band_widths = [
|
||||
round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans
|
||||
]
|
||||
if _signature_single_logical_header(signature):
|
||||
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
|
||||
# 固定带失准 → 表体顶部候选行;单逻辑表头时把下一视觉行折行副标签并入。
|
||||
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
|
||||
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 (
|
||||
[str(item).casefold() for item in merged_tokens],
|
||||
list(merged_centers or []),
|
||||
list(merged_widths or []),
|
||||
)
|
||||
return band_tokens, band_centers, band_widths
|
||||
|
||||
|
||||
|
||||
@@ -356,8 +356,20 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
run.status = 'failed'; run.stage = 'failed'; run.error_message = str(payload.get('error_message') or '测试导出失败')[:500]; run.completed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return _payload(run)
|
||||
path = Path(str(payload.get('file_path') or ''))
|
||||
if not path.is_file():
|
||||
# Windows Worker 回传 C:\HxopsRpa...\inventory_drop\file.xlsx;Linux 后端必须映射到
|
||||
# SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR 下同名文件,否则 Path(windows).is_file() 恒假。
|
||||
raw_file_path = str(payload.get('file_path') or '').strip()
|
||||
path: Path | None = None
|
||||
from app.services.shipping_notice.rpa import inventory_drop_dir
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import _resolve_shared_inventory_drop_file
|
||||
drop_root = inventory_drop_dir()
|
||||
if drop_root is not None:
|
||||
path = _resolve_shared_inventory_drop_file(raw_file_path, allowed_root=drop_root)
|
||||
if path is None:
|
||||
candidate = Path(raw_file_path)
|
||||
if candidate.is_file():
|
||||
path = candidate
|
||||
if path is None or not path.is_file():
|
||||
run.status = 'failed'; run.stage = 'failed'; run.error_message = '测试导出文件不存在'; run.completed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return _payload(run)
|
||||
|
||||
Reference in new issue
Block a user