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:55:37 +08:00
1 parent af2658e244
commit d7d4819a42
15 files changed
+1660 -6

No files matched your search

@@ -724,6 +724,58 @@ def _handoff_continue_order_extraction(
return True
def _emit_reservation_heuristic_audit(
*,
run: Any,
merged_by_unit_id: dict[int, list[dict[str, Any]]],
) -> None:
"""
合并末段「裸数字预约单号兜底」落地后补审计事件,供上线后观察误判率。
【AI 触发时机】:EML 补充合并(merge_email_supplements)完成后调用。
只读订单上的 _hxops_reservation_heuristic 标记,不修改订单;命中与多候选
各发一条事件,metadata 携带 unit/候选值/正文文档定位,便于按 Case 回溯证据。
Args:
run: 当前订单抽取 Run(审计聚合根)。
merged_by_unit_id: 本趟合并产物 {unit_id: [order]}。
"""
applied_entries: list[dict[str, Any]] = []
ambiguous_entries: list[dict[str, Any]] = []
for unit_id, orders in (merged_by_unit_id or {}).items():
for order in orders or []:
marker = order.get('_hxops_reservation_heuristic') if isinstance(order, dict) else None
if not isinstance(marker, dict):
continue
entry = {
'unit_id': int(unit_id),
'values': marker.get('values') or [],
'document_id': marker.get('document_id'),
}
if marker.get('status') == 'applied':
applied_entries.append({**entry, 'value': marker.get('value')})
else:
ambiguous_entries.append(entry)
for event_type, entries in (
('reservation_heuristic_applied', applied_entries),
('reservation_heuristic_ambiguous', ambiguous_entries),
):
if not entries:
continue
append_shipping_audit_event(
event_type=event_type,
aggregate_type='order_extraction_run',
aggregate_id=str(run.id),
run_no=run.run_no,
actor_type='system',
source='shipping_order_extraction',
metadata={
'entries': entries,
'decision_rule_version': 'bare-numeric-reservation-v1',
},
)
def _is_transient_lock_error(exc: BaseException) -> bool:
"""
判断异常是否为瞬时锁冲突(PostgreSQL 死锁 40P01 / 锁等待超时 55P03)。
@@ -1139,6 +1191,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
},
)
_merge_group_orders(eml_units, apply_email_supplements=True)
_emit_reservation_heuristic_audit(run=run, merged_by_unit_id=merged_by_unit_id)
append_shipping_audit_event(
event_type='ORDER_EMAIL_ADJUDICATION_COMPLETED',
aggregate_type='order_extraction_run',
@@ -47,6 +47,7 @@ from app.services.shipping_notice.order_candidate_builder import (
build_email_order_index,
merge_attachment_candidate,
)
from app.services.shipping_notice.reservation_id import find_bare_numeric_reservation_candidates
BODY_ATTACHMENT_KEY = 'body'
@@ -665,6 +666,14 @@ def persist_documents_and_candidates(
schema_definition=definition,
)
supplement['document_id'] = int(body_doc.id)
# [裸数字兜底] 无表头数据行解析不出补充行时,预置正文裸 5/10 位数字候选;
# 是否采纳由 merge_email_supplements 在合并末段结合已提取字段值裁决。
supplement['reservation_candidates'] = find_bare_numeric_reservation_candidates(
body_text=body_text,
html_tables=canonical_html_tables,
content_hash=str(body_doc.content_hash or ''),
)
supplement['email_subject'] = str(email_meta.get('subject') or '')
body_doc.order_extraction_result_json = _json_safe_value({
'email_supplement': supplement,
})
@@ -680,6 +689,7 @@ def persist_documents_and_candidates(
'row_count': len(supplement.get('rows') or []),
'issue_codes': list(supplement.get('issues') or []),
'parser_version': supplement.get('version'),
'reservation_candidate_count': len(supplement.get('reservation_candidates') or []),
},
)
active_keys.add(BODY_ATTACHMENT_KEY)
@@ -95,6 +95,10 @@ class ProfileMatchCandidate(BaseModel):
dimension_states: dict[str, MatchDimensionState] = Field(default_factory=dict)
margin_to_next: float | None = Field(default=None, ge=0, le=1)
coordinate_transform: dict[str, Any] | None = None
identity_rescue_assisted: bool = Field(
default=False,
description='该候选的表头身份由表头带证据补洞达成(order_profile_ocr_rescue)。',
)
class ProfileMatchResult(BaseModel):
@@ -124,6 +128,10 @@ class ProfileMatchResult(BaseModel):
margin: float | None = Field(default=None, ge=0, le=1)
scoring_policy_version: str = MATCHER_POLICY_ID
parse_validation: dict[str, Any] | None = None
identity_rescue_source: str | None = Field(
default=None,
description='本次唯一命中的表头带证据补洞来源(acroform_widget / ocr_coordinate);None=未补洞。',
)
def match_frozen_coordinate_profiles(
@@ -1088,7 +1096,10 @@ def _header_normalized_words(text: str) -> list[str]:
核心逻辑:词级原子化与 Schema 别名短语匹配共用同一切词口径,保证两条路径
产出的身份原子完全同源;返回非空小写词序列(中文等非 [a-z0-9] 文本切词为空,
调用方按各自的跳过策略处理)。
调用方按各自的跳过策略处理)。有意不拆驼峰:真实表头大小写不可靠
('UnitCost'/'unitcost'/'UNITCOST' 皆可能出现),仅按大小写边界拆分对全小写
渲染不生效,反而制造两侧不对称;camelCase 别名的对齐由
schema_canonical_header_atoms/_tokens 的连写短语键承担。
"""
normalized = _HEADER_PAREN_GLOSS.sub(' ', str(text).casefold())
normalized = re.sub(r"['’]", '', normalized)
@@ -1180,10 +1191,12 @@ def schema_canonical_header_atoms(
具体措辞。未配置别名时零行为变化,完全退化为词级原子。
核心逻辑:
- header_to_field 为 None/空 dict 时直接返回词级原子(兼容旧签名,零风险);
- header_to_field 为 None/空 dict 时直接返回词级原子(兼容旧签名,零行为变化);
- 先把每个别名 key 经与 token 完全相同的词管线(剥括号注记 → casefold →
去撇号 → 按非字母数字切词)转为词元组;同一词元组 casefold 后指向多个
field_code 时整体弃用该短语——身份归属不允许歧义;
- 多词别名额外注册去空格连写短语键([STEP 1.1],如 'Unit Cost' ↔
'unitcost'),使 camelCase 无分隔符表头与空格措辞收敛到同一 field 原子;
- 逐 token 用同一词管线切词后做贪心最长短语匹配:命中即消费整段并产出
field::<field_code> 原子(短语内单词不再残留);未命中的剩余单词沿用词级
原子的既有过滤(长度 >= _HEADER_ATOM_MIN_LEN 且不在 _HEADER_ATOM_STOPWORDS);
@@ -1218,6 +1231,19 @@ def schema_canonical_header_atoms(
if len(codes) == 1
}
# [STEP 1.1] 连写短语键:camelCase 别名经 normalize_table_header 拆成
# 'Unit Cost' 类带空格键,但真实表头 token 常以无分隔符形式出现且大小写
# 不可靠('UnitCost'/'unitcost'),按大小写边界拆词对全小写渲染不生效。
# 为多词短语额外注册去空格连写键,使连写/空格/混合大小写拼写收敛到同一
# field 原子;只新增、不覆盖既有键,连写键跨字段歧义时整体弃用(同 [STEP 1])。
joined_candidates: dict[tuple[str, ...], set[str]] = {}
for words, code in phrase_to_field.items():
if len(words) > 1:
joined_candidates.setdefault((''.join(words),), set()).add(code)
for joined, codes in joined_candidates.items():
if len(codes) == 1 and joined not in phrase_to_field:
phrase_to_field[joined] = next(iter(codes))
# [STEP 2] 逐 token 贪心最长短语匹配;未命中单词走既有词级原子过滤。
atoms: set[str] = set()
for token in tokens:
@@ -1269,6 +1295,7 @@ def schema_canonical_header_tokens(
- header_to_field 为 None/空 dict 时原样返回输入列表(零归一、零行为变化);
- 短语字典构建与 atoms [STEP 1] 完全同源:别名 key 经同一词管线转词元组,
同一词元组 casefold 后指向多个 field_code 时整体弃用(身份不允许歧义);
多词别名同样注册连写短语键([STEP 1.1],与 atoms 同一口径);
- 逐 token 贪心最长短语匹配:命中片段消费整段并在原位置产出**单个**
`field::<field_code>` 列表项(短语内单词不残留);未命中词按 atoms 同一
过滤(长度 >= _HEADER_ATOM_MIN_LEN 且不在 _HEADER_ATOM_STOPWORDS)原词保留;
@@ -1301,6 +1328,17 @@ def schema_canonical_header_tokens(
if len(codes) == 1
}
# [STEP 1.1] 连写短语键:与 schema_canonical_header_atoms 的 [STEP 1.1] 同一
# 口径——为 camelCase 多词别名注册去空格连写键('Unit Cost' ↔ 'UnitCost'/
# 'unitcost'),只新增、不覆盖既有键,歧义整体弃用。
joined_candidates: dict[tuple[str, ...], set[str]] = {}
for words, code in phrase_to_field.items():
if len(words) > 1:
joined_candidates.setdefault((''.join(words),), set()).add(code)
for joined, codes in joined_candidates.items():
if len(codes) == 1 and joined not in phrase_to_field:
phrase_to_field[joined] = next(iter(codes))
# [STEP 2] 逐 token 贪心最长短语匹配;序列语义:命中产出单个标记列表项,
# 未命中单词原样保留(沿用 atoms 过滤),整体保序、允许重复。
canonical: list[str] = []
@@ -0,0 +1,395 @@
"""
backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py
用途:模板路由失败时的「表头带证据补洞」定向补救(Route B)。
依赖:order_profile_matcher(匹配器与观测管线)、xfa_acroform(AcroForm 控件定位)、
native_pdf(pdfium 渲染)、ocr_pdf(RapidOCR)、file_assets 服务、tool_common 配置。
逻辑:常规匹配 layout_drift/no_match 且存在「仅表头判别冲突 + 观测原子为期望原子
真子集」的可补救候选集合时,按优先级补齐页 1 主表表头带证据:
① AcroForm/XFA 控件展示值(确定性、精确坐标,覆盖供应商把表头文字放进
表单控件/矢量层的世代);② RapidOCR 表头带(纯扫描/图像兜底)。
补洞字形带 source 标记并入页 1 表头带后重跑完整匹配器;仅当结果恰好唯一
命中集合内某个候选时采纳并打 identity_rescue_source 标记,否则维持原判
(fail-closed 由构造保证:补洞引入外来原子会破坏候选自身集合全等,同时
满足多个候选则转 ambiguous,均被拒绝)。补洞字形只在本次匹配内存中生效,
禁止回写布局版本。
"""
from __future__ import annotations
import unicodedata
from typing import Any, Callable
from app.services.shipping_notice.document_layout.order_profile_matcher import (
ProfileMatchCandidate,
ProfileMatchResult,
_extract_matching_signature,
_header_token_atoms,
_observe_layout_features,
_profile_exclusion_regions,
_profile_termination_rules,
_resolve_coordinate_transform,
_signature_identity_header_tokens,
_translate_signature,
match_frozen_coordinate_profiles,
schema_canonical_header_atoms,
)
from app.services.shipping_notice.document_layout.order_profile import (
OrderCoordinateProfile,
)
# 与 ocr_pdf.OCR_CONFIDENCE_FLOOR 对齐;低于该置信度的 OCR 行不参与补洞。
OCR_RESCUE_CONFIDENCE_FLOOR = 0.8
# 表头带高度占主表高度的比例,与 _observe_header_candidates 的保守带一致。
_HEADER_BAND_RATIO = 0.30
_BAND_EPSILON = 0.005
def _fold_diacritics(text: str) -> str:
"""NFKD 折叠并剥离音变符号(Komárom→Komarom),与历史签名的无音变口径对齐。"""
decomposed = unicodedata.normalize('NFKD', str(text or ''))
return ''.join(ch for ch in decomposed if unicodedata.category(ch) != 'Mn')
def _candidate_header_atoms(
*,
raw_profile: dict[str, Any],
layout: dict[str, Any],
header_to_field: dict[str, str] | None,
) -> tuple[frozenset[str], frozenset[str], dict[str, Any]]:
"""按匹配器同一观测口径计算候选的期望/观测表头原子与观测特征。"""
signature_body, _meta = _extract_matching_signature(raw_profile)
definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {}
profile = OrderCoordinateProfile(
profile_code=str(raw_profile.get('profile_code') or ''),
version=int(raw_profile.get('version') or 0),
document_match=definition.get('document_match'),
table_regions=definition.get('table_regions'),
order_field_layouts=definition.get('order_field_layouts') or [],
coordinate_model=definition.get('coordinate_model') or {},
reference_page_frames=definition.get('reference_page_frames') or {},
)
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
transform, _reasons = _resolve_coordinate_transform(
profile=profile, pages=pages, page_glyphs=page_glyphs,
)
observed = _observe_layout_features(
layout=layout,
tables=[item for item in layout.get('tables') or [] if isinstance(item, dict)],
pages=pages,
glyph_tables=glyph_tables,
page_glyphs=page_glyphs,
signature=_translate_signature(signature=signature_body, coordinate_transform=transform),
termination_rules=_profile_termination_rules(profile),
exclusion_regions=_profile_exclusion_regions(profile),
)
expected_tokens = _signature_identity_header_tokens(signature_body)
observed_tokens = [str(item) for item in observed.get('header_tokens') or []]
if header_to_field:
expected_atoms = schema_canonical_header_atoms(expected_tokens, header_to_field)
observed_atoms = schema_canonical_header_atoms(observed_tokens, header_to_field)
else:
expected_atoms = _header_token_atoms(expected_tokens)
observed_atoms = _header_token_atoms(observed_tokens)
return expected_atoms, observed_atoms, observed
def _eligible_rescue_candidates(
*,
match: ProfileMatchResult,
profiles: list[dict[str, Any]],
layout: dict[str, Any],
header_to_field: dict[str, str] | None,
) -> dict[tuple[str, int], tuple[ProfileMatchCandidate, dict[str, Any]]]:
"""
甄别可补救候选集合:冲突仅表头判别、观测原子为期望原子真子集。
核心逻辑:近亲模板常各自缺不同的尾部列,多个候选可同时可补救——竞争裁决
交给补洞后的完整重跑(接受条件要求补洞后恰好唯一命中集合内候选);
观测侧存在期望之外的外来原子时该候选不可补救(不是单纯缺字)。
"""
profile_by_key = {
(str(item.get('profile_code') or ''), int(item.get('version') or 0)): item
for item in profiles if isinstance(item, dict)
}
eligible: dict[tuple[str, int], tuple[ProfileMatchCandidate, dict[str, Any]]] = {}
for candidate in match.candidates:
if sorted(candidate.reason_codes) != ['profile_header_discriminator_conflict']:
continue
key = (candidate.profile_code, candidate.version)
raw = profile_by_key.get(key)
if raw is None:
continue
expected_atoms, observed_atoms, _observed = _candidate_header_atoms(
raw_profile=raw, layout=layout, header_to_field=header_to_field,
)
if not (expected_atoms - observed_atoms) or (observed_atoms - expected_atoms):
continue
eligible[key] = (candidate, raw)
return eligible
def _glyphs_in_header_band(
*,
glyphs: list[dict[str, Any]],
page_width: float,
page_height: float,
primary_table_bbox: list[float] | None,
source: str,
) -> list[dict[str, Any]]:
"""把补洞字形过滤到主表表头带内(归一化坐标,含少量容差)并打来源标记。"""
if not primary_table_bbox or len(primary_table_bbox) != 4:
return []
if page_width <= 0 or page_height <= 0:
return []
x0, y0, x1, y1 = primary_table_bbox
band_height = max(0.001, y1 - y0) * _HEADER_BAND_RATIO
kept: list[dict[str, Any]] = []
for glyph in glyphs:
bbox = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else None
if not bbox:
continue
center_x = (float(bbox.get('x0') or 0) + float(bbox.get('x1') or 0)) / 2 / page_width
center_y = (float(bbox.get('y0') or 0) + float(bbox.get('y1') or 0)) / 2 / page_height
if (
x0 - _BAND_EPSILON <= center_x <= x1 + _BAND_EPSILON
and y0 - _BAND_EPSILON <= center_y <= y0 + band_height + _BAND_EPSILON
):
marked = dict(glyph)
marked['source'] = source
kept.append(marked)
return kept
def _text_to_char_glyphs(text: str, bbox: dict[str, float]) -> list[dict[str, Any]]:
"""
把控件展示值按词分配展开为字形(与 OCR 字形同构,供视觉行重组)。
核心逻辑:词内字符连续;词间与控件尾部预留 > 0.75×字符宽的几何空隙,
保证 positioned_token_spans 的显著间隔分词能恢复出与签名一致的 token
切分(否则相邻控件字形会被并词,如 'ETD'+'ETA' → 'etdeta')。
"""
folded = _fold_diacritics(text)
words = [word for word in folded.split() if word.strip()]
if not words:
return []
bbox_width = max(0.01, float(bbox['x1']) - float(bbox['x0']))
usable_ratio = 0.7
word_gap_ratio = 1.2
total_chars = sum(len(word) for word in words)
char_width = bbox_width * usable_ratio / max(1, total_chars)
out: list[dict[str, Any]] = []
x = float(bbox['x0'])
y0, y1 = float(bbox['y0']), float(bbox['y1'])
for word in words:
for character in word:
out.append({'text': character, 'bbox': {
'x0': x, 'y0': y0, 'x1': x + char_width, 'y1': y1,
}})
x += char_width
x += char_width * word_gap_ratio
return out
def _collect_rescue_glyphs(
*,
document: Any,
page: dict[str, Any],
primary_table_bbox: list[float] | None,
page_images_fn: Callable[[bytes], list[Any]] | None,
ocr_lines_fn: Callable[..., list[Any]] | None,
read_asset_fn: Callable[[int], bytes],
) -> tuple[list[dict[str, Any]], str] | None:
"""
按优先级收集表头带补洞字形。
① AcroForm/XFA 控件展示值(确定性);② 整带 RapidOCR(图像兜底)。
Returns:
(字形列表, 来源标记) 或 None(无可用证据)。
"""
page_width = float(page.get('width') or 0)
page_height = float(page.get('height') or 0)
asset_id = int(getattr(document, 'asset_id', 0) or 0)
# [STEP 1] AcroForm/XFA 控件文本:确定性坐标与文本,优先于 OCR。
if asset_id > 0:
try:
from app.services.shipping_notice.document_layout.xfa_acroform import (
read_acroform_widgets,
)
content = read_asset_fn(asset_id)
widgets = [
widget for widget in read_acroform_widgets(content)
if int(widget.page_no) == 1 and str(widget.value or '').strip()
]
widget_glyphs: list[dict[str, Any]] = []
for widget in widgets:
nb = widget.normalized_bbox or {}
if not all(key in nb for key in ('x0', 'y0', 'x1', 'y1')):
continue
widget_glyphs.extend(_text_to_char_glyphs(str(widget.value), {
'x0': float(nb['x0']) * page_width,
'y0': float(nb['y0']) * page_height,
'x1': float(nb['x1']) * page_width,
'y1': float(nb['y1']) * page_height,
}))
band = _glyphs_in_header_band(
glyphs=widget_glyphs, page_width=page_width, page_height=page_height,
primary_table_bbox=primary_table_bbox, source='acroform_widget',
)
if band:
return band, 'acroform_widget'
except Exception: # noqa: BLE001 - 控件读取失败时回退 OCR 来源,补救不阻断主链
pass
# [STEP 2] 表头带 RapidOCR:渲染页 1 后 OCR(纯扫描/图像世代兜底)。
if asset_id <= 0:
return None
try:
if read_asset_fn is None:
from app.services.file_assets.service import read_asset_bytes
read_asset_fn = read_asset_bytes
if page_images_fn is None:
from app.services.shipping_notice.document_layout.native_pdf import (
extract_native_pdf_pages,
)
def page_images_fn(content: bytes) -> list[Any]:
return extract_native_pdf_pages(content, render_images=True)
if ocr_lines_fn is None:
from app.services.shipping_notice.document_layout.ocr_pdf import (
OCR_CONFIDENCE_FLOOR,
extract_ocr_lines,
)
def ocr_lines_fn(*args: Any, **kwargs: Any) -> list[Any]:
kwargs.setdefault('minimum_confidence', OCR_CONFIDENCE_FLOOR)
return extract_ocr_lines(*args, **kwargs)
pdf_pages = page_images_fn(read_asset_fn(asset_id))
first_page = next((item for item in pdf_pages if int(item.page_no) == 1), None)
if first_page is None or first_page.image is None:
return None
ocr_lines = ocr_lines_fn(
first_page.image,
page_width=first_page.width,
page_height=first_page.height,
minimum_confidence=OCR_RESCUE_CONFIDENCE_FLOOR,
)
if not ocr_lines:
return None
from app.services.shipping_notice.order_document_profile_service import (
_ocr_lines_to_page_characters,
)
ocr_glyphs = [
{**glyph, 'text': _fold_diacritics(str(glyph.get('text') or ''))}
for glyph in _ocr_lines_to_page_characters(lines=ocr_lines)
if str(glyph.get('text') or '').strip()
]
band = _glyphs_in_header_band(
glyphs=ocr_glyphs, page_width=page_width, page_height=page_height,
primary_table_bbox=primary_table_bbox, source='ocr_coordinate',
)
if band:
return band, 'ocr_coordinate'
return None
except (ValueError, TypeError, KeyError, OSError):
return None
def rescue_match_with_header_ocr(
*,
match: ProfileMatchResult,
profiles: list[dict[str, Any]],
layout: dict[str, Any],
header_to_field: dict[str, str] | None,
document: Any,
match_fn: Callable[..., ProfileMatchResult] | None = None,
page_images_fn: Callable[[bytes], list[Any]] | None = None,
ocr_lines_fn: Callable[..., list[Any]] | None = None,
read_asset_fn: Callable[[int], bytes] | None = None,
) -> ProfileMatchResult:
"""
对路由失败结果尝试表头带证据补洞;任何不满足都原样返回(fail-closed)。
Args:
match: 常规匹配结果,须为 layout_drift / no_match 才尝试。
profiles: 冻结模板快照列表(与常规匹配同一份)。
layout: 已含原生坐标证据的运行期 Layout;禁止修改原对象。
header_to_field: Schema 表头别名契约(与常规匹配同源)。
document: ShippingOrderDocument;用于定位原始 PDF 资产。
match_fn / page_images_fn / ocr_lines_fn / read_asset_fn: 测试注入点,
默认分别使用真实匹配器、pdfium 渲染、RapidOCR 与资产读取。
Returns:
ProfileMatchResult:补洞成功返回带 identity_rescue_source 标记的唯一命中;
否则原样返回入参 match。
"""
if match.status not in {'layout_drift', 'no_match'} or not match.candidates:
return match
eligible = _eligible_rescue_candidates(
match=match, profiles=profiles, layout=layout, header_to_field=header_to_field,
)
if not eligible:
return match
try:
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
page = pages.get('1') or pages.get(1)
if not isinstance(page, dict):
return match
if read_asset_fn is None:
from app.services.file_assets.service import read_asset_bytes
read_asset_fn = read_asset_bytes
_, _, probe_observed = _candidate_header_atoms(
raw_profile=next(iter(eligible.values()))[1],
layout=layout,
header_to_field=header_to_field,
)
rescued_glyphs = _collect_rescue_glyphs(
document=document, page=page,
primary_table_bbox=probe_observed.get('primary_table_bbox'),
page_images_fn=page_images_fn, ocr_lines_fn=ocr_lines_fn,
read_asset_fn=read_asset_fn,
)
if not rescued_glyphs:
return match
band_glyphs, rescue_source = rescued_glyphs
page_key = '1'
page_glyphs = dict(evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {})
page_glyphs[page_key] = list(page_glyphs.get(page_key) or []) + band_glyphs
augmented = dict(layout)
augmented_evidence = {**evidence, 'page_glyphs': page_glyphs}
merged_sources = dict(augmented_evidence.get('sources') or {})
merged_page_sources = dict(merged_sources.get('pages') or {})
merged_page_sources[page_key] = f"pdf_coordinate+{rescue_source}"
merged_sources['pages'] = merged_page_sources
augmented_evidence['sources'] = merged_sources
augmented['coordinate_evidence'] = augmented_evidence
re_match_fn = match_fn if match_fn is not None else match_frozen_coordinate_profiles
rescued = re_match_fn(
profiles=profiles, layout=augmented, header_to_field=header_to_field,
)
if rescued.status not in {'unique_match', 'selected_by_score'}:
return match
winner_key = (str(rescued.profile_code or ''), int(rescued.version or 0))
if winner_key not in eligible:
# 补洞改变了竞争格局(唤醒了集合外候选)——维持原判。
return match
marked_candidates = [
item.model_copy(update={'identity_rescue_assisted': (
str(item.profile_code or ''), int(item.version or 0)) == winner_key
})
for item in rescued.candidates
]
return rescued.model_copy(update={
'identity_rescue_source': rescue_source,
'candidates': marked_candidates,
})
except (ValueError, TypeError, KeyError, OSError):
# 补救属锦上添花:任何数据/环境异常都回退原判,不阻断主链。
return match
@@ -866,6 +866,7 @@ def _build_snapshot(
)
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
from app.services.shipping_notice.generic_parse_plan import compile_generic_parse_plan
from app.services.shipping_notice.reservation_id import find_bare_numeric_reservation_candidates
table_contract = compile_table_header_contract(dict(schema_version.definition_json or {}))
generic_config = (
@@ -932,6 +933,14 @@ def _build_snapshot(
)
if isinstance(email_supplement, dict):
email_supplement['document_id'] = int(document.id)
# [裸数字兜底] 快照冻结前按当前正文重扫裸 5/10 位数字候选;
# 合并末段结合订单已提取字段值裁决,快照重建保证与 Schema 同源。
email_supplement['reservation_candidates'] = find_bare_numeric_reservation_candidates(
body_text=str(document.extracted_text or ''),
html_tables=html_tables,
content_hash=str(document.content_hash or ''),
)
email_supplement['email_subject'] = str(email.get('subject') or '')
document_snapshot = {
'document_id': document.id,
'document_type': document.document_type,
@@ -49,6 +49,9 @@ from app.services.shipping_notice.document_layout.order_profile_matcher import (
ProfileMatchResult,
match_frozen_coordinate_profiles,
)
from app.services.shipping_notice.document_layout.order_profile_ocr_rescue import (
rescue_match_with_header_ocr,
)
from app.services.shipping_notice.document_layout.order_profile_parse_validation import (
validate_profile_parse_candidate,
)
@@ -1078,6 +1081,16 @@ def _profile_table_candidates(
profiles=coordinate_profiles, layout=layout,
header_to_field=contract.header_to_field,
)
if (
match.status in {'layout_drift', 'no_match'}
and document_model is not None
):
# 表头带证据补洞:仅当存在「仅表头判别冲突 + 观测原子纯缺失」候选时
# 尝试;重跑完整匹配器且恰好唯一命中可补救候选才采纳,否则维持原判。
match = rescue_match_with_header_ocr(
match=match, profiles=coordinate_profiles, layout=layout,
header_to_field=contract.header_to_field, document=document_model,
)
affinity_applied = False
if not match_only:
match = _apply_parse_validation_gate(
@@ -4,6 +4,9 @@
逻辑:优先 PO+MPN;其次同 PO+合法 reservation_id 对齐;仅唯一签名的 PO 可降级广播;
无同 PO 候选时仅对「PO 缺失」行做唯一料号兜底(mpn_fallback);有 PO 且与 PDF
不一致则禁止补充。歧义只写复核原因。同趟单次合并,不互相重入。
主合并结束后另做「裸数字兜底」:仍无预约单号的订单,从正文裸 5/10 位数字
候选里排除已识别字段值/主题标签值/跨单已占用值,唯一候选以低置信度写入
header 默认值,多候选转为复核冲突,绝不覆盖任何已有值。
"""
from __future__ import annotations
@@ -13,7 +16,12 @@ from typing import Any
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value
from app.services.shipping_notice.po_number import normalize_atomic_po_number
from app.services.shipping_notice.reservation_id import validated_reservation_id
from app.services.shipping_notice.reservation_id import (
filter_reservation_heuristic_candidates,
normalize_reservation_id,
reservation_ids_in_labeled_context,
validated_reservation_id,
)
def _values(fields: Any, code: str, codes: dict[str, str]) -> set[str]:
@@ -273,6 +281,182 @@ def _supplement_multi_value_conflict(
}
def _iter_order_observation_values(order: dict[str, Any]) -> list[Any]:
"""收集订单头 + 全部行的原始字段 Observation 值,供兜底排除集使用。"""
values: list[Any] = []
field_groups: list[Any] = [order.get('header_fields')]
for line in order.get('lines') or []:
if isinstance(line, dict):
field_groups.append(line.get('fields'))
for fields in field_groups:
if not isinstance(fields, list):
continue
for field in fields:
if not isinstance(field, dict):
continue
for observation in field.get('observations') or []:
if isinstance(observation, dict) and observation.get('value') not in (None, ''):
values.append(observation.get('value'))
return values
def _heuristic_excluded_values(
order: dict[str, Any],
supplement: dict[str, Any],
) -> set[str]:
"""构造裸数字候选的排除集:订单已提取值 + 邮件补充行值 + 邮件主题标签值。
核心逻辑:客户 PO 号本身就是 10 位纯数字,是启发式最大的误判源;因此除了
订单 Observation 原值外,还纳入 Reservation/PO 两种归一变体(千分位、x.0、
前导零),并排除主题里「PO xxx」等带标签数字(Q10 双保险)。
"""
excluded: set[str] = set()
raw_values = _iter_order_observation_values(order)
rows = supplement.get('rows') if isinstance(supplement.get('rows'), list) else []
for row in rows:
if isinstance(row, dict):
raw_values.extend(str(value) for value in row.values() if str(value or '').strip())
for raw in raw_values:
text = str(raw).strip()
if text:
excluded.add(text.upper())
normalized = validated_reservation_id(normalize_reservation_id(raw))
if normalized:
excluded.add(normalized)
excluded.add(normalized.lstrip('0'))
po = normalize_atomic_po_number(raw)
if po:
excluded.add(po.upper())
excluded.add(po.lstrip('0').upper() or po.upper())
excluded.update(
value.upper()
for value in reservation_ids_in_labeled_context(str(supplement.get('email_subject') or ''))
)
return {value for value in excluded if value}
def _inject_reservation_heuristic(
fields: list[dict[str, Any]],
field_id: str,
value: str,
evidence: dict[str, Any],
document_id: int,
) -> None:
"""以裸数字兜底语义写入 reservation Observation:低置信度并携带 basis 标记。
与 _inject 的差异:confidence 固定 0.5(启发式,非权威证据),
email_supplement_evidence 增加 basis='bare_numeric_heuristic' 供复核端标注。
"""
target = next((item for item in fields if isinstance(item, dict) and item.get('field_id') == field_id), None)
observation = {
'value': value, 'document_id': document_id, 'quote': str(evidence.get('raw_value') or value),
'confidence': 0.5, 'email_supplement_evidence': {
'table_index': evidence.get('table_index'), 'row_index': evidence.get('row_index'),
'column_index': evidence.get('column_index'), 'cell_id': evidence.get('cell_id'),
'basis': 'bare_numeric_heuristic',
},
}
if target is None:
fields.append({'field_id': field_id, 'observations': [observation]})
else:
target['observations'] = [observation]
def _order_has_reservation_value(order: dict[str, Any], ids: dict[str, str]) -> bool:
"""判断订单头或任意行已存在预约单号取值(含非法格式原值);存在则兜底绝不写入。
按 Q2 契约「已有值永不覆盖」:即使原值未通过 5/10 位校验(如字母型编号),
也视为已有业务事实,只能走人工纠错,不能被裸数字猜测悄悄替换。
"""
reverse_ids = {v: k for k, v in ids.items()}
if _values(order.get('header_fields'), 'reservation_id', reverse_ids):
return True
for line in order.get('lines') or []:
if isinstance(line, dict) and _values(line.get('fields'), 'reservation_id', reverse_ids):
return True
return False
def _apply_reservation_heuristic(
order: dict[str, Any],
supplement: dict[str, Any],
*,
configs: dict[str, dict[str, Any]],
ids: dict[str, str],
schema_version: str,
claimed: set[str],
) -> None:
"""对仍无预约单号的订单执行裸数字兜底裁决(唯一→写入;多候选→冲突)。
核心逻辑:
[STEP 1] Schema 无 reservation_id 字段、候选键缺失或订单已有合法值 → 直接返回;
[STEP 2] 排除集 = 订单已提取值 ∪ 补充行值 ∪ 主题标签值 ∪ 跨单已占用(claimed);
[STEP 3] 唯一候选 → 按 Schema 作用域写入 header 默认值或缺失行,relation 标记
reservation_heuristic 供工作台补充状态展示;
[STEP 4] 多候选 → 复用 supplement_field_conflict 冲突结构(values + 逐候选
email_body 证据源),转现有字段冲突裁决面板,绝不自动挑值。
"""
config = configs.get('reservation_id')
field_id = ids.get('reservation_id')
candidates = supplement.get('reservation_candidates')
if config is None or not field_id or not isinstance(candidates, list) or not candidates:
return
if _order_has_reservation_value(order, ids):
return
excluded = _heuristic_excluded_values(order, supplement) | claimed
surviving, status = filter_reservation_heuristic_candidates(candidates, excluded_values=excluded)
if status == 'none':
return
document_id = int(supplement.get('document_id') or 0)
values = [str(item.get('value') or '') for item in surviving]
marker = {'status': status, 'values': values, 'document_id': document_id or None}
if status == 'unique':
value = validated_reservation_id(values[0])
if not value:
return
evidence = dict(surviving[0].get('evidence') or {})
if str(config.get('scope') or '') == 'header':
header_fields = order.get('header_fields')
if isinstance(header_fields, list):
_inject_reservation_heuristic(header_fields, field_id, value, evidence, document_id)
else:
# 行级写入只补真正缺失的行;带任何原值(含非法格式)的行不覆盖。
reverse_ids = {v: k for k, v in ids.items()}
for line in order.get('lines') or []:
if isinstance(line, dict) and isinstance(line.get('fields'), list):
if not _values(line['fields'], 'reservation_id', reverse_ids):
_inject_reservation_heuristic(line['fields'], field_id, value, evidence, document_id)
claimed.add(value)
marker['status'] = 'applied'
marker['value'] = value
if not str(order.get('_hxops_email_supplement_relation') or '').strip():
order['_hxops_email_supplement_relation'] = 'reservation_heuristic'
else:
pseudo_rows = [
{
'reservation_id': item.get('value'),
'table_index': (item.get('evidence') or {}).get('table_index'),
'row_index': (item.get('evidence') or {}).get('row_index'),
'evidence': {'reservation_id': dict(item.get('evidence') or {})},
}
for item in surviving
]
conflict = _supplement_multi_value_conflict(
field_code='reservation_id',
config=config,
values=set(values),
selected_rows=pseudo_rows,
line_index=-1,
email_document_id=document_id,
schema_version=schema_version,
)
if conflict not in order.setdefault('conflicts', []):
order['conflicts'].append(conflict)
if not str(order.get('_hxops_email_supplement_relation') or '').strip():
order['_hxops_email_supplement_relation'] = 'reservation_heuristic'
order['_hxops_reservation_heuristic'] = marker
def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_intake: dict[int, dict[str, Any]], schema_definition: dict[str, Any]) -> list[dict[str, Any]]:
"""
按冻结 Schema 逐字段合并正文事实,并对歧义订单附加复核冲突。
@@ -487,4 +671,18 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
})
order['_hxops_email_supplement_relation'] = relation
merged.append(order)
# [STEP] 裸数字兜底:主合并完成后仍无预约单号的订单,按排除规则裁决正文候选。
# 跨单 claimed 防止同一候选同时灌入多个订单;旧 Run 补充快照无候选键时整体跳过。
claimed_reservations: set[str] = set()
for order in merged:
supplement = supplements_by_intake.get(int(order.get('_hxops_intake_id') or 0))
if isinstance(supplement, dict) and isinstance(supplement.get('reservation_candidates'), list):
_apply_reservation_heuristic(
order,
supplement,
configs=configs,
ids=ids,
schema_version=schema_version,
claimed=claimed_reservations,
)
return merged
@@ -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'