feat(shipping-notice): 无表头文档抽取增强与复核深链身份修复

- 新增表头 OCR 救援:模板匹配落 layout_drift/no_match 时按表头带证据补洞重评候选身份,主抽取流程接入并落 identity_rescue 事实字段
- 预约号裸数字兜底:正文无表头且常规证据缺失时扫描 5/10 位纯数字候选,持久化预置、合并末段唯一/多候选裁决
- 修复复核深链仅带 run_no 时队列项显示未命名:Case 身份优先按当前工作面 displayCase 匹配队列项
- 同步抽取 Job/运行服务/候选持久化配套与 OCR 救援、预约号启发式、表头身份测试
This commit is contained in:
hugo committed 2026-10-14 19:31:39 +08:00
1 parent 6ac2effac3
commit 92ed140739
15 files changed
+1660 -6

No files matched your search

@@ -2,9 +2,11 @@
services/shipping_notice/reservation_id.py
用途:提取、标准化并校验发货通知与库存中的 Reservation ID。
依赖:正则表达式与标准 `typing` 工具。
依赖:正则表达式与标准 `typing` 工具;裸数字兜底扫描惰性依赖版面 HTML 网格解析。
逻辑:由 notice_lines、inventory_snapshot、match、extract、EML 补充解析等多个模块复用;
归一结果恒为 5/10 位纯数字(可剥括号备注、@ 前缀、短数字行序后缀如 35354-1)。
另提供「裸数字兜底」:正文无表头且常规证据缺失时,扫描排除后的 5/10 位
纯数字候选(供 order_supplement_merge 在合并末段做唯一/多候选裁决)。
"""
from __future__ import annotations
@@ -30,6 +32,17 @@ PR_NUMBER_LINE_RE = re.compile(
r"PR\s*Number\s*[::]?\s*([^\n\r]+)",
re.IGNORECASE,
)
# [裸数字兜底] 独立的 5/10 位纯数字 token;前后不能紧贴数字,防止从更长数字串截取。
BARE_NUMERIC_RESERVATION_RE = re.compile(r"(?<!\d)(\d{5}|\d{10})(?!\d)")
# [裸数字兜底] 紧跟业务标签的数字串(PO/订单/发票/数量)不是预约单号;捕获组为数字本体。
# 保留前导词边界防止命中复合词内部;尾部不加边界、由「必须跟数字」门控,
# 使 PO12345 / PO# 12345 / Purchase Order: 12345 等写法都被覆盖,而 podium 等词不受影响。
LABELED_NON_RESERVATION_RE = re.compile(
r"(?i)(?:\bp\.?\s*o\.?|\bpurchase\s+orders?|\borders?|\binvoices?|\binv\.?|\bqty\.?|\bquantity)"
r"(?:\s*(?:number|no\.?|#))?\s*[:#]?\s*(\d{3,})"
)
# 候选数量上限:转发/引用链可能携带大量历史数字,防止 supplement 快照被刷爆。
MAX_HEURISTIC_RESERVATION_CANDIDATES = 20
def normalize_reservation_id(value: Any) -> str:
@@ -151,3 +164,135 @@ def validated_reservation_id(value: Any, *, numeric_only: bool = False) -> str:
"""提取并返回合法 Reservation ID;候选不满足契约时返回空字符串。"""
candidate = extract_reservation_id(value)
return candidate if is_valid_reservation_id(candidate, numeric_only=numeric_only) else ""
def reservation_ids_in_labeled_context(text: str) -> set[str]:
"""返回文本中紧跟业务标签(PO/订单/发票/数量)的数字串,供裸数字候选排除。
AI 触发时机:合并末段判断裸数字候选前,先排除邮件主题等上下文里
「PO xxx」「Invoice xxx」这类带标签的数字,即使它们未被提取为字段。
Args:
text: 任意原文(邮件主题、正文段落等)。
Returns:
set[str]: 标签后紧跟的数字串原文(未归一);无命中返回空集合。
"""
return {
match.group(1)
for match in LABELED_NON_RESERVATION_RE.finditer(str(text or ""))
}
def _heuristic_context_snippet(text: str, match: re.Match[str]) -> str:
"""截取 token 所在行命中国的前后片段,供复核面板展示证据上下文。"""
start = max(match.start() - 40, 0)
end = min(match.end() + 40, len(text))
return text[start:end].strip()
def _iter_heuristic_cell_texts(html_tables: list[str] | None, content_hash: str):
"""惰性产出 HTML 表格单元格文本及其证据定位;解析失败的表安全跳过。
逻辑:版面网格的 cell_id 是 DOM 级可追溯证据,优先于行号猜测;
惰性导入 html_table 避免给本工具模块增加常驻依赖。
"""
if not html_tables:
return
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
for table_index, html in enumerate(html_tables):
try:
grid = parse_html_grid(
str(html or ''), table_id=f'reservation-heuristic:{content_hash}:{table_index}',
)
except Exception:
continue
for row_index, row in enumerate(grid.rows):
for column, slot in enumerate(row):
if slot is None or not str(slot.text or '').strip():
continue
yield str(slot.text), {
'table_index': table_index,
'row_index': row_index,
'column_index': column,
'cell_id': slot.cell_id,
}
def find_bare_numeric_reservation_candidates(
*,
body_text: str = "",
html_tables: list[str] | None = None,
content_hash: str = "",
) -> list[dict[str, Any]]:
"""扫描正文中的裸 5/10 位纯数字预约单号候选(排除带业务标签的数字)。
AI 触发时机:EML 正文数据行没有表头、常规表头契约解析不出预约单号时,
在补充事实里预置候选列表;真正「是否采纳」由 order_supplement_merge 在
合并末段结合已提取字段值裁决,本函数绝不直接写入订单。
核心逻辑:先扫 HTML 表格单元格(保留 DOM cell_id 证据),再扫纯文本行
(保留行号与上下文片段);紧跟 PO/订单/发票/数量标签的数字串不作为候选;
同值只保留首个证据;总数截断到 MAX_HEURISTIC_RESERVATION_CANDIDATES。
Args:
body_text: EML 正文纯文本(含展平的数据行)。
html_tables: 正文顶层 HTML 表格片段列表;可为空。
content_hash: 正文 Document 内容哈希,用于稳定 cell_id。
Returns:
list[dict]: ``[{value, evidence}]``;evidence 含 table_index/row_index/
column_index/cell_id/raw_value,纯文本候选另含 context。扫描不到返回空列表。
"""
candidates: list[dict[str, Any]] = []
seen: set[str] = set()
def _collect(text: str, base_evidence: dict[str, Any]) -> None:
excluded_spans = [item.span() for item in LABELED_NON_RESERVATION_RE.finditer(text)]
for match in BARE_NUMERIC_RESERVATION_RE.finditer(text):
if any(start <= match.start() and match.end() <= end for start, end in excluded_spans):
continue
value = match.group()
if value in seen or len(candidates) >= MAX_HEURISTIC_RESERVATION_CANDIDATES:
continue
seen.add(value)
evidence = {**base_evidence, 'raw_value': value}
if 'cell_id' not in evidence:
evidence['cell_id'] = f"reservation-heuristic:{content_hash}:line{evidence.get('row_index')}"
evidence['context'] = _heuristic_context_snippet(text, match)
candidates.append({'value': value, 'evidence': evidence})
for cell_text, base_evidence in _iter_heuristic_cell_texts(html_tables, content_hash):
_collect(cell_text, dict(base_evidence))
for line_index, line in enumerate(str(body_text or '').splitlines()):
if line.strip():
_collect(line, {'table_index': None, 'row_index': line_index + 1, 'column_index': None})
return candidates
def filter_reservation_heuristic_candidates(
candidates: list[dict[str, Any]],
*,
excluded_values: set[str],
) -> tuple[list[dict[str, Any]], str]:
"""按「已识别字段值/跨单已占用」排除后裁决候选状态。
Args:
candidates: ``find_bare_numeric_reservation_candidates`` 的产物。
excluded_values: 需排除的值集合(比较前统一 strip+大写)。
Returns:
``(surviving, status)``:status 为 ``unique``(恰好一个,可自动采纳)、
``ambiguous``(多个,转人工裁决)或 ``none``(无候选)。
"""
excluded = {str(value).strip().upper() for value in excluded_values if str(value).strip()}
surviving = [
item for item in (candidates or [])
if str(item.get('value') or '').strip().upper() not in excluded
]
if not surviving:
return [], 'none'
if len(surviving) == 1:
return surviving, 'unique'
return surviving, 'ambiguous'