fix(shipping-notice): 抽取收口纠正失败文档状态并修复 OCR 救援资产读取

- 抽取收口读取 Run 内 Unit 级失败事实:全部 Unit 失败的附件不再按零 pending 误写 completed
- EML 父项跟随 Run 结果收敛:终态 Run 禁止停留「处理中」,运行中仅区分解析失败与处理中
- OCR 救援资产读取修复:read_asset_bytes 接收 id 时按 FileAsset 加载字节,传参口径纠正
- 同步抽取/投影测试并新增工作台投影测试
This commit is contained in:
hugo committed 2026-10-14 22:40:37 +08:00
1 parent 92ed140739
commit 9f132564d6
8 files changed
+480 -39

No files matched your search

@@ -17,6 +17,7 @@ backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py
from __future__ import annotations
import logging
import unicodedata
from typing import Any, Callable
@@ -38,6 +39,8 @@ from app.services.shipping_notice.document_layout.order_profile import (
OrderCoordinateProfile,
)
logger = logging.getLogger(__name__)
# 与 ocr_pdf.OCR_CONFIDENCE_FLOOR 对齐;低于该置信度的 OCR 行不参与补洞。
OCR_RESCUE_CONFIDENCE_FLOOR = 0.8
# 表头带高度占主表高度的比例,与 _observe_header_candidates 的保守带一致。
@@ -194,6 +197,18 @@ def _text_to_char_glyphs(text: str, bbox: dict[str, float]) -> list[dict[str, An
return out
def _default_read_asset_bytes(asset_id: int) -> bytes:
"""按 id 加载 FileAsset 后读取字节;read_asset_bytes 接收 ORM 对象而非 id。"""
from app.extensions import db
from app.models import FileAsset
from app.services.file_assets.service import read_asset_bytes
asset = db.session.get(FileAsset, int(asset_id))
if asset is None:
raise LookupError(f'file asset not found: {asset_id}')
return read_asset_bytes(asset)
def _collect_rescue_glyphs(
*,
document: Any,
@@ -213,6 +228,8 @@ def _collect_rescue_glyphs(
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)
if read_asset_fn is None:
read_asset_fn = _default_read_asset_bytes
# [STEP 1] AcroForm/XFA 控件文本:确定性坐标与文本,优先于 OCR。
if asset_id > 0:
try:
@@ -247,9 +264,6 @@ def _collect_rescue_glyphs(
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,
@@ -296,7 +310,15 @@ def _collect_rescue_glyphs(
if band:
return band, 'ocr_coordinate'
return None
except (ValueError, TypeError, KeyError, OSError):
except Exception as exc: # noqa: BLE001 - 兜底来源失败时交回上层维持原判
# [PARAM_TUNING] 2026-10-14 test 事故(SNER-20261014-8EBAB7A1):AttributeError
# 炸穿本层令整个 Unit 技术失败。收口语义保持「静默回退」,但必须留观测痕
# 迹,否则只能靠 Unit error_message 反推。
logger.warning(
'order profile rescue glyphs failed document_id=%s error_type=%s',
int(getattr(document, 'id', 0) or 0),
type(exc).__name__,
)
return None
@@ -341,9 +363,6 @@ def rescue_match_with_header_ocr(
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,
@@ -390,6 +409,10 @@ def rescue_match_with_header_ocr(
'identity_rescue_source': rescue_source,
'candidates': marked_candidates,
})
except (ValueError, TypeError, KeyError, OSError):
# 补救属锦上添花:任何数据/环境异常都回退原判,不阻断主链。
except Exception as exc: # noqa: BLE001 - 补救属锦上添花:任何异常(含 AttributeError 等未预期类型错误)都回退原判,不得阻断抽取主链。
logger.warning(
'order profile rescue aborted document_id=%s error_type=%s',
int(getattr(document, 'id', 0) or 0),
type(exc).__name__,
)
return match
@@ -311,6 +311,51 @@ def _resolve_automatic_acceptance(raw_order: dict[str, Any]) -> dict[str, str] |
return dict(_AUTOMATIC_ACCEPTANCE_BY_MARKER[marker]) if marker in _AUTOMATIC_ACCEPTANCE_BY_MARKER else None
def _failed_unit_errors_by_document(run_id: int | None) -> dict[int, dict[str, str | None]]:
"""
读取 Run 内 Unit 级失败事实(document_id → 错误码/消息),供收口裁决纠正文档级状态。
核心逻辑:persist 的候选裁决只知道「有没有 pending」,不知道 Unit 是否技术失败;
Unit 全失败的附件没有任何产出裁决,禁止按零 pending 误写 completed
(回归 SNER-20261014-8EBAB7A1:9 Unit 全失败仍整批 completed,批次中心误报通知完成)。
Args:
run_id: ShippingOrderProcessingRun 主键;为空时返回空表(领域单测路径)。
Returns:
document_id → {'error_code', 'error_message'} 映射。
"""
if run_id is None:
return {}
from app.models import ShippingOrderProcessingPlan, ShippingOrderProcessingUnit
rows = (
db.session.query(
ShippingOrderProcessingUnit.document_id,
ShippingOrderProcessingUnit.error_code,
ShippingOrderProcessingUnit.error_message,
)
.join(
ShippingOrderProcessingPlan,
ShippingOrderProcessingPlan.id == ShippingOrderProcessingUnit.plan_id,
)
.filter(
ShippingOrderProcessingPlan.run_id == int(run_id),
ShippingOrderProcessingUnit.status == 'failed',
ShippingOrderProcessingUnit.document_id.isnot(None),
)
.all()
)
return {
int(document_id): {
'error_code': str(error_code or '').strip() or 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED',
'error_message': str(error_message or '').strip() or 'Order extraction unit failed',
}
for document_id, error_code, error_message in rows
if document_id is not None
}
def persist_order_extraction_result(
*,
session: ChatSession,
@@ -794,21 +839,31 @@ def persist_order_extraction_result(
# [STEP 2] 聚合 Document 结果;无法归属到 Intake 的异常项会使本轮全部 Document 保持部分完成。
has_unassigned_pending = any(not item.get('source_intake_no') for item in pending)
# Unit 失败事实优先:Unit 失败且无候选/待处理裁决的附件,识别并未完成,
# 必须落 failed(携带 Unit 错误码),禁止按「零 pending」误写 completed——
# 否则随后的 Run 失败收口会因「已是终态」跳过回填,批次中心误报已完成。
failed_unit_error_by_document = _failed_unit_errors_by_document(run_id)
for document in documents:
keys = document_candidate_keys[int(document.id)]
document.order_extraction_status = (
'partially_completed'
if document_has_pending[int(document.id)] or has_unassigned_pending
else 'completed'
)
unit_failure = failed_unit_error_by_document.get(int(document.id))
if unit_failure and not keys and not document_has_pending[int(document.id)]:
document.order_extraction_status = 'failed'
document.order_extraction_error_code = unit_failure['error_code']
document.order_extraction_error_message = unit_failure['error_message']
else:
document.order_extraction_status = (
'partially_completed'
if document_has_pending[int(document.id)] or has_unassigned_pending
else 'completed'
)
document.order_extraction_error_code = None
document.order_extraction_error_message = None
document.order_extraction_source = extraction_source
document.order_extraction_result_json = {
'request_id': request_id,
'candidate_keys': keys,
'non_shipping_order_indexes': document_non_shipping_indexes[int(document.id)],
}
document.order_extraction_error_code = None
document.order_extraction_error_message = None
# [STEP 3] 只对本次 documents 作用域内消失的 Candidate 做版本失效。
# Unit 增量提交仅带当前 PDF,禁止把同 Intake/Run 的兄弟 PDF Candidate
@@ -836,13 +891,32 @@ def persist_order_extraction_result(
duplicate_results_by_intake.get(int(intake.id), []),
)
apply_duplicate_result_to_intake(intake, aggregate)
intake.order_extraction_status = (
'partially_completed'
if pending_by_intake[int(intake.id)] or has_unassigned_pending
else 'completed'
# Intake 聚合文档级终态:全部业务附件 failed → failed;部分失败 → partially_completed;
# 二者都不得被后续「零 pending 即 completed」的收口覆盖。
intake_documents = documents_by_intake.get(int(intake.id)) or []
failed_intake_documents = [
document
for document in intake_documents
if str(document.order_extraction_status or '').strip().lower() == 'failed'
]
business_document_count = sum(
1
for document in intake_documents
if str(document.document_type or '').strip().lower() != 'email_body'
)
intake.order_extraction_error_code = None
intake.order_extraction_error_message = None
if failed_intake_documents and business_document_count > 0 \
and len(failed_intake_documents) >= business_document_count:
intake.order_extraction_status = 'failed'
intake.order_extraction_error_code = failed_intake_documents[0].order_extraction_error_code
intake.order_extraction_error_message = failed_intake_documents[0].order_extraction_error_message
elif failed_intake_documents or pending_by_intake[int(intake.id)] or has_unassigned_pending:
intake.order_extraction_status = 'partially_completed'
intake.order_extraction_error_code = None
intake.order_extraction_error_message = None
else:
intake.order_extraction_status = 'completed'
intake.order_extraction_error_code = None
intake.order_extraction_error_message = None
intake.updated_at = datetime.utcnow()
db.session.flush()
@@ -1001,7 +1075,13 @@ def persist_order_extraction_result(
for intake in intakes:
intake.parse_status = 'consumed'
intake.consumed_at = now
intake.order_extraction_status = 'completed'
# consumed 仅代表「邮件解析结果已被抽取收口消费」;文档/Intake 级
# order_extraction_status 若已按 Unit 失败裁决为 failed/partially_completed,
# 不得在此覆盖回 completed——否则 Run 失败收口会因「已是终态」跳过回填。
if str(intake.order_extraction_status or '').strip().lower() not in {
'failed', 'partially_completed',
}:
intake.order_extraction_status = 'completed'
intake.updated_at = now
db.session.commit()
@@ -498,7 +498,21 @@ def _email_parent_rows(
if document_id <= 0 or document_id in existing_document_ids:
continue
parse_status = parse_statuses.get(intake_id, '')
parent_status = 'failed' if parse_status == 'parse_failed' else 'processing'
run_status = str(run.status or '').strip().lower()
if run_status in {'queued', 'processing'}:
# 运行中的 Run:EML 父项只区分解析失败与处理中。
parent_status = 'failed' if parse_status == 'parse_failed' else 'processing'
else:
# [STEP] 终态 Run 的 EML 父项必须跟随 Run 结果收敛,禁止停留在「处理中」
# (历史缺陷:全部 Unit 失败后父项仍显示处理中,误导用户批次仍在进行)。
# partially_completed 的用户语义与 review_required 一致(需人工处理)。
parent_status = {
'failed': 'failed',
'cancelled': 'cancelled',
'completed': 'completed',
'review_required': 'review_required',
'partially_completed': 'review_required',
}.get(run_status, 'failed')
rows.append({
'unit_id': -document_id,
'document_id': document_id,
@@ -4263,14 +4263,17 @@ def project_conversation_processing_summary(
if case.run_id is not None
)
# 订单抽取失败且尚无 Candidate/Case/OT 时,仍需最新 Run 身份供重解析;
# 仅 load id/run_no,不触碰 Plan/Unit。
# 仅 load id/run_no/status/error_code,不触碰 Plan/Unit。status/error_code
# 供摘要把「抽取收口 completed 但最新 Run 失败」的文档纠正为失败裁决。
latest_run_by_intake_id: dict[int, Any] = {}
if intake_ids:
for intake_id, run_id, run_no in (
for intake_id, run_id, run_no, run_status, run_error_code in (
db.session.query(
ShippingOrderProcessingRunIntake.intake_id,
ShippingOrderProcessingRun.id,
ShippingOrderProcessingRun.run_no,
ShippingOrderProcessingRun.status,
ShippingOrderProcessingRun.error_code,
)
.join(
ShippingOrderProcessingRun,
@@ -4287,7 +4290,12 @@ def project_conversation_processing_summary(
key = int(intake_id)
if key in latest_run_by_intake_id:
continue
latest_run_by_intake_id[key] = {'id': int(run_id), 'run_no': str(run_no or '').strip()}
latest_run_by_intake_id[key] = {
'id': int(run_id),
'run_no': str(run_no or '').strip(),
'status': str(run_status or '').strip().lower(),
'error_code': str(run_error_code or '').strip() or None,
}
run_ids.add(int(run_id))
runs_by_id = {
int(run.id): run
@@ -4455,7 +4463,25 @@ def project_conversation_processing_summary(
if raw in {'review_required', 'waiting_review', 'pending_review', 'waiting_human'}:
return 'waiting_human', 'waiting_review' if stage == 'candidate_creating' else stage, 'waiting_review'
if raw in {'completed', 'uploaded'}:
return 'completed', 'completed', None
# 文档级 completed 只代表「抽取收口完成」,不是业务终态:通知完成必须
# 以正式 OT/Notice/上传核验为前提,禁止把收口语义译成通知完成
# (回归 SNER-20261014-8EBAB7A1:9 Unit 全失败仍整批 completed,
# 批次中心据此误报 9/9 已完成 + 通知完成)。
if task is not None:
return 'completed', 'completed', None
if case is not None and case_status == 'non_order':
# 非订单处置是唯一无 OT 的合法业务完成出口。
return 'completed', 'completed', None
latest_intake_run = latest_run_by_intake_id.get(int(document.intake_id)) or {}
if str(latest_intake_run.get('status') or '').strip().lower() == 'failed':
# 收口 completed 但最新 Run 失败(含历史脏数据):按失败裁决并提供重解析。
return (
'failed',
stage,
str(latest_intake_run.get('error_code') or '') or 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED',
)
# 无 OT/无处置的收口完成与全量视图同判词:停接收解析(处理中)。
return 'running', stage, None
if raw in {'cancelled', 'archived'}:
return raw, raw, None
return 'running', stage, None
@@ -4499,9 +4525,22 @@ def project_conversation_processing_summary(
stage = 'candidate_creating'
case_status = str(getattr(case, 'status', None) or '').strip().lower()
terminal_case = case_status in {'confirmed', 'non_order', 'superseded', 'reparse_pending'}
extraction_failed = str(document.order_extraction_status or '').strip().lower() in {
'failed', 'parse_failed', 'technical_retrying',
}
# 抽取失败事实除文档级状态外,还认「无 OT/无 Case 且最新 Run 失败」:
# 历史/并发脏数据可能把 Unit 全失败的附件写成 completed(抽取收口语义),
# 此时仍必须下发重解析入口,与 _status 的失败裁决同源。
latest_intake_run_status = str(
(latest_run_by_intake_id.get(int(document.intake_id)) or {}).get('status') or ''
).strip().lower()
extraction_failed = (
str(document.order_extraction_status or '').strip().lower() in {
'failed', 'parse_failed', 'technical_retrying',
}
or (
task is None
and case is None
and latest_intake_run_status == 'failed'
)
)
task_no = str(task.task_no).strip() if task is not None else None
available_actions: list[str] = []
primary_action: dict[str, Any] | None = None