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
@@ -1,10 +1,11 @@
|
||||
"""
|
||||
backend/app/services/schedule/shipping_inventory_rpa_archive.py
|
||||
|
||||
用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)。
|
||||
用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
|
||||
依赖:ScheduleRun、ShippingInventoryFile、shipping_inventory_rpa_finalize.is_shipping_inventory_rpa_task。
|
||||
逻辑:finalize 调用 persist_inventory_rpa_raw_zip_archive 写入磁盘与 summary;
|
||||
query_service 只读 summary;api/schedule/runs 按 raw_inventory_zip_path send_file。
|
||||
企微/下载展示名用「库存RPA-日期-时刻-结果|库存」;包内条目仅「序号_仓码」;
|
||||
完整 source_code / inventory_file_no 只写在 manifest.json;磁盘归档键仍为 {run_no}.zip。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,6 +13,7 @@ from __future__ import annotations
|
||||
import json
|
||||
import re
|
||||
import zipfile
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -48,9 +50,51 @@ def get_inventory_archive_dir() -> str:
|
||||
return str(archive_dir)
|
||||
|
||||
|
||||
def inventory_raw_zip_download_name(run_no: str) -> str:
|
||||
"""浏览器下载时使用的 ZIP 文件名。"""
|
||||
return f"inventory-rpa-raw-{run_no}.zip"
|
||||
def _attachment_when_from_run(run: ScheduleRun) -> datetime:
|
||||
"""
|
||||
推导企微/下载展示名中的时刻。
|
||||
|
||||
核心逻辑:优先 started_at → created_at → finished_at;再尝试解析 RUN{yyyyMMddHHmmss}*;
|
||||
最后回退 utcnow。完整 run_no 仍留在卡片与磁盘归档键,不塞进展示名。
|
||||
"""
|
||||
for value in (run.started_at, run.created_at, run.finished_at):
|
||||
if isinstance(value, datetime):
|
||||
return value
|
||||
match = re.match(r"^RUN(\d{14})", str(run.run_no or "").strip())
|
||||
if match:
|
||||
try:
|
||||
return datetime.strptime(match.group(1), "%Y%m%d%H%M%S")
|
||||
except ValueError:
|
||||
pass
|
||||
return datetime.utcnow()
|
||||
|
||||
|
||||
def inventory_rpa_attachment_stem(run: ScheduleRun) -> str:
|
||||
"""
|
||||
库存 RPA 企微附件共用前缀:库存RPA-{yyyyMMdd}-{HHmm}。
|
||||
|
||||
Args:
|
||||
run: 排程执行记录。
|
||||
|
||||
Returns:
|
||||
不含角色后缀与扩展名的展示名前缀。
|
||||
"""
|
||||
when = _attachment_when_from_run(run)
|
||||
return f"库存RPA-{when.strftime('%Y%m%d')}-{when.strftime('%H%M')}"
|
||||
|
||||
|
||||
def inventory_rpa_result_excel_name(run: ScheduleRun) -> str:
|
||||
"""库存 RPA 结果 Excel 的企微/下载展示名。"""
|
||||
return f"{inventory_rpa_attachment_stem(run)}-结果.xlsx"
|
||||
|
||||
|
||||
def inventory_raw_zip_download_name(run: ScheduleRun) -> str:
|
||||
"""
|
||||
库存 ZIP 的企微/浏览器下载展示名。
|
||||
|
||||
核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。
|
||||
"""
|
||||
return f"{inventory_rpa_attachment_stem(run)}-库存.zip"
|
||||
|
||||
|
||||
def _inventory_raw_zip_archive_path(run_no: str) -> Path:
|
||||
@@ -157,7 +201,6 @@ def persist_inventory_rpa_raw_zip_archive(
|
||||
index=zip_index,
|
||||
source_code=source_code,
|
||||
warehouse_id=warehouse_id,
|
||||
inventory_file_no=inventory_file_no,
|
||||
original_suffix=storage_path.suffix or ".xlsx",
|
||||
)
|
||||
archive.write(storage_path, arcname=entry_name)
|
||||
@@ -236,7 +279,7 @@ def resolve_inventory_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
|
||||
if not _is_allowed_inventory_archive_path(zip_path):
|
||||
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
|
||||
|
||||
return zip_path.resolve(), inventory_raw_zip_download_name(run.run_no)
|
||||
return zip_path.resolve(), inventory_raw_zip_download_name(run)
|
||||
|
||||
|
||||
def _sanitize_zip_segment(value: str) -> str:
|
||||
@@ -245,25 +288,33 @@ def _sanitize_zip_segment(value: str) -> str:
|
||||
return cleaned or "unknown"
|
||||
|
||||
|
||||
def _zip_entry_label(*, source_code: str, warehouse_id: str) -> str:
|
||||
"""
|
||||
包内短标签:优先 source_code(库存站点业务键,Crane 等无固定仓码也能辨认)。
|
||||
|
||||
warehouse_id / inventory_file_no 已写入 manifest.json;条目名不必再叠仓码。
|
||||
"""
|
||||
source = str(source_code or "").strip()
|
||||
if source:
|
||||
return source
|
||||
warehouse = str(warehouse_id or "").strip()
|
||||
if warehouse and warehouse.lower() != "unknown":
|
||||
return warehouse
|
||||
return "inventory"
|
||||
|
||||
|
||||
def _build_zip_entry_name(
|
||||
*,
|
||||
index: int,
|
||||
source_code: str,
|
||||
warehouse_id: str,
|
||||
inventory_file_no: str,
|
||||
original_suffix: str,
|
||||
) -> str:
|
||||
"""生成 ZIP 内单文件条目名(不含目录)。"""
|
||||
base = "_".join(
|
||||
filter(
|
||||
None,
|
||||
[
|
||||
f"{index:03d}",
|
||||
_sanitize_zip_segment(source_code),
|
||||
_sanitize_zip_segment(warehouse_id),
|
||||
_sanitize_zip_segment(inventory_file_no),
|
||||
],
|
||||
)
|
||||
)
|
||||
"""
|
||||
生成 ZIP 内单文件条目名(不含目录)。
|
||||
|
||||
核心逻辑:`{序号}_{source_code}.{ext}`;序号保证极端撞名时仍唯一。
|
||||
"""
|
||||
label = _sanitize_zip_segment(_zip_entry_label(source_code=source_code, warehouse_id=warehouse_id))
|
||||
suffix = original_suffix if original_suffix.startswith(".") else f".{original_suffix}"
|
||||
return f"{base}{suffix}"
|
||||
return f"{index:03d}_{label}{suffix}"
|
||||
@@ -493,6 +493,11 @@ def _finalize_shipping_inventory_schedule_run_impl(
|
||||
errors.append(f"Excel导出失败: {excel_exc}")
|
||||
if status == "success":
|
||||
status = "partial_failed"
|
||||
else:
|
||||
# 企微/下载展示名:库存RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import inventory_rpa_result_excel_name
|
||||
|
||||
file_name = inventory_rpa_result_excel_name(run)
|
||||
|
||||
step_logs = list(run.step_logs or [])
|
||||
step_logs.append({
|
||||
|
||||
@@ -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]:
|
||||
|
||||
@@ -6,6 +6,7 @@ services/shipping_notice/document_profile_quality_service.py
|
||||
逻辑:管理员先固化一份独立样本的期望行,服务按冻结 Profile 执行比对;
|
||||
共同坐标回放完成视觉证据,末端值源 adapter 再补充正式字段和结构校验;
|
||||
策略需复核时仍展示最佳努力明细供人工核对,正式自动建单仍要求策略 selected;
|
||||
盲测主明细仅 business_lines,随后按 LN 合并 line_field_supplement 料号;
|
||||
盲测执行附加 visual/split/evidence 指标,XFA 任一指标 < 1.0 即失败;样本通过并批准后才放行自动建单。
|
||||
"""
|
||||
|
||||
@@ -399,6 +400,9 @@ def _candidate_for_sample(
|
||||
# layout. They are valid template regions, but cannot reconstruct rows.
|
||||
if not region.line_layouts:
|
||||
continue
|
||||
# COO 等补充表不进入盲测主明细行;稍后按 LN 合并料号。
|
||||
if str(getattr(region, 'region_role', None) or 'business_lines') == 'line_field_supplement':
|
||||
continue
|
||||
# ``page_scope`` 是历史人工策略。验证必须与正式解析一致:检查当前样本中
|
||||
# 每个有页级坐标事实的页面,由实际行结果决定是否属于续页。
|
||||
eligible_pages = [
|
||||
@@ -463,6 +467,30 @@ def _candidate_for_sample(
|
||||
)
|
||||
# selected 与 needs_review 的 fallback 明细都要展示;后者仅供盲测人工复核。
|
||||
rows.extend(item.fields for item in chosen_rows if not item.issues)
|
||||
# 与正式解析共用:按 LN 合并 line_field_supplement(如 COO)料号。
|
||||
from app.services.shipping_notice.order_extraction_workflow import (
|
||||
_reconstruct_line_field_supplement_rows,
|
||||
)
|
||||
from app.services.shipping_notice.line_field_supplement_merge import (
|
||||
merge_line_field_supplement,
|
||||
)
|
||||
supplement_rows, line_start = _reconstruct_line_field_supplement_rows(
|
||||
raw_profile={
|
||||
'definition': profile.definition_json if isinstance(profile.definition_json, dict) else {},
|
||||
'profile_code': profile.profile_code,
|
||||
'version': profile.version,
|
||||
'checksum': profile.checksum,
|
||||
},
|
||||
layout=layout,
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
supplement_reasons: list[str] = []
|
||||
if supplement_rows:
|
||||
rows, supplement_reasons = merge_line_field_supplement(
|
||||
rows,
|
||||
supplement_rows,
|
||||
line_start_field_code=line_start or 'customer_po_line_no',
|
||||
)
|
||||
order_fields = [
|
||||
{
|
||||
'field_code': item.field_code, 'value': _json_value(item.value), 'status': item.status,
|
||||
@@ -521,8 +549,13 @@ def _candidate_for_sample(
|
||||
'document_id': document.id, 'table_id': str(table_id), 'rows': rows,
|
||||
'order_fields': order_fields, 'reservation_region_status': 'needs_review',
|
||||
'reservation_region_review_reasons': list(dict.fromkeys(review_reasons)),
|
||||
'line_field_supplement_reasons': list(supplement_reasons),
|
||||
}
|
||||
return {'document_id': document.id, 'table_id': str(table_id), 'rows': rows, 'order_fields': order_fields}
|
||||
return {
|
||||
'document_id': document.id, 'table_id': str(table_id), 'rows': rows,
|
||||
'order_fields': order_fields,
|
||||
'line_field_supplement_reasons': list(supplement_reasons),
|
||||
}
|
||||
raise ValidationError('Profile samples are unsupported', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
"""
|
||||
services/shipping_notice/line_field_supplement_merge.py
|
||||
|
||||
用途:将同文档「明细字段补充表」(如 Hyve COO)按 LN 保守合并进主表明细。
|
||||
依赖:无外部 IO;仅字符串规范化与行字典读写。
|
||||
逻辑:由正式解析 / 盲测 / 验证在主表重建后调用;只补 customer_part_number、part_number;
|
||||
空值直补、主表为补充值前缀则补全、冲突不覆盖并写稳定 reason。不改数量/单价/金额。
|
||||
``REASON_APPLIED`` 仅写入表级 reasons 审计,不进入行 ``issues``(成功补齐不得触发 row_needs_review)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
LINE_FIELD_SUPPLEMENT_CODES = frozenset({'customer_part_number', 'part_number'})
|
||||
DEFAULT_LINE_START_FIELD_CODE = 'customer_po_line_no'
|
||||
|
||||
REASON_APPLIED = 'line_field_supplement_applied'
|
||||
REASON_CONFLICT = 'line_field_supplement_conflict'
|
||||
REASON_LN_AMBIGUOUS = 'line_field_supplement_ln_ambiguous'
|
||||
REASON_LN_MISSING = 'line_field_supplement_ln_missing'
|
||||
|
||||
# 表级审计码:不得当作行级缺陷拦截确定性建单。
|
||||
NON_BLOCKING_ROW_ISSUE_CODES = frozenset({REASON_APPLIED})
|
||||
|
||||
|
||||
def normalize_line_start_key(raw: Any) -> str:
|
||||
"""
|
||||
将行号规范为对齐键:去空白;纯数字去掉无意义前导零(保留至少一位)。
|
||||
|
||||
Args:
|
||||
raw: 主表或补充表上的起行字段值。
|
||||
|
||||
Returns:
|
||||
非空对齐键;无法规范化时返回空串。
|
||||
"""
|
||||
text = re.sub(r'\s+', '', str(raw or '')).strip()
|
||||
if not text:
|
||||
return ''
|
||||
if text.isdigit():
|
||||
return str(int(text))
|
||||
return text
|
||||
|
||||
|
||||
def normalize_part_value(raw: Any) -> str:
|
||||
"""料号比较用:去掉空白,保留连字符等符号。"""
|
||||
return re.sub(r'\s+', '', str(raw or '')).strip()
|
||||
|
||||
|
||||
def _row_field_map(row: dict[str, Any]) -> dict[str, str]:
|
||||
"""将扁平行或 workflow ``fields`` 列表统一为 field_code -> 文本值。"""
|
||||
if not isinstance(row, dict):
|
||||
return {}
|
||||
fields = row.get('fields')
|
||||
if isinstance(fields, list):
|
||||
result: dict[str, str] = {}
|
||||
for item in fields:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
code = str(item.get('field_code') or '').strip()
|
||||
if not code:
|
||||
continue
|
||||
result[code] = str(item.get('value') or '').strip()
|
||||
return result
|
||||
return {
|
||||
str(key): str(value or '').strip()
|
||||
for key, value in row.items()
|
||||
if key not in {'fields', 'issues', 'status', 'row_index', 'role', 'source_row_indices'}
|
||||
and not str(key).startswith('_')
|
||||
}
|
||||
|
||||
|
||||
def _set_row_field(row: dict[str, Any], field_code: str, value: str) -> None:
|
||||
"""按行形态写回字段值;workflow 行写入 ``fields`` 列表。"""
|
||||
fields = row.get('fields')
|
||||
if isinstance(fields, list):
|
||||
target = next(
|
||||
(
|
||||
item for item in fields
|
||||
if isinstance(item, dict) and str(item.get('field_code') or '') == field_code
|
||||
),
|
||||
None,
|
||||
)
|
||||
if target is None:
|
||||
fields.append({'field_code': field_code, 'value': value})
|
||||
else:
|
||||
target['value'] = value
|
||||
return
|
||||
row[field_code] = value
|
||||
|
||||
|
||||
def _append_row_issue(row: dict[str, Any], code: str) -> None:
|
||||
"""为 workflow 行追加 issue;扁平行写入 ``issues`` 列表供调用方读取。"""
|
||||
issues = row.get('issues')
|
||||
if not isinstance(issues, list):
|
||||
row['issues'] = [code]
|
||||
return
|
||||
if code not in issues:
|
||||
issues.append(code)
|
||||
|
||||
|
||||
def _index_rows_by_line(
|
||||
rows: list[dict[str, Any]],
|
||||
*,
|
||||
line_start_field_code: str,
|
||||
) -> tuple[dict[str, dict[str, Any]], set[str], list[str]]:
|
||||
"""
|
||||
按规范化 LN 建唯一索引。
|
||||
|
||||
Returns:
|
||||
(唯一行映射, 重复 LN 集合, 缺 LN 的全局 reasons)
|
||||
"""
|
||||
buckets: dict[str, list[dict[str, Any]]] = {}
|
||||
missing_reasons: list[str] = []
|
||||
for row in rows:
|
||||
key = normalize_line_start_key(_row_field_map(row).get(line_start_field_code))
|
||||
if not key:
|
||||
missing_reasons.append(REASON_LN_MISSING)
|
||||
continue
|
||||
buckets.setdefault(key, []).append(row)
|
||||
unique: dict[str, dict[str, Any]] = {}
|
||||
ambiguous: set[str] = set()
|
||||
for key, items in buckets.items():
|
||||
if len(items) != 1:
|
||||
ambiguous.add(key)
|
||||
continue
|
||||
unique[key] = items[0]
|
||||
return unique, ambiguous, missing_reasons
|
||||
|
||||
|
||||
def merge_line_field_supplement(
|
||||
main_rows: list[dict[str, Any]],
|
||||
supplement_rows: list[dict[str, Any]],
|
||||
*,
|
||||
line_start_field_code: str = DEFAULT_LINE_START_FIELD_CODE,
|
||||
field_codes: frozenset[str] = LINE_FIELD_SUPPLEMENT_CODES,
|
||||
) -> tuple[list[dict[str, Any]], list[str]]:
|
||||
"""
|
||||
按 LN 将补充表料号合并进主表明细。
|
||||
|
||||
核心逻辑:只处理 ``field_codes``;空值直补;主表规范化值是补充值前缀则补全;
|
||||
两边完整且不同则写冲突 reason 且不覆盖;补充侧或主侧 LN 重复/缺失则跳过该键。
|
||||
成功补齐仅写入返回的 reasons(``REASON_APPLIED``),不写入行 ``issues``。
|
||||
|
||||
Args:
|
||||
main_rows: 主表明细(扁平 dict 或含 ``fields`` 的 workflow 行)。
|
||||
supplement_rows: 补充表重建行,形态同主表。
|
||||
line_start_field_code: 对齐用起行字段,默认 customer_po_line_no。
|
||||
field_codes: 允许补齐的字段集合。
|
||||
|
||||
Returns:
|
||||
(合并后的主表行深拷贝, 稳定 reason 列表;可含表级审计码与行级冲突码)
|
||||
"""
|
||||
if not main_rows or not supplement_rows:
|
||||
return [copy.deepcopy(row) for row in main_rows], []
|
||||
|
||||
merged = [copy.deepcopy(row) for row in main_rows]
|
||||
main_index, main_ambiguous, main_missing = _index_rows_by_line(
|
||||
merged, line_start_field_code=line_start_field_code,
|
||||
)
|
||||
supplement_index, supplement_ambiguous, supplement_missing = _index_rows_by_line(
|
||||
supplement_rows, line_start_field_code=line_start_field_code,
|
||||
)
|
||||
|
||||
reasons: list[str] = []
|
||||
reasons.extend(main_missing)
|
||||
reasons.extend(supplement_missing)
|
||||
for key in sorted(main_ambiguous | supplement_ambiguous):
|
||||
reasons.append(REASON_LN_AMBIGUOUS)
|
||||
if key in main_index:
|
||||
_append_row_issue(main_index[key], REASON_LN_AMBIGUOUS)
|
||||
for row in merged:
|
||||
if normalize_line_start_key(_row_field_map(row).get(line_start_field_code)) == key:
|
||||
_append_row_issue(row, REASON_LN_AMBIGUOUS)
|
||||
|
||||
for line_key, main_row in main_index.items():
|
||||
if line_key in main_ambiguous or line_key in supplement_ambiguous:
|
||||
continue
|
||||
supplement_row = supplement_index.get(line_key)
|
||||
if supplement_row is None:
|
||||
continue
|
||||
main_fields = _row_field_map(main_row)
|
||||
supplement_fields = _row_field_map(supplement_row)
|
||||
for code in sorted(field_codes):
|
||||
supplement_raw = supplement_fields.get(code) or ''
|
||||
if not supplement_raw:
|
||||
continue
|
||||
main_raw = main_fields.get(code) or ''
|
||||
main_norm = normalize_part_value(main_raw)
|
||||
supplement_norm = normalize_part_value(supplement_raw)
|
||||
if not supplement_norm:
|
||||
continue
|
||||
if not main_norm:
|
||||
# [STEP] 成功直补:只记表级审计,不写行 issues(避免误判 row_needs_review)。
|
||||
_set_row_field(main_row, code, supplement_raw)
|
||||
reasons.append(REASON_APPLIED)
|
||||
continue
|
||||
if main_norm == supplement_norm:
|
||||
continue
|
||||
if supplement_norm.startswith(main_norm) and len(supplement_norm) > len(main_norm):
|
||||
# [STEP] 前缀补全成功:同上,审计进 reasons,不写入 issues。
|
||||
_set_row_field(main_row, code, supplement_raw)
|
||||
reasons.append(REASON_APPLIED)
|
||||
continue
|
||||
_append_row_issue(main_row, REASON_CONFLICT)
|
||||
reasons.append(REASON_CONFLICT)
|
||||
|
||||
# 保持 reason 顺序稳定且去重保留首次出现,便于审计对照。
|
||||
deduped: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for code in reasons:
|
||||
if code in seen:
|
||||
continue
|
||||
seen.add(code)
|
||||
deduped.append(code)
|
||||
return merged, deduped
|
||||
|
||||
|
||||
def project_line_field_supplement_onto_validation_evidence(
|
||||
evidence: dict[str, Any],
|
||||
*,
|
||||
supplement_rows: list[dict[str, Any]],
|
||||
line_start_field_code: str = DEFAULT_LINE_START_FIELD_CODE,
|
||||
) -> tuple[dict[str, Any], list[str]]:
|
||||
"""
|
||||
将补充表合并结果写回验证证据的 lines 字段。
|
||||
|
||||
Args:
|
||||
evidence: 含 header_fields / lines 的验证 DTO。
|
||||
supplement_rows: workflow 或扁平行。
|
||||
line_start_field_code: LN 对齐字段。
|
||||
|
||||
Returns:
|
||||
(更新后的 evidence 深拷贝, reason 列表)
|
||||
"""
|
||||
if not isinstance(evidence, dict) or not supplement_rows:
|
||||
return copy.deepcopy(evidence) if isinstance(evidence, dict) else {}, []
|
||||
result = copy.deepcopy(evidence)
|
||||
lines = result.get('lines') if isinstance(result.get('lines'), list) else []
|
||||
main_rows: list[dict[str, Any]] = []
|
||||
for line in lines:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
fields = []
|
||||
for item in line.get('fields') or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
fields.append({
|
||||
'field_code': str(item.get('field_code') or ''),
|
||||
'value': str(item.get('raw_value') or item.get('normalized_value') or ''),
|
||||
})
|
||||
main_rows.append({'fields': fields, 'issues': []})
|
||||
if not main_rows:
|
||||
return result, []
|
||||
merged, reasons = merge_line_field_supplement(
|
||||
main_rows, supplement_rows, line_start_field_code=line_start_field_code,
|
||||
)
|
||||
for index, row in enumerate(merged):
|
||||
if index >= len(lines) or not isinstance(lines[index], dict):
|
||||
continue
|
||||
values = _row_field_map(row)
|
||||
issues = list(row.get('issues') or [])
|
||||
for field in lines[index].get('fields') or []:
|
||||
if not isinstance(field, dict):
|
||||
continue
|
||||
code = str(field.get('field_code') or '')
|
||||
if code not in LINE_FIELD_SUPPLEMENT_CODES or code not in values:
|
||||
continue
|
||||
value = values[code]
|
||||
field['raw_value'] = value or None
|
||||
field['normalized_value'] = value or None
|
||||
field['status'] = 'passed' if value else field.get('status') or 'missing'
|
||||
if issues:
|
||||
field['issues'] = list(dict.fromkeys([*(field.get('issues') or []), *issues]))
|
||||
result['line_field_supplement_reasons'] = list(reasons)
|
||||
return result, reasons
|
||||
@@ -1289,6 +1289,9 @@ def preview_profile_region(
|
||||
# Header-only pages document column semantics but must never emit data rows.
|
||||
if not table_region.line_layouts:
|
||||
continue
|
||||
# 补充表不进入预览主网格;验证/正式路径另行按 LN 合并。
|
||||
if str(getattr(table_region, 'region_role', None) or 'business_lines') == 'line_field_supplement':
|
||||
continue
|
||||
# 表头区域只描述列语义与预览,运行时不得删除其覆盖的 glyph;起行 Schema
|
||||
# 交叉校验会拒绝表头,普通 exclusion_regions 才是显式删除授权。
|
||||
reconstruction_exclusions = reconstruction_exclusion_regions(table_region.model_dump())
|
||||
|
||||
@@ -3,10 +3,11 @@ services/shipping_notice/order_document_profile_validation_service.py
|
||||
|
||||
用途:执行订单文档 Profile 草稿的不可变即时检查、当前样本试运行、版面/XFA 结构签名与跨模板唯一性验证。
|
||||
依赖:Profile Revision、受控样本、版面签名/匹配服务、XFA 提取与结构签名、解析校验、
|
||||
Profile 保存服务、编辑租约服务、Reservation 专区锚点投影。
|
||||
Profile 保存服务、编辑租约服务、Reservation 专区锚点投影、line_field_supplement_merge。
|
||||
逻辑:每次运行先冻结草稿和样本证据身份,再只保存安全摘要;坐标 current-sample 在表格/
|
||||
表头试读后投影 Vendor Comments Reservation;XFA current-sample 另附脱敏字段级
|
||||
Header/Line;签名成功后更新 Profile 轻量引用;查询时根据当前 checksum 派生 stale。
|
||||
表头试读后投影 Vendor Comments Reservation,并按 LN 合并 COO 等补充表料号;
|
||||
XFA current-sample 另附脱敏字段级 Header/Line;签名成功后更新 Profile 轻量引用;
|
||||
查询时根据当前 checksum 派生 stale。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -419,6 +420,44 @@ def _extract_coordinate_current_sample(
|
||||
reason=reservation.get('reason'),
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
# [STEP] COO 等明细字段补充表按 LN 合并进验证 lines(与正式/盲测同契约)。
|
||||
if any(
|
||||
isinstance(item, dict) and str(item.get('region_role') or '') == 'line_field_supplement'
|
||||
for item in definition.get('table_regions') or []
|
||||
):
|
||||
from app.services.shipping_notice.line_field_supplement_merge import (
|
||||
project_line_field_supplement_onto_validation_evidence,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_workflow import (
|
||||
_reconstruct_line_field_supplement_rows,
|
||||
)
|
||||
document = db.session.get(ShippingOrderDocument, int(sample.document_id))
|
||||
layout = _load_sample_layout(sample) if document is not None else {}
|
||||
if document is not None and isinstance(layout, dict):
|
||||
layout = ensure_on_demand_coordinate_evidence(
|
||||
document=document, layout=layout, page_nos=None,
|
||||
)
|
||||
schema_fields = {
|
||||
str(item.get('field_id') or ''): item
|
||||
for item in (profile.schema_version.definition_json or {}).get('fields') or []
|
||||
if isinstance(item, dict) and item.get('enabled', True) and item.get('field_id')
|
||||
}
|
||||
supplement_rows, line_start = _reconstruct_line_field_supplement_rows(
|
||||
raw_profile={
|
||||
'definition': definition,
|
||||
'profile_code': profile.profile_code,
|
||||
'version': profile.version,
|
||||
'checksum': profile.checksum,
|
||||
},
|
||||
layout=layout if isinstance(layout, dict) else {},
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
if supplement_rows:
|
||||
evidence, _reasons = project_line_field_supplement_onto_validation_evidence(
|
||||
evidence,
|
||||
supplement_rows=supplement_rows,
|
||||
line_start_field_code=line_start or 'customer_po_line_no',
|
||||
)
|
||||
summary['validation_evidence'] = evidence
|
||||
return status, summary, snapshot
|
||||
|
||||
|
||||
@@ -3,11 +3,12 @@ backend/app/services/shipping_notice/order_extraction_workflow.py
|
||||
|
||||
用途:提供冻结订单抽取快照的确定性模板路由及 STP 裁决(straight_through / needs_review)。
|
||||
依赖:MinerU 紧凑快照、订单 Profile(coordinate / xfa_dataset)、Schema 校验、
|
||||
order_extraction_route_contract、xfa_profile_*、统一错误类型。
|
||||
order_extraction_route_contract、xfa_profile_*、line_field_supplement_merge、统一错误类型。
|
||||
逻辑:Worker 先调用本模块裁决;所有 PDF 先走共同视觉路径,datasets 仅在末端取正式值;
|
||||
datasets 缺失或冲突时共同 OCR 仅作复核/兜底证据并强制 needs_review;
|
||||
唯一 PO 提升到 Header 后从明细剥离,避免 persist 因 scope 不匹配失败;
|
||||
路由产出 Candidate 后由 Candidate Qualification 统一评估自动建单资格;
|
||||
主明细仅来自 region_role=business_lines;line_field_supplement 按 LN 补料号;
|
||||
模板 auto_create_approved 仅作解析器质量痕迹;主链不调用 Dify。
|
||||
"""
|
||||
|
||||
@@ -38,6 +39,10 @@ from app.services.shipping_notice.document_layout.runtime_parse_strategy import
|
||||
resolve_runtime_parse_strategy,
|
||||
select_runtime_region_ids,
|
||||
)
|
||||
from app.services.shipping_notice.line_field_supplement_merge import (
|
||||
NON_BLOCKING_ROW_ISSUE_CODES,
|
||||
merge_line_field_supplement,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
ProfileMatchResult,
|
||||
@@ -379,6 +384,9 @@ def _coordinate_profile_rows(
|
||||
# 的坐标、起行字段与行重建结果裁决,不能仅依赖历史 page_scope 自动建单。
|
||||
if region.region_id not in runtime_region_ids:
|
||||
continue
|
||||
# 补充表不参与主明细重建,避免 COO 等副表进入 matches / multiple_business_tables。
|
||||
if str(getattr(region, 'region_role', None) or 'business_lines') == 'line_field_supplement':
|
||||
continue
|
||||
# A continuation page may carry column headers only; it is not a data layout.
|
||||
if not region.line_layouts:
|
||||
continue
|
||||
@@ -469,6 +477,239 @@ def _coordinate_profile_rows(
|
||||
return rows
|
||||
|
||||
|
||||
def _pick_overlapping_layout_table(
|
||||
*,
|
||||
layout_tables: list[Any],
|
||||
page_no: int,
|
||||
region_relative: dict[str, Any],
|
||||
page_size: dict[str, Any],
|
||||
reference_page_frame: dict[str, Any] | None = None,
|
||||
coordinate_transform: dict[str, Any] | None = None,
|
||||
) -> tuple[str | None, dict[str, float] | None]:
|
||||
"""
|
||||
在同页 layout.tables 中选取与补充表相对区重叠的物理表。
|
||||
|
||||
核心逻辑:将相对区投影为页绝对框后与 MinerU 表求交,取纵向重叠面积最大者。
|
||||
用于样本仅 1 行 COO 时,盲测多行仍能纵向扩到整张物理表读 glyph。
|
||||
|
||||
Args:
|
||||
layout_tables: layout.tables 列表。
|
||||
page_no: 当前页号。
|
||||
region_relative: 补充表区相对 bbox。
|
||||
page_size: 当前页宽高。
|
||||
reference_page_frame: 可选参考页框;缺省用 page_size。
|
||||
coordinate_transform: 可选坐标变换。
|
||||
|
||||
Returns:
|
||||
(table_id, 绝对 bbox) 或 (None, None)。
|
||||
"""
|
||||
projected = apply_coordinate_transform_to_region(
|
||||
region_relative, coordinate_transform=coordinate_transform,
|
||||
)
|
||||
if projected is None:
|
||||
return None, None
|
||||
try:
|
||||
ref_w = float(reference_page_frame['width']) if reference_page_frame is not None else float(page_size['width'])
|
||||
ref_h = float(reference_page_frame['height']) if reference_page_frame is not None else float(page_size['height'])
|
||||
region_bbox = {
|
||||
'x0': float(projected['x0']) * ref_w,
|
||||
'y0': float(projected['y0']) * ref_h,
|
||||
'x1': float(projected['x1']) * ref_w,
|
||||
'y1': float(projected['y1']) * ref_h,
|
||||
}
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None, None
|
||||
best_id: str | None = None
|
||||
best_bbox: dict[str, float] | None = None
|
||||
best_overlap = 0.0
|
||||
for item in layout_tables:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if int(item.get('page_no') or 1) != int(page_no):
|
||||
continue
|
||||
bbox = item.get('bbox')
|
||||
if not isinstance(bbox, dict):
|
||||
continue
|
||||
try:
|
||||
x0, y0, x1, y1 = float(bbox['x0']), float(bbox['y0']), float(bbox['x1']), float(bbox['y1'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if not (x0 < region_bbox['x1'] and x1 > region_bbox['x0'] and y0 < region_bbox['y1'] and y1 > region_bbox['y0']):
|
||||
continue
|
||||
overlap_h = max(0.0, min(x1, region_bbox['x1']) - max(x0, region_bbox['x0']))
|
||||
overlap_v = max(0.0, min(y1, region_bbox['y1']) - max(y0, region_bbox['y0']))
|
||||
overlap_area = overlap_h * overlap_v
|
||||
if overlap_area <= best_overlap:
|
||||
continue
|
||||
best_overlap = overlap_area
|
||||
best_id = str(item.get('table_id') or '') or None
|
||||
best_bbox = {'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1}
|
||||
return best_id, best_bbox
|
||||
|
||||
|
||||
def _reconstruct_line_field_supplement_rows(
|
||||
*,
|
||||
raw_profile: dict[str, Any],
|
||||
layout: dict[str, Any],
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
coordinate_transform: dict[str, Any] | None = None,
|
||||
) -> tuple[list[dict[str, Any]], str | None]:
|
||||
"""
|
||||
从 Profile 的 line_field_supplement 表区按页坐标重建补充行(如 COO)。
|
||||
|
||||
核心逻辑:不把补充表当作业务表命中源;在补充区相对框内读 page_glyphs。
|
||||
若同页存在与标注区重叠的 MinerU 物理表,则用其 bbox 纵向扩展字符范围
|
||||
(样本单行 / 盲测多行时仍能读到整张 COO)。再以 with_strategy 取最佳努力行供 LN 合并。
|
||||
|
||||
Returns:
|
||||
(workflow 形态行列表, line_start_field_code 或 None)
|
||||
"""
|
||||
try:
|
||||
profile = _frozen_coordinate_profile(raw_profile)
|
||||
except (TypeError, ValueError, ValidationError):
|
||||
return [], None
|
||||
supplement_regions = [
|
||||
region for region in profile.table_regions
|
||||
if str(getattr(region, 'region_role', None) or '') == 'line_field_supplement'
|
||||
and region.line_layouts
|
||||
]
|
||||
if not supplement_regions:
|
||||
return [], None
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
layout_tables = layout.get('tables') if isinstance(layout.get('tables'), list) else []
|
||||
rows: list[dict[str, Any]] = []
|
||||
line_start = None
|
||||
for region in supplement_regions:
|
||||
line_start = region.line_start_field_code or 'customer_po_line_no'
|
||||
runtime_ids = set(select_runtime_region_ids(
|
||||
table_regions=[_coordinate_object_mapping(item) for item in profile.table_regions],
|
||||
page_no=int(region.page_no or 1) if region.page_scope == 'exact_page' else 1,
|
||||
))
|
||||
# exact_page 补充区按其页;all_pages/first_page 扫有 glyph 的页。
|
||||
if region.page_scope == 'exact_page':
|
||||
candidate_pages = [int(region.page_no or 1)]
|
||||
else:
|
||||
candidate_pages = sorted(
|
||||
int(page_no) for page_no in page_glyphs
|
||||
if str(page_no).isdigit() and isinstance(page_glyphs.get(str(page_no)), list)
|
||||
)
|
||||
if region.page_scope == 'first_page':
|
||||
candidate_pages = [page for page in candidate_pages if page == 1] or [1]
|
||||
for page_no in candidate_pages:
|
||||
if region.page_scope == 'exact_page' and region.region_id not in runtime_ids and str(page_no) not in {str(region.page_no)}:
|
||||
continue
|
||||
page_size = pages.get(str(page_no))
|
||||
characters = page_glyphs.get(str(page_no))
|
||||
if not isinstance(page_size, dict) or not isinstance(characters, list) or not characters:
|
||||
continue
|
||||
try:
|
||||
page_bbox = {
|
||||
'x0': 0, 'y0': 0,
|
||||
'x1': float(page_size['width']), 'y1': float(page_size['height']),
|
||||
}
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
reference_page_frames = getattr(profile, 'reference_page_frames', {})
|
||||
reference_page_frame = (
|
||||
reference_page_frames.get(page_no)
|
||||
if isinstance(reference_page_frames, dict) else None
|
||||
)
|
||||
reconstruction_page_bbox = (
|
||||
{
|
||||
'x0': 0, 'y0': 0,
|
||||
'x1': reference_page_frame.width, 'y1': reference_page_frame.height,
|
||||
}
|
||||
if reference_page_frame is not None else page_bbox
|
||||
)
|
||||
relative_region = _coordinate_region_mapping(region.region)
|
||||
if relative_region is None:
|
||||
continue
|
||||
ref_frame_mapping = (
|
||||
_coordinate_object_mapping(reference_page_frame)
|
||||
if reference_page_frame is not None else None
|
||||
)
|
||||
# [STEP 1] 样本单行标注的相对框常盖不住盲测多行;重叠物理表纵向扩 glyph。
|
||||
overlap_table_id, overlap_table_bbox = _pick_overlapping_layout_table(
|
||||
layout_tables=layout_tables,
|
||||
page_no=page_no,
|
||||
region_relative=_coordinate_object_mapping(region.region),
|
||||
page_size=page_size,
|
||||
reference_page_frame=ref_frame_mapping,
|
||||
coordinate_transform=coordinate_transform,
|
||||
)
|
||||
filtered, _ = coordinate_profile_character_candidates(
|
||||
table_region=_coordinate_object_mapping(region.region),
|
||||
page_size=page_size,
|
||||
reference_page_frame=ref_frame_mapping,
|
||||
page_characters=characters,
|
||||
table_characters=None,
|
||||
raw_table_bbox=overlap_table_bbox,
|
||||
table_id=overlap_table_id,
|
||||
page_no=page_no,
|
||||
coordinate_transform=coordinate_transform,
|
||||
allow_table_fallback=False,
|
||||
)
|
||||
if not isinstance(filtered, list) or not filtered:
|
||||
continue
|
||||
chosen_rows, _strategy = reconstruct_coordinate_profile_rows_with_strategy(
|
||||
characters=[item for item in filtered if isinstance(item, dict)],
|
||||
table_bbox=reconstruction_page_bbox,
|
||||
line_layouts=[_coordinate_object_mapping(item) for item in region.line_layouts],
|
||||
table_region=relative_region,
|
||||
termination_rules=[_coordinate_object_mapping(item) for item in region.termination_rules],
|
||||
exclusion_regions=reconstruction_exclusion_regions(_coordinate_object_mapping(region)),
|
||||
line_start_field_code=region.line_start_field_code,
|
||||
schema_field_metadata=list(schema_fields.values()),
|
||||
coordinate_transform=coordinate_transform,
|
||||
page_no=page_no,
|
||||
)
|
||||
for reconstructed in chosen_rows:
|
||||
values = [
|
||||
{'field_code': code, 'value': str(raw or '')}
|
||||
for code, raw in reconstructed.fields.items()
|
||||
]
|
||||
rows.append({
|
||||
'fields': values,
|
||||
'issues': list(reconstructed.issues),
|
||||
'page_no': page_no,
|
||||
})
|
||||
return rows, line_start
|
||||
|
||||
|
||||
def _apply_line_field_supplement(
|
||||
*,
|
||||
raw_profile: dict[str, Any],
|
||||
layout: dict[str, Any],
|
||||
parsed_rows: list[dict[str, Any]],
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
coordinate_transform: dict[str, Any] | None = None,
|
||||
) -> tuple[list[dict[str, Any]], list[str]]:
|
||||
"""主表明细重建后,按 LN 合并 line_field_supplement 料号。"""
|
||||
supplement_rows, line_start = _reconstruct_line_field_supplement_rows(
|
||||
raw_profile=raw_profile,
|
||||
layout=layout,
|
||||
schema_fields=schema_fields,
|
||||
coordinate_transform=coordinate_transform,
|
||||
)
|
||||
if not supplement_rows:
|
||||
return parsed_rows, []
|
||||
merged, reasons = merge_line_field_supplement(
|
||||
parsed_rows,
|
||||
supplement_rows,
|
||||
line_start_field_code=line_start or 'customer_po_line_no',
|
||||
)
|
||||
for row in merged:
|
||||
issue_list = row.get('issues') if isinstance(row.get('issues'), list) else []
|
||||
if any(
|
||||
code in {'line_field_supplement_conflict', 'line_field_supplement_ln_ambiguous'}
|
||||
for code in issue_list
|
||||
):
|
||||
row['status'] = 'needs_review'
|
||||
return merged, reasons
|
||||
|
||||
|
||||
def _selected_coordinate_transform(
|
||||
*, profile_match: dict[str, Any], raw_profile: dict[str, Any],
|
||||
) -> dict[str, Any] | None:
|
||||
@@ -620,10 +861,11 @@ def _physical_table_targets_profile_region(
|
||||
):
|
||||
return False
|
||||
return True
|
||||
# [STEP 2] 仅含 line_layouts 的明细区才是重建目标;纯表头壳直接跳过。
|
||||
# [STEP 2] 仅含 line_layouts 的业务明细区才是重建目标;纯表头壳与补充表直接跳过。
|
||||
active_regions = [
|
||||
region for region in page_regions
|
||||
if region.get('line_layouts')
|
||||
and str(region.get('region_role') or 'business_lines') != 'line_field_supplement'
|
||||
]
|
||||
if not active_regions:
|
||||
return False
|
||||
@@ -1042,6 +1284,18 @@ def _profile_table_candidates(
|
||||
issues.append('order_profile_multiple_matches')
|
||||
continue
|
||||
raw_profile, parsed = matches[0]
|
||||
coordinate_transform = _selected_coordinate_transform(
|
||||
profile_match=profile_match, raw_profile=raw_profile,
|
||||
)
|
||||
parsed, supplement_reasons = _apply_line_field_supplement(
|
||||
raw_profile=raw_profile,
|
||||
layout=layout,
|
||||
parsed_rows=parsed,
|
||||
schema_fields=schema_fields,
|
||||
coordinate_transform=coordinate_transform,
|
||||
)
|
||||
if any(code.endswith('_conflict') or code.endswith('_ambiguous') for code in supplement_reasons):
|
||||
issues.extend(supplement_reasons)
|
||||
reservation_region = _reservation_region_candidates(raw_profile=raw_profile, layout=layout)
|
||||
result_tables.append({
|
||||
'profile_id': raw_profile.get('profile_id') or raw_profile.get('id'),
|
||||
@@ -1052,6 +1306,7 @@ def _profile_table_candidates(
|
||||
'page_no': int(raw_table.get('page_no') or 1),
|
||||
'auto_create_approved': bool(raw_profile.get('auto_create_approved')),
|
||||
'rows': parsed,
|
||||
'line_field_supplement_reasons': list(supplement_reasons),
|
||||
'reservation_region_candidates': reservation_region['candidates'],
|
||||
'reservation_region_reason': reservation_region['reason'],
|
||||
'runtime_parse_strategy': {
|
||||
@@ -1925,7 +2180,13 @@ def _build_approved_profile_order_result(
|
||||
# Profile parser 已判定 deleted/invalid 行不可进入订单;禁止把部分解析结果当作完整订单。
|
||||
if not isinstance(row, dict) or row.get('status') == 'deleted':
|
||||
continue
|
||||
if row.get('status') != 'parsed' or row.get('issues'):
|
||||
# [STEP] 忽略成功补料号等非阻塞审计码;仅真实缺陷才触发 row_needs_review。
|
||||
raw_issues = row.get('issues') if isinstance(row.get('issues'), list) else []
|
||||
blocking_issues = [
|
||||
code for code in raw_issues
|
||||
if str(code or '').strip() and str(code) not in NON_BLOCKING_ROW_ISSUE_CODES
|
||||
]
|
||||
if row.get('status') != 'parsed' or blocking_issues:
|
||||
if not allow_manual_review:
|
||||
return None, 'row_needs_review'
|
||||
has_review_rows = True
|
||||
|
||||
@@ -5,7 +5,7 @@ Reservation ID 专用证据区域解析器。
|
||||
并投影到验证证据 / 订单归属契约。
|
||||
依赖:reservation_id 格式校验、coordinate_region_text 视觉行序。
|
||||
逻辑:reservation_id_region 仅作启用标记;画布预览、盲测、正式解析共用本模块的
|
||||
锚点扫描与 apply/project,不再按保存矩形截取正式值。
|
||||
锚点扫描与 apply/project,不再按保存矩形截取正式值;行号含 line# / L# / LN#。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,7 +19,15 @@ from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
|
||||
_ID_RE = re.compile(r"(?<!\d)(\d{5}|\d{10})(?!\d)")
|
||||
_LINE_RE = re.compile(r"\b(?:reservation\s+)?line\s*#?\s*(\d+)\b|\bfor\s+line\s*#?\s*(\d+)\b", re.I)
|
||||
# 行号写法:Line 1 / line#1 / for line#1 / Hyve 缩写 L#1、LN#1。
|
||||
_LINE_RE = re.compile(
|
||||
r"(?:"
|
||||
r"\b(?:reservation\s+)?line\s*#?\s*(\d+)\b"
|
||||
r"|\bfor\s+line\s*#?\s*(\d+)\b"
|
||||
r"|\bl(?:n)?\s*#\s*(\d+)\b"
|
||||
r")",
|
||||
re.I,
|
||||
)
|
||||
_RESERVATION_LABEL_RE = re.compile(r"\breservation\b\s*(?:id)?\s*(?:#|:|-)?", re.I)
|
||||
_VENDOR_COMMENTS_HEADING_RE = re.compile(r'^\s*vendor\s+comments?\b', re.I)
|
||||
_TERMS_AND_CONDITIONS_HEADING_RE = re.compile(
|
||||
@@ -48,7 +56,11 @@ class ReservationRegionApplication:
|
||||
|
||||
|
||||
def extract_reservation_from_region(text: str) -> list[ReservationRegionCandidate]:
|
||||
"""从区域原文提取候选;有行号归明细,无行号归订单头。"""
|
||||
"""从区域原文提取候选;有行号归明细,无行号归订单头。
|
||||
|
||||
核心逻辑:同行须含 Reservation 标签;行号支持 ``line#1`` / ``for line#1`` /
|
||||
``L#1`` / ``LN#1`` 等写法,命中后 scope=line,禁止误写入订单头。
|
||||
"""
|
||||
candidates: list[ReservationRegionCandidate] = []
|
||||
for raw_line in (str(text or '').splitlines() or [str(text or '')]):
|
||||
line = raw_line.strip()
|
||||
@@ -63,7 +75,8 @@ def extract_reservation_from_region(text: str) -> list[ReservationRegionCandidat
|
||||
line_match = _LINE_RE.search(line)
|
||||
line_no = None
|
||||
if line_match:
|
||||
line_no = int(line_match.group(1) or line_match.group(2))
|
||||
captured = next((group for group in line_match.groups() if group is not None), None)
|
||||
line_no = int(captured) if captured is not None else None
|
||||
scope = 'line' if line_no is not None else 'header'
|
||||
status = 'mapped' if line_no is not None else 'header'
|
||||
for value in dict.fromkeys(ids):
|
||||
|
||||
Reference in new issue
Block a user